-
Notifications
You must be signed in to change notification settings - Fork 4
/
plots_SPB.py
2410 lines (1664 loc) · 80 KB
/
plots_SPB.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
#from numpy import * # imported below at np
from scipy import *
import mpmath
import cmath
from scipy.special import sph_harm
from scipy.spatial import Delaunay
from scipy.sparse import csgraph
# For Plotting: (import once for all fns below)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
from matplotlib import cm
matplotlib.use('agg'); # This allows for headless plotting (changes plt.show() so non-modal...)
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import matplotlib.pyplot as mpl
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['ps.fonttype'] = 42
#mpl.rcParams['lines.linewidth'] = .25
#import mayavi.mlab as ml #NOT Supported in python 3.6 yet
import numpy as np
import scipy as sp
#for pickling:
#import cPickle as pkl # BJG: py2pt7 version
import pickle as pkl
import os, sys
#for timestamp:
import datetime as dt
from charts_SPB import *
from sph_func_SPB import *
import euc_k_form_SPB as euc_kf
import lebedev_write_SPB as leb_wr
import lbdv_info_SPB as lbdv_i
import itertools # for sorting
# For new meshing:
import vtk
#Create Plot of Function
def Plot_Func(func, Theta_Res, Phi_Res, Theta_Min, Theta_Max, Phi_Min, Phi_Max, Plot_Title):
Theta_Test_Vals = linspace(Theta_Min, Theta_Max, Theta_Res, endpoint = False)
Phi_Test_Vals = linspace(Phi_Min, Phi_Max, Phi_Res)
#linspace(pi/(Phi_Res+1), pi, Phi_Res, endpoint = False)
fig = plt.figure()
ax = fig.gca(projection='3d')
X = Theta_Test_Vals #np.arange(-5, 5, 0.25)
Y = Phi_Test_Vals #np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
#R = np.sqrt(X**2 + Y**2)
Z = zeros([Phi_Res, Theta_Res])
for x in range(Theta_Res):
for y in range(Phi_Res):
Z[y][x] = func(Theta_Test_Vals[x], Phi_Test_Vals[y])
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_zlim(amin(Z), amax(Z))
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_xlabel('Theta')
ax.set_ylabel('Phi')
ax.set_zlabel("func")
fig.suptitle(Plot_Title, fontsize=20)
plt.show()
#Create Appropriate Error Plots
def Error_Plots(func1, func2, func3, Theta_Res, Phi_Res, Theta_Min, Theta_Max, Phi_Min, Phi_Max, Title1, Title2, Title3):
Plot_Func(lambda theta, phi: func1(theta, phi)-func2(theta, phi), Theta_Res, Phi_Res, Theta_Min, Theta_Max, Phi_Min, Phi_Max, "("+str(Title1)+") - ("+str(Title2)+")")
Plot_Func(lambda theta, phi: func1(theta, phi)-func3(theta, phi), Theta_Res, Phi_Res, Theta_Min, Theta_Max, Phi_Min, Phi_Max, "("+str(Title1)+") - ("+str(Title3)+")")
Plot_Func(lambda theta, phi: func2(theta, phi)-func3(theta, phi), Theta_Res, Phi_Res, Theta_Min, Theta_Max, Phi_Min, Phi_Max, "("+str(Title2)+") - ("+str(Title3)+")")
# Shows Quad Pts used for collocation in Least Sqaures approach
def Show_Quad_Pts_Used(fixed_ls_colloc_pts, lbdv):
#x = Fixed_LS_Colloc_Pts[:,0]
#y = Fixed_LS_Colloc_Pts[:,1]
#colors = np.ones(generated_fixed_ls_colloc_pts)
#area = np.pi*np.ones(generated_fixed_ls_colloc_pts)
#plt.scatter(x, y, s=area, c=colors, alpha=0.5)
#plt.show()
x1 = fixed_ls_colloc_pts[:,0]
y1 = fixed_ls_colloc_pts[:,1]
x2 = lbdv.Lbdv_Sph_Pts_Quad[:, 0]
y2 = lbdv.Lbdv_Sph_Pts_Quad[:, 1]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(x1, y1, s=10, c='b', marker="s", label='used')
ax1.scatter(x2,y2, s=5, c='r', marker="o", label='not used')
plt.legend(loc='upper left');
plt.show()
#Plots Errors of SPH functions vs exact function at the quad pts
def Plot_Errors_At_Quad_Pts(Plot_Title, vals_at_quad_pts, exact_func, lbdv):
#Theta_Test_Vals = linspace(Theta_Min, Theta_Max, Theta_Res, endpoint = False)
#Phi_Test_Vals = linspace(Phi_Min, Phi_Max, Phi_Res)
#linspace(pi/(Phi_Res+1), pi, Phi_Res, endpoint = False)
fig = plt.figure()
ax = fig.gca(projection='3d')
#X = Theta_Test_Vals #np.arange(-5, 5, 0.25)
#Y = Phi_Test_Vals #np.arange(-5, 5, 0.25)
#X, Y = np.meshgrid(X, Y)
#R = np.sqrt(X**2 + Y**2)
X, Y, W = hsplit(lbdv.Lbdv_Sph_Pts_Quad, 3)
Z = zeros(shape(X))
for q in range(lbdv.lbdv_quad_pts):
theta = X[q]
phi = Y[q]
#Z[q] = lbdv.Eval_SPH_Der_Phi_At_Quad_Pts(0,1, q) - exact_func(theta, phi)
Z[q] = vals_at_quad_pts[q] - exact_func(theta, phi)
ax.scatter(X, Y, Z, c='r', marker='o')
ax.set_zlim(amin(Z), amax(Z))
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.set_xlabel('Theta')
ax.set_ylabel('Phi')
ax.set_zlabel("Error at Quad Pts (exact - sph)")
fig.suptitle(Plot_Title, fontsize=20)
plt.show()
#Used to plot results of Convergence Loop, in log-log and semi-log plots:
def Plot_Conv_Results(conv_title, q_vals, p_refs, errors):
plt.subplots_adjust(hspace=0.4)
plt.suptitle(str(conv_title)+" Convergence", fontsize=12)
## Log(Error) vs Quad Pts:
#fit_exp_Q = polyfit(q_vals, log(errors), 1)
#print("exp fit for Q = "+str(fit_exp_Q))
#fit_exp_Q_fn = poly1d(fit_exp_Q)
#print("fit vals ="+str(fit_exp_Q_fn(q_vals)))
plt.subplot(221)
plt.semilogy(q_vals, errors + np.finfo(float).eps/2, '-o')
#plt.plot(q_vals, fit_exp_Q_fn(q_vals), 'r-')
plt.title('log(Error) vs Quad Pts')
plt.grid(True)
plt.subplot(222)
plt.loglog(q_vals, errors + np.finfo(float).eps/2, '-o')
plt.grid(True)
plt.title('log(Error) vs log(Quad Pts)')
plt.subplot(223)
plt.semilogy(p_refs, errors + np.finfo(float).eps/2, '-o')
plt.grid(True)
plt.title('log(Error) vs P-Refinement')
plt.subplot(224)
plt.loglog(p_refs, errors + np.finfo(float).eps/2, '-o')
plt.grid(True)
plt.title('log(Error) vs log(P-Refinement)')
plt.show()
#Used to plot results of Convergence Loop, in log-log and semi-log plots, if P_Ref is the same, but R_0 Changes:
def Plot_Conv_Results_Const_P_Ref(conv_title, q_val, p_ref, r0_vals, errors):
fig = plt.figure()
plt.subplots_adjust(hspace=0.4)
plt.suptitle(str(conv_title)+" Convergence for P = "+str(p_ref)+"and Q = "+str(q_val), fontsize=12)
plt.subplot(211)
plt.semilogy(r0_vals, errors + np.finfo(float).eps/2, '-o')
plt.title('log(Error) vs R_0')
plt.grid(True)
plt.subplot(212)
plt.loglog(r0_vals, errors + np.finfo(float).eps/2, '-o')
plt.grid(True)
plt.title('log(Error) vs log(R_0)')
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = str(conv_title)+"_Convergence"+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
# Pickled Plot Data in Pickled_Data:
Picked_Data_DIR = os.path.join(MY_DIR, 'Pickled_Data')
Data_Dictionary = {}
Data_Dictionary['Plot_Title'] = conv_title
Data_Dictionary['Quad_Refinement'] = q_val
Data_Dictionary['P_Refinement'] = p_ref
Data_Dictionary['Relative_Errors'] = errors
Data_Dictionary['R_0_Values'] = r0_vals
Dictionary_Name = str(conv_title)+"_dictionary"+str(Time_and_Date_Str())+".pickle"
dictionary_path = os.path.join(Picked_Data_DIR, Dictionary_Name)
with open(dictionary_path, 'wb') as dict_file:
pkl.dump(Data_Dictionary, dict_file)
#Used to plot UNSCALED DATA, if P_Ref is the same, but R_0 Changes:
def Plot_Data_Const_P_Ref(conv_title, q_val, p_ref, r0_vals, data):
fig = plt.figure()
plt.subplots_adjust(hspace=0.4)
plt.suptitle(str(conv_title)+" Data for P = "+str(p_ref)+"and Q = "+str(q_val), fontsize=12)
plt.subplot(111)
plt.plot(r0_vals, data, '-o')
plt.title('Data vs R_0')
plt.grid(True)
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = str(conv_title)+"_Data"+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
# Pickled Plot Data in Pickled_Data:
Picked_Data_DIR = os.path.join(MY_DIR, 'Pickled_Data')
Data_Dictionary = {}
Data_Dictionary['Plot_Title'] = conv_title
Data_Dictionary['Quad_Refinement'] = q_val
Data_Dictionary['P_Refinement'] = p_ref
Data_Dictionary['Data'] = data
Data_Dictionary['R_0_Values'] = r0_vals
Dictionary_Name = str(conv_title)+"_dictionary"+str(Time_and_Date_Str())+".pickle"
dictionary_path = os.path.join(Picked_Data_DIR, Dictionary_Name)
with open(dictionary_path, 'wb') as dict_file:
pkl.dump(Data_Dictionary, dict_file)
#Used to plot results with variotion of parameter of Convergence Loop, in log-log and semi-log plots:
def Plot_Param_Conv_Results(conv_title, q_vals, p_refs, errors, Param_Values, Param_Name):
fig = plt.figure()
plt.subplots_adjust(hspace=0.4)
plt.suptitle(str(conv_title)+" Convergence", fontsize=12)
## Log(Error) vs Quad Pts:
#fit_exp_Q = polyfit(q_vals, log(errors), 1)
#print("exp fit for Q = "+str(fit_exp_Q))
#fit_exp_Q_fn = poly1d(fit_exp_Q)
#print("fit vals ="+str(fit_exp_Q_fn(q_vals)))
labels = array([]) #label by param value
# plot for each parameter value
for param_iter in range(len(Param_Values)):
Param_val = Param_Values[param_iter]
errors_param = []
if(len(Param_Values) > 1):
errors_param = errors[:, param_iter]
else:
errors_param = errors
plt.subplot(221)
plt.semilogy(q_vals, errors_param + np.finfo(float).eps/2, '-o', label= Param_Name+" = "+str(Param_val))
#plt.plot(q_vals, fit_exp_Q_fn(q_vals), 'r-')
plt.title('log(Error) vs Quad Pts')
plt.grid(True)
plt.subplot(222)
plt.loglog(q_vals, errors_param + np.finfo(float).eps/2, '-o', label=Param_Name+" = "+str(Param_val))
plt.grid(True)
plt.title('log(Error) vs log(Quad Pts)')
plt.subplot(223)
plt.semilogy(p_refs, errors_param + np.finfo(float).eps/2, '-o', label= Param_Name+" = "+str(Param_val))
plt.grid(True)
plt.title('log(Error) vs P-Refinement')
plt.subplot(224)
plt.loglog(p_refs, errors_param + np.finfo(float).eps/2, '-o', label= Param_Name+" = "+str(Param_val))
plt.grid(True)
plt.title('log(Error) vs log(P-Refinement)')
labels = concatenate(( labels, [Param_Name+" = "+str(Param_val)] ))
plt.legend(labels, loc='upper right') #show legend
plt.legend(bbox_to_anchor=(1.25, 1.25))
#mng = plt.get_current_fig_manager() #We want to save maximized image, need wx backend
#mng.window.showMaximized()
#plt.show() #plotting stops the code
# Pickle Result in Pickled_Images:
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = str(conv_title)+"_Convergence"+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
# Pickled Plot Data in Pickled_Data:
Picked_Data_DIR = os.path.join(MY_DIR, 'Pickled_Data')
Data_Dictionary = {}
Data_Dictionary['Plot_Title'] = conv_title
Data_Dictionary['Quad_Refinement'] = q_vals
Data_Dictionary['P_Refinement'] = p_refs
Data_Dictionary['Relative_Errors'] = errors
Data_Dictionary['Parameter_Values'] = Param_Values
Data_Dictionary['Parameter_Name'] = Param_Name
Dictionary_Name = str(conv_title)+"_dictionary"+str(Time_and_Date_Str())+".pickle"
dictionary_path = os.path.join(Picked_Data_DIR, Dictionary_Name)
with open(dictionary_path, 'wb') as dict_file:
pkl.dump(Data_Dictionary, dict_file)
#Used to plot results with variotion of parameter of Convergence Loop, in log-log and semi-log plots:
def Plot_Histograms(conv_title, errors):
fig = plt.figure()
plt.suptitle(str(conv_title)+" Error Histogram", fontsize=12)
plt.hist(errors)
# Pickle Result in Pickled_Images:
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = str(conv_title)+"_Error_Hist"+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
#Used to plot mean curvature pdf and cdf for Droplet codes:
def Plot_Histograms(plot_title, X_prob, hist_dist, sorted_distr, delta, min_curv_excl, max_curv_excl, Input_Dir=[]):
fig = plt.figure()
plt.suptitle(str(plot_title), fontsize=12)
plt.title("CDF of "+str(plot_title))
num_data_pts = len(sorted_distr)
weights_pdf = np.ones_like(sorted_distr)/float(num_data_pts)
num_bins = num_data_pts
if(num_data_pts > 40.):
num_bins = int(num_data_pts/20)
plt.subplot(221)
plt.hist(sorted_distr, weights=weights_pdf, bins=num_bins, label = 'PDF', color = "purple") # can't use bins = 'auto' with weights
plt.axvline(x=min_curv_excl, label= "min val excl = "+str(min_curv_excl)+", for delta = "+str(delta), c='red')
plt.axvline(x=max_curv_excl, label= "max val excl = "+str(max_curv_excl)+", for delta = "+str(delta), c='blue')
plt.legend(loc='upper center', bbox_to_anchor=(0.45, -0.1), prop={'size': 6})
#plt.plot(X_prob, hist_dist.ppf(X_prob), label='PPF')
plt.subplot(222)
plt.plot(X_prob, hist_dist.cdf(X_prob), label='CDF', c='green')
plt.axvline(x=min_curv_excl, label= "min val excl = "+str(min_curv_excl)+", for delta = "+str(delta), c='red')
plt.axvline(x=max_curv_excl, label= "max val excl = "+str(max_curv_excl)+", for delta = "+str(delta), c='blue')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), prop={'size': 6})
# Pickle Result in Pickled_Images:
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
if(Input_Dir != []):
Picked_Image_DIR = Input_Dir
fig_name = str(plot_title)+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
#Used to plot mean curvature pdf ONLY Droplet codes:
def Plot_Histogram_PDF(plot_title, distr_vals, Input_Dir=[]):
sorted_distr = np.sort(distr_vals)
median_val = np.median(sorted_distr) # plot mean and median
mean_val = np.average(sorted_distr)
fig = plt.figure()
plt.suptitle(str(plot_title), fontsize=12)
plt.title("PDF of "+str(plot_title))
num_data_pts = len(sorted_distr)
weights_pdf = np.ones_like(sorted_distr)/float(num_data_pts)
num_bins = num_data_pts
if(num_data_pts > 10.):
num_bins = int(num_data_pts/5.)
plt.hist(sorted_distr, weights=weights_pdf, bins=num_bins, label = 'PDF', color = "purple") # can't use bins = 'auto' with weights
plt.axvline(x=median_val, label= "median = "+str(median_val), c='red')
plt.axvline(x=mean_val, label= "mean = "+str(mean_val), c='blue')
plt.legend(loc='upper center', bbox_to_anchor=(0.45, -0.1), prop={'size': 6})
# Pickle Result in Pickled_Images:
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
if(Input_Dir != []):
Picked_Image_DIR = Input_Dir
fig_name = str(plot_title)+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
#Used to plot JUST CDF:
def Plot_Histogram_CDF_ONLY(plot_title, X_pts, sorted_normalized_distr, Input_Dir = []):
fig = plt.figure()
plt.suptitle(str(plot_title), fontsize=12)
plt.title("CDF of "+str(plot_title))
plt.plot(X_pts, np.cumsum(sorted_normalized_distr), label='CDF', c='green')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), prop={'size': 6})
# Pickle Result in Pickled_Images:
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
if(Input_Dir != []):
Picked_Image_DIR = Input_Dir
fig_name = str(plot_title)+str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
#Plots errors as function of BOTH (p_deg, q_deg)
def Plot_Multi_Conv_Results(multi_conv_title, q_vals, q_degs, p_degs, errors):
p_refs = np.square(p_degs + 1) #Number of basis elements
labels = array([]) #label convergence by basis degree
#plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])
plt.subplot(221)
plt.grid(True)
for p in range(len(p_degs)):
clr = plt.cm.YlOrBr(np.float64(p+1)/(len(p_degs)+1)) #different color for each degree plot
plt.loglog(q_degs, errors[p,:], '-o', color = clr) #plot for different quads used
str_lbl_p = str(p_degs[p]) #label by degree
labels = concatenate(( labels, ["p_deg ="+str_lbl_p] )) #add to labels
plt.legend(labels, loc='upper right') #show legend
plt.title('log(Error) vs log(Quad Degree)')
plt.subplot(222)
plt.grid(True)
for p in range(len(p_degs)):
clr = plt.cm.YlOrBr(np.float64(p+1)/(len(p_degs)+1)) #different color for each degree plot
plt.semilogy(q_degs, errors[p,:], '-o', color = clr) #plot for different quads used
str_lbl_p = str(p_degs[p]) #label by degree
labels = concatenate(( labels, ["p_deg ="+str_lbl_p] )) #add to labels
plt.legend(labels, loc='upper right') #show legend
plt.title('log(Error) vs Quad Degree')
plt.subplot(223)
plt.grid(True)
for p in range(len(p_degs)):
clr = plt.cm.YlOrBr(np.float64(p+1)/(len(p_degs)+1)) #different color for each degree plot
plt.loglog(q_vals, errors[p,:], '-o', color = clr) #plot for different quads used
str_lbl_p = str(p_degs[p]) #label by degree
labels = concatenate(( labels, ["p_deg ="+str_lbl_p] )) #add to labels
plt.legend(labels, loc='upper right') #show legend
plt.title('log(Error) vs log(Quad Pts)')
plt.subplot(224)
plt.grid(True)
for p in range(len(p_degs)):
clr = plt.cm.YlOrBr(np.float64(p+1)/(len(p_degs)+1)) #different color for each degree plot
plt.semilogy(q_vals, errors[p,:], '-o', color = clr) #plot for different quads used
str_lbl_p = str(p_degs[p]) #label by degree
labels = concatenate(( labels, ["p_deg ="+str_lbl_p] )) #add to labels
plt.legend(labels, loc='upper right') #show legend
plt.title('log(Error) vs Quad Pts')
plt.show()
# Plot 2-param values for fig 2 membrane flow paper:
def plot_mem_flows_fig2(manny_label, param_vals, dep_field_vals, indep_var_vals):
'''
param_val = list(delta_vals, beta_val (USE .6), gamma_vals, epsilon_vals)
dep_field_vals = (num_r0 (\delta), num_beta, num_gamma, num_eps, 3 {\V\|, T, k_D}, num_quad_pts (Q)
indep_var_vals = {K, arclen} for each r_0, shape: {num_r0, Q, 2}
'''
num_quad_pts_to_plot = indep_var_vals.shape[1]
mk_size = 200./num_quad_pts_to_plot
delta_vals = param_vals[0]
num_delta_vals = len(delta_vals)
beta_val_used = param_vals[1][0] # WE ONLY HAVE ONE
gamma_vals = param_vals[2]
num_gamma_vals = len(gamma_vals)
epsilon_vals = param_vals[3]
num_epsilon_vals = len(epsilon_vals)
num_plots_per_subplot = num_gamma_vals*num_epsilon_vals # plots of params on each subplot
num_plots = num_delta_vals*3
fig = plt.figure(figsize=(8.5, 8.5))
plt.subplots_adjust(hspace=0.4)
fig_title = manny_label +"_beta_"+str(beta_val_used).replace(".", "pt")+ "_mem_flow_paper_fig2_"
#plt.suptitle(fig_title, fontsize=12, y=1.08) # plt.title(figure_title, y=1.08)
plot_num = 1
labels = array([]) #label by param value
# find maximum V for plot scale, and min and max T for each delta:
max_V_mag = 0.
T_min_delta = np.zeros(( num_delta_vals ))
T_max_delta = np.zeros(( num_delta_vals ))
for delta_i in range(num_delta_vals):
T_append = np.array([])
for epsilon_i in range(num_epsilon_vals):
for gamma_i in range(num_gamma_vals):
V_r0, T_r0, k_D_r0 = np.hsplit( np.squeeze(dep_field_vals[delta_i, 0, gamma_i, epsilon_i, :, :]), 3)
T_append = np.concatenate(( T_append, T_r0.flatten() ))
max_V_r0 =max(V_r0)
if(max_V_mag < max_V_r0):
max_V_mag = max_V_r0
T_min_delta[delta_i] = min(T_append)
T_max_delta[delta_i] = max(T_append)
print("for delta_i = "+str(delta_i)+", T_min_delta[delta_i] = "+str(T_min_delta[delta_i] )+", T_max_delta[delta_i] = "+str(T_max_delta[delta_i] )+", T_append = "+str(np.sort(T_append)) )
for delta_i in range(num_delta_vals):
delta_val_i = param_vals[0][delta_i]
arclens_used = indep_var_vals[delta_i, :, 1]
inds_arclens_used_sort = arclens_used.argsort() # we need to sort these to connect plot lines
arclens_used_sorted = np.sort(arclens_used)
color_i = 0
for epsilon_i in range(num_epsilon_vals):
epsilon_val_i = epsilon_vals[epsilon_i]
for gamma_i in range(num_gamma_vals):
gamma_val_i = gamma_vals[gamma_i]
V_r0, T_r0, k_D_r0 = np.hsplit( np.squeeze(dep_field_vals[delta_i, 0, gamma_i, epsilon_i, :, :]), 3)
V_r0_sorted = V_r0[inds_arclens_used_sort] # sort these by arclength from exo pt
T_r0_sorted = T_r0[inds_arclens_used_sort]
k_D_r0_sorted = k_D_r0[inds_arclens_used_sort]
clr = plt.cm.tab10(np.float64(color_i+1)/(num_plots_per_subplot+1)) #different color for each params
if(delta_i == 0):
labels = concatenate(( labels, ['$\gamma$ ='+str(gamma_val_i)+', $\epsilon$ = '+str(epsilon_val_i)] )) #add to labels
#\| V \| plot
plt.subplot(num_delta_vals, 3, plot_num, aspect = 1./max_V_mag )
plt.plot(arclens_used_sorted, V_r0_sorted, '-o', c=clr, markersize=mk_size)
plt.ylim(bottom=0., top= max_V_mag)
plt.xlabel("arclength")
plt.ylabel('$\|V\|$')
#T plot
min_T_delta = T_min_delta[delta_i]
max_T_delta = T_max_delta[delta_i]
plt.subplot(num_delta_vals, 3, plot_num+1, aspect = 1./(max_T_delta-min_T_delta) )
plt.plot(arclens_used_sorted, T_r0_sorted, '-o', c=clr, markersize=mk_size)
plt.ylim(bottom=min_T_delta, top=max_T_delta )
plt.xlabel("arclength")
plt.ylabel("T")
#k_D plot
plt.subplot(num_delta_vals, 3, plot_num+2, aspect = 1. )
plt.plot(arclens_used_sorted, k_D_r0_sorted, '-o', c=clr, markersize=mk_size)
plt.ylim(bottom=0., top= 1.)
plt.xlabel("arclength")
plt.ylabel('$k_D$')
color_i = color_i + 1
plot_num = plot_num + 3
#plt.legend(labels, loc='upper right', bbox_to_anchor=(0.5, -0.05))
plt.legend(labels, loc='upper left', bbox_to_anchor=(1.05, 1))
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
'''
for p in range(len(p_degs)):
clr = plt.cm.YlOrBr(np.float64(p+1)/(len(p_degs)+1)) #different color for each degree plot
plt.semilogy(q_vals, errors[p,:], '-o', color = clr) #plot for different quads used
str_lbl_p = str(p_degs[p]) #label by degree
labels = concatenate(( labels, ["p_deg ="+str_lbl_p] )) #add to labels
plt.legend(labels, loc='upper right') #show legend
# plt.legend(lns, labels, loc='upper right', bbox_to_anchor=(0.5, -0.05))
'''
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = fig_title + str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
# Plot 2-param values for fig 2 protein flow paper:
def plot_Prot_mem_driven_flows_fig2(manny_label, param_vals, dep_field_vals, indep_var_vals, use_linearization, gamma_i):
'''
param_val = list(delta_vals, beta_val (USE .6), gamma_vals, epsilon_vals, alpha_vals) #Params_Lists = [delta_list, beta_list, gamma_list, epsilon_list, alpha_list ]
dep_field_vals = (num_r0 (\delta), num_beta, num_gamma, num_eps, 2 {\rho_prot_LIN, \rho_prot_NON_LIN}, num_quad_pts (Q)
indep_var_vals = {K, arclen} for each r_0, shape: {num_r0, Q, 2}
gamma_i = index of gamma value to use
'''
num_quad_pts_to_plot = indep_var_vals.shape[1]
mk_size = min(200./num_quad_pts_to_plot, 1.)
delta_vals = param_vals[0]
num_delta_vals = len(delta_vals)
beta_val_used = param_vals[1][0] # WE ONLY HAVE ONE
gamma_vals = param_vals[2]
num_gamma_vals = len(gamma_vals)
# USED GAMMA VALUE:
gamma_val_i = gamma_vals[gamma_i]
epsilon_vals = param_vals[3]
num_epsilon_vals = len(epsilon_vals)
alpha_vals = param_vals[4]
num_alpha_vals = len(alpha_vals)
num_plots_per_subplot = num_alpha_vals # plots of params on each subplot
num_plots = num_delta_vals*num_epsilon_vals
label_str_lin = ""
if(use_linearization == True):
label_str_lin = "_LINEARIZED_"
else:
label_str_lin = "_NL_"
fig = plt.figure(figsize=(8.5, 8.5))
plt.subplots_adjust(hspace=0.4)
fig_title = manny_label +"_beta_"+str(beta_val_used).replace(".", "pt") +"_gamma_"+str(gamma_val_i).replace(".", "pt") +"_"+ label_str_lin + "_Prot_mem_driven_flow_paper_fig2_"
plt.ticklabel_format(axis='both', style='plain')
#plt.suptitle(fig_title, fontsize=12, y=1.08) # plt.title(figure_title, y=1.08)
plot_num = 1
labels = array([]) #label by param value
for delta_i in range(num_delta_vals):
delta_val_i = param_vals[0][delta_i]
arclens_used = indep_var_vals[delta_i, :, 1]
inds_arclens_used_sort = arclens_used.argsort() # we need to sort these to connect plot lines
arclens_used_sorted = np.sort(arclens_used)
for epsilon_i in range(num_epsilon_vals):
epsilon_val_i = epsilon_vals[epsilon_i]
color_i = 0
for alpha_i in range(num_alpha_vals):
alpha_val_i = alpha_vals[alpha_i]
# prot_rho_param_vals_for_plot[R_0_test, alpha_i, beta_ind, gamma_ind, epsilon_ind, 2, :]
rho_r0_eps_alpha = []
if(use_linearization == True):
rho_r0_eps_alpha = np.squeeze(dep_field_vals[delta_i, alpha_i, 0, gamma_i, epsilon_i, 0, :])
else:
rho_r0_eps_alpha = np.squeeze(dep_field_vals[delta_i, alpha_i, 0, gamma_i, epsilon_i, 1, :])
rho_r0_eps_alpha_sorted = rho_r0_eps_alpha[inds_arclens_used_sort] # sort these by arclength from exo pt
clr = plt.cm.tab10(np.float64(color_i+1)/(num_plots_per_subplot+1)) #different color for each params
if(delta_i == 0 and epsilon_i == 0):
labels = concatenate(( labels, ['$\gamma$ ='+str(gamma_val_i)+", "+r'$\alpha$'+" = "+str(alpha_val_i)] )) #add to labels
#\rho plot
plt.subplot(num_delta_vals, 3, plot_num, aspect='equal')
plt.ylim(bottom=0., top= 1.)
plt.plot(arclens_used_sorted, rho_r0_eps_alpha_sorted, '-o', c=clr, markersize=mk_size)
plt.xlabel('arclength') #($\delta$ = '+str(delta_val_i)+', $\epsilon$ = '+str(epsilon_val_i)+")")
plt.ylabel(r'$\rho$')#'$\rho$')
plt.title('$\delta$'+" = "+str(delta_val_i)[0:4]+", "+'$\epsilon$'+" = "+str(epsilon_val_i))
color_i = color_i + 1
plot_num = plot_num + 1
#plt.legend(labels, loc='upper right', bbox_to_anchor=(0.5, -0.05))
plt.legend(labels, loc='upper left', bbox_to_anchor=(1.05, 1))
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = fig_title + str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
# Plot flow info for different geos, for fig 3 membrane flow paper:
def plot_mem_flows_fig3(manny_label, r0_vals, dep_field_vals, indep_var_vals, plot_vs_K_or_arclen):
'''
Indep = K, arclen
dep = \| V \|, T, k_D
dep_field_vals = (num_r0, num_beta, num_gamma, num_eps, 3 {fields}, num_quad_pts (Q)
indep_var_vals = {K, arclen} for each r_0, shape: {num_r0, Q, 2}
plot_vs_K_or_arclen = True: we plot vs K; False: we plot vs arclen
'''
num_r0_vals = len(r0_vals) # new row for each plot, col for {V, T, k_D}
num_quad_pts_to_plot = indep_var_vals.shape[1]
mk_size = min(200./num_quad_pts_to_plot, 1.)
mk_type = []
num_beta_vals = dep_field_vals.shape[1]
num_gamma_vals = dep_field_vals.shape[2]
num_epsilon_vals = dep_field_vals.shape[3]
num_param_val = num_beta_vals*num_gamma_vals*num_epsilon_vals
fig = plt.figure()
plt.subplots_adjust(hspace=0.4)
plt.ticklabel_format(axis='both', style='plain')
indep_var_name = ""
if(plot_vs_K_or_arclen == True):
indep_var_name = "Gauss_Curv"
mk_type = 'o'
else:
indep_var_name = "arclength"
mk_type = '-o'
fig_title = manny_label + "_mem_flow_paper_fig3"+"_plots_against_"+indep_var_name
#plt.suptitle(fig_title, fontsize=12)
plot_num = 1
for r0_i in range(num_r0_vals):
r0_val_i = r0_vals[r0_i]
indep_var_val_used = []
if(plot_vs_K_or_arclen == True):
indep_var_val_used = indep_var_vals[r0_i, :, 0]
else:
indep_var_val_used = indep_var_vals[r0_i, :, 1]
inds_indep_var_used_sort = indep_var_val_used.argsort() # we need to sort these to connect plot lines
indep_var_used_sorted = np.sort(indep_var_val_used)
V_r0, T_r0, k_D_r0 = np.hsplit( np.squeeze(dep_field_vals[r0_i, 0, 0, 0, :, :]), 3)
V_r0_sorted = V_r0[inds_indep_var_used_sort]
T_r0_sorted = T_r0[inds_indep_var_used_sort]
k_D_r0_sorted = k_D_r0[inds_indep_var_used_sort]
#\| V \| plot
plt.subplot(num_r0_vals, 3, plot_num)
plt.plot(indep_var_used_sorted, V_r0_sorted, mk_type, c='red', markersize=mk_size)
plt.xlabel(indep_var_name)
plt.ylabel('$\|V\|$')
# T plot
plt.subplot(num_r0_vals, 3, plot_num+1)
plt.plot(indep_var_used_sorted, T_r0_sorted, mk_type, c='red', markersize=mk_size)
plt.xlabel(indep_var_name)
plt.ylabel("T")
# k_D plot
plt.subplot(num_r0_vals, 3, plot_num+2)
plt.plot(indep_var_used_sorted, k_D_r0_sorted, mk_type, c='red', markersize=mk_size)
plt.xlabel(indep_var_name)
plt.ylabel('$k_D$')
plot_num = plot_num + 3
'''
for p in range(len(p_degs)):
clr = plt.cm.YlOrBr(np.float64(p+1)/(len(p_degs)+1)) #different color for each degree plot
plt.semilogy(q_vals, errors[p,:], '-o', color = clr) #plot for different quads used
str_lbl_p = str(p_degs[p]) #label by degree
labels = concatenate(( labels, ["p_deg ="+str_lbl_p] )) #add to labels
plt.legend(labels, loc='upper right') #show legend
# plt.legend(lns, labels, loc='upper right', bbox_to_anchor=(0.5, -0.05))
'''
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
MY_DIR = os.path.realpath(os.path.dirname(__file__))
Picked_Image_DIR = os.path.join(MY_DIR, 'Pickled_Images')
fig_name = fig_title + str(Time_and_Date_Str())+".pdf" #Creates unique filename
fig_path = os.path.join(Picked_Image_DIR, fig_name)
fig.savefig(fig_path, format='pdf')
# Plot 2-param values for fig 4 plot analyzing distribution of \| V \|:
def plot_mem_vel_prot_mag_fig4(manny_label, param_vals2, Vel_or_Prot_Seg_Outputs, Vel_or_Prot_field):
'''
param_val = list(r0_vals, gamma_vals, epsilon_vals, beta_vals) , Assume beta_val = .6, OR list(r0_vals, gamma_vals, epsilon_vals, beta_vals, alpha_vals)
Vel_or_Prot_Seg_Outputs = (num_r0_vals, num_gamma_vals, num_eps_vals) OR (num_r0_vals, num_gamma_vals, num_eps_vals, num_alpha_vals) for protein case
Vel_or_Prot_field: True if vel, false if prot
'''
mk_size = 1.
r0_vals_used = param_vals2[0]
num_r0_vals = len(r0_vals_used)
beta_val_used = param_vals2[3][0] # WE ONLY HAVE ONE
gamma_vals = param_vals2[1]
num_gamma_vals = len(gamma_vals)
epsilon_vals = param_vals2[2]
num_epsilon_vals = len(epsilon_vals)
alpha_vals = []
num_alpha_vals = 0
if(Vel_or_Prot_field == False):
alpha_vals = param_vals2[4]
num_alpha_vals = len(alpha_vals)
num_plots_per_subplot = num_gamma_vals*num_epsilon_vals # plots of params on each subplot
if(Vel_or_Prot_field == False):
num_plots_per_subplot = num_plots_per_subplot*num_alpha_vals
fig = plt.figure(figsize=(8.5, 8.5))
plt.subplots_adjust(hspace=0.4)
type_label = []
if(Vel_or_Prot_field == True):
type_label = "_mem_vel_mag"
else:
type_label = "_NL_prot_SS"
fig_title = manny_label +"_beta_"+str(beta_val_used).replace(".", "pt")+ type_label + "_seg_fig4_"
#plt.suptitle(fig_title, fontsize=12, y=1.08) # plt.title(figure_title, y=1.08)
labels = array([]) #label by param value
color_i = 0
for epsilon_i in range(num_epsilon_vals):
epsilon_val_i = epsilon_vals[epsilon_i]
for gamma_i in range(num_gamma_vals):
gamma_val_i = gamma_vals[gamma_i]
if(Vel_or_Prot_field == True):
Vel_Seg_Outputs_gamma_eps = Vel_or_Prot_Seg_Outputs[:, gamma_i, epsilon_i].flatten()
clr = plt.cm.tab10(np.float64(color_i+1)/(num_plots_per_subplot+1)) #different color for each params
labels = concatenate(( labels, ['$\gamma$ ='+str(gamma_val_i)+', $\epsilon$ = '+str(epsilon_val_i)] )) #add to labels
#\| V \| plot
plt.subplot(1, 1, 1)
plt.plot(r0_vals_used, Vel_Seg_Outputs_gamma_eps, '-o', c=clr, markersize=mk_size)
plt.xlabel('$r_0$')
plt.ylabel('$\|V\|$'+" density ratio")
color_i = color_i + 1
else:
for alpha_i in range(num_alpha_vals):
alpha_val_i = alpha_vals[alpha_i]
Prot_Seg_Outputs_gamma_eps_alpha = Vel_or_Prot_Seg_Outputs[:, gamma_i, epsilon_i, alpha_i].flatten()
clr = plt.cm.tab10(np.float64(color_i+1)/(num_plots_per_subplot+1)) #different color for each params
labels = concatenate(( labels, ['$\gamma$ ='+str(gamma_val_i)+', $\epsilon$ = '+str(epsilon_val_i)+
", "+r'$\alpha$'+" = "+str(alpha_val_i)] )) #add to labels
# rho density plot
plt.subplot(1, 1, 1)
plt.plot(r0_vals_used, Prot_Seg_Outputs_gamma_eps_alpha, '-o', c=clr, markersize=mk_size)