forked from salvadorgarciamunoz/pyphi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyphi_plots.py
1872 lines (1644 loc) · 77.3 KB
/
pyphi_plots.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plots for pyPhi
@author: Sal Garcia <[email protected]> <[email protected]>
Addition on Jan 18 2024 Added flag to score_scatter to include model scores in plot
replaced phi.unique -> np.unique
Updated call to maptplotlib colormap to keep it compatible
Addition on Sep 26 2023 All plots are now viewable offline (e.g. in airplane mode)
Addition on May 1 2023 corrected description of mb_vip
Addition on Apr 25 2023 added markersize to score_scatter
Addition on Apr 23 2023 also added the text_alpha flag to loadings map for PCA models
Addition on Apr 22 2023 added tooltips to contribution plots and VIP
implemented multiple columns in score scatter (yay!)
Addition on Apr 17 2023 added tpls to the supported models in all loadings, vip, r2pv
and score_scatter plots
Addition on Apr 15 2023, made all loadings, vip, r2pv and score_scatter compatible with
lpls and jrpls models
Addition on April 9 2023, added legends and pan tools to r2pv (yay!)
Addition on April 8 2023, fixed predvsobs to take MB data
Release Nov 15 2021
* Added "xgrid" flag to all plots using bar plots (loadings, weighted loadings, contributions) to add the Xgrid lines to the plot
Release Jan 15, 2021
* Added mb_blockweights plot for MBPSL models
Release Date: March 30 2020
* Fixed small syntax change for Bohek to stay compatible
Release Date: Aug 22 2019
What was done:
* This header is now included to track high level changes
"""
import numpy as np
from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.layouts import column
from bokeh.models import ColumnDataSource,LabelSet,Span,Legend
import pyphi as phi
import pandas as pd
#import matplotlib.cm as cm
import matplotlib
def r2pv(mvm_obj,*,plotwidth=600,plotheight=400,addtitle='',material=False,zspace=False):
"""
R2 per variable plots
by Salvador Garcia-Munoz
mvm_obj: A model created with phi.pca or phi.pls
"""
mvmobj=mvm_obj.copy()
A= mvmobj['T'].shape[1]
yaxlbl='X'
if (mvmobj['type']=='lpls') or (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls'):
if ((mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls')) and not(isinstance(material, bool) ):
mvmobj['r2xpv']=mvmobj['r2xpvi'][mvmobj['materials'].index(material)]
mvmobj['varidX']=mvmobj['varidXi'][mvmobj['materials'].index(material) ]
elif (mvmobj['type']=='tpls') and zspace :
mvmobj['r2xpv']=mvmobj['r2zpv']
mvmobj['varidX']=mvmobj['varidZ']
yaxlbl='Z'
else:
num_varX=mvmobj['P'].shape[0]
if 'Q' in mvmobj:
is_pls=True
lv_prefix='LV #'
else:
is_pls=False
lv_prefix='PC #'
lv_labels = []
for a in list(np.arange(A)+1):
lv_labels.append(lv_prefix+str(a))
if 'varidX' in mvmobj:
r2pvX_dict = {'XVar': mvmobj['varidX']}
XVar=mvmobj['varidX']
else:
XVar = []
for n in list(np.arange(num_varX)+1):
XVar.append('XVar #'+str(n))
r2pvX_dict = {'XVar': XVar}
for i in list(np.arange(A)):
r2pvX_dict.update({lv_labels[i] : mvmobj['r2xpv'][:,i].tolist()})
if 'Q' in mvmobj:
num_varY=mvmobj['Q'].shape[0]
if 'varidY' in mvmobj:
r2pvY_dict = {'YVar': mvmobj['varidY']}
YVar=mvmobj['varidY']
else:
YVar = []
for n in list(np.arange(num_varY)+1):
YVar.append('YVar #'+str(n))
r2pvY_dict = {'YVar': YVar}
for i in list(np.arange(A)):
r2pvY_dict.update({lv_labels[i] : mvmobj['r2ypv'][:,i].tolist()})
if is_pls:
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("r2xypv_"+rnd_num+".html",title="R2"+ yaxlbl+ "YPV",mode='inline')
#colormap =cm.get_cmap("rainbow")
colormap = matplotlib.colormaps['rainbow']
different_colors=A
color_mapping=colormap(np.linspace(0,1,different_colors),1,True)
bokeh_palette=["#%02x%02x%02x" % (r, g, b) for r, g, b in color_mapping[:,0:3]]
px = figure(x_range=XVar, title="R2"+ yaxlbl+" Per Variable "+addtitle,
tools="save,box_zoom,xpan,hover,reset", tooltips="$name @XVar: @$name",width=plotwidth,height=plotheight)
v=px.vbar_stack(lv_labels, x='XVar', width=0.9,color=bokeh_palette,source=r2pvX_dict)
px.y_range.range_padding = 0.1
px.ygrid.grid_line_color = None
px.xgrid.grid_line_color = None
px.axis.minor_tick_line_color = None
px.outline_line_color = None
px.yaxis.axis_label = 'R2'+ yaxlbl
px.xaxis.major_label_orientation = 45
legend = Legend(items=[(x, [v[i]]) for i, x in enumerate(lv_labels)], location=(0, 0))
px.add_layout(legend, 'right')
py = figure(x_range=YVar, height=plotheight, title="R2Y Per Variable "+addtitle,
tools="save,box_zoom,xpan,hover,reset", tooltips="$name @YVar: @$name",width=plotwidth)
v=py.vbar_stack(lv_labels, x='YVar', width=0.9,color=bokeh_palette,source=r2pvY_dict)
py.y_range.range_padding = 0.1
py.ygrid.grid_line_color = None
py.axis.minor_tick_line_color = None
py.xgrid.grid_line_color = None
py.outline_line_color = None
py.yaxis.axis_label = 'R2Y'
py.xaxis.major_label_orientation = 45
legend = Legend(items=[(x, [v[i]]) for i, x in enumerate(lv_labels)], location=(0, 0))
py.add_layout(legend, 'right')
show(column(px,py))
else:
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("r2xpv_"+rnd_num+".html",title='R2XPV',mode='inline')
#colormap =cm.get_cmap("rainbow")
colormap = matplotlib.colormaps['rainbow']
different_colors=A
color_mapping=colormap(np.linspace(0,1,different_colors),1,True)
bokeh_palette=["#%02x%02x%02x" % (r, g, b) for r, g, b in color_mapping[:,0:3]]
p = figure(x_range=XVar, title="R2X Per Variable "+addtitle,
tools="save,box_zoom,xpan,hover,reset", tooltips="$name @XVar: @$name",width=plotwidth,height=plotheight)
v=p.vbar_stack(lv_labels, x='XVar', width=0.9,color=bokeh_palette,source=r2pvX_dict)
legend = Legend(items=[(x, [v[i]]) for i, x in enumerate(lv_labels)], location=(0, 0))
p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.yaxis.axis_label = 'R2X'
p.xaxis.major_label_orientation = 45
p.add_layout(legend, 'right')
show(p)
return
def loadings(mvm_obj,*,plotwidth=600,xgrid=False,addtitle='',material=False,zspace=False):
"""
Column plots of loadings
by Salvador Garcia-Munoz
mvm_obj: A model created with phi.pca or phi.pls
"""
mvmobj=mvm_obj.copy()
space_lbl='X'
A= mvmobj['T'].shape[1]
if (mvmobj['type']=='lpls') or (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls'):
loading_lbl='S*'
if (mvmobj['type']=='lpls'):
mvmobj['Ws']=mvmobj['Ss']
if isinstance(material, bool) and not(zspace):
mvmobj['Ws']=mvmobj['Ss']
if ((mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls') ) and not(isinstance(material, bool) ):
mvmobj['Ws']=mvmobj['Ssi'][mvmobj['materials'].index(material)]
mvmobj['varidX']=mvmobj['varidXi'][mvmobj['materials'].index(material) ]
elif (mvmobj['type']=='tpls') and zspace :
mvmobj['varidX']=mvmobj['varidZ']
loading_lbl='Wz*'
space_lbl='Z'
else:
num_varX=mvmobj['P'].shape[0]
loading_lbl='W*'
if 'Q' in mvmobj:
is_pls=True
lv_prefix='LV #'
else:
is_pls=False
lv_prefix='PC #'
lv_labels = []
for a in list(np.arange(A)+1):
lv_labels.append(lv_prefix+str(a))
if 'varidX' in mvmobj:
X_loading_dict = {'XVar': mvmobj['varidX']}
XVar=mvmobj['varidX']
else:
XVar = []
for n in list(np.arange(num_varX)+1):
XVar.append('XVar #'+str(n))
X_loading_dict = {'XVar': XVar}
if 'Q' in mvmobj:
for i in list(np.arange(A)):
X_loading_dict.update({lv_labels[i] : mvmobj['Ws'][:,i].tolist()})
num_varY=mvmobj['Q'].shape[0]
if 'varidY' in mvmobj:
Q_dict = {'YVar': mvmobj['varidY']}
YVar=mvmobj['varidY']
else:
YVar = []
for n in list(np.arange(num_varY)+1):
YVar.append('YVar #'+str(n))
Q_dict = {'YVar': YVar}
for i in list(np.arange(A)):
Q_dict.update({lv_labels[i] : mvmobj['Q'][:,i].tolist()})
else:
for i in list(np.arange(A)):
X_loading_dict.update({lv_labels[i] : mvmobj['P'][:,i].tolist()})
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("Variable:","@names")
]
if is_pls:
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings "+space_lbl+" Space_"+rnd_num+".html",title=space_lbl+' Loadings PLS',mode='inline')
for i in list(np.arange(A)):
p = figure(x_range=XVar, title=space_lbl+" Space Loadings "+lv_labels[i]+addtitle,
tools=TOOLS,tooltips=TOOLTIPS,width=plotwidth)
source1 = ColumnDataSource(data=dict(x_=XVar, y_=mvmobj['Ws'][:,i].tolist(),names=XVar))
#p.vbar(x=XVar, top=mvmobj['Ws'][:,i].tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
p.ygrid.grid_line_color = None
if xgrid:
p.xgrid.grid_line_color = 'lightgray'
else:
p.xgrid.grid_line_color = None
p.yaxis.axis_label = loading_lbl+' ['+str(i+1)+']'
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([hline])
p.xaxis.major_label_orientation = 45
if i==0:
p_list=[p]
else:
p_list.append(p)
show(column(p_list))
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings Y Space_"+rnd_num+".html",title='Y Loadings PLS',mode='inline')
for i in list(np.arange(A)):
p = figure(x_range=YVar, title="Y Space Loadings "+lv_labels[i]+addtitle,
tools="save,box_zoom,pan,reset",tooltips=TOOLTIPS,width=plotwidth)
source1 = ColumnDataSource(data=dict(x_=YVar, y_=mvmobj['Q'][:,i].tolist(),names=YVar))
#p.vbar(x=YVar, top=mvmobj['Q'][:,i].tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
p.ygrid.grid_line_color = None
if xgrid:
p.xgrid.grid_line_color = 'lightgray'
else:
p.xgrid.grid_line_color = None
p.yaxis.axis_label = 'Q ['+str(i+1)+']'
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([hline])
p.xaxis.major_label_orientation = 45
if i==0:
p_list=[p]
else:
p_list.append(p)
show(column(p_list))
else:
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings X Space_"+rnd_num+".html",title='X Loadings PCA',mode='inline')
for i in list(np.arange(A)):
source1 = ColumnDataSource(data=dict(x_=XVar, y_=mvmobj['P'][:,i].tolist(),names=XVar))
p = figure(x_range=XVar, title="X Space Loadings "+lv_labels[i]+addtitle,
tools=TOOLS,tooltips=TOOLTIPS,width=plotwidth)
#p.vbar(x=XVar, top=mvmobj['P'][:,i].tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
if xgrid:
p.xgrid.grid_line_color = 'lightgray'
else:
p.xgrid.grid_line_color = None
p.yaxis.axis_label = 'P ['+str(i+1)+']'
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([hline])
p.xaxis.major_label_orientation = 45
if i==0:
p_list=[p]
else:
p_list.append(p)
show(column(p_list))
return
def loadings_map(mvm_obj,dims,*,plotwidth=600,addtitle='',material=False,zspace=False,textalpha=0.75):
"""
Scatter plot overlaying X and Y loadings
by Salvador Garcia-Munoz
mvm_obj: A model created with phi.pca or phi.pls
dims: what latent spaces to plot in x and y axes e.g. dims=[1,2]
"""
mvmobj=mvm_obj.copy()
A= mvmobj['T'].shape[1]
if (mvmobj['type']=='lpls') or (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls'):
if (mvmobj['type']=='lpls'):
mvmobj['Ws']=mvmobj['Ss']
if isinstance(material, bool) and not(zspace):
mvmobj['Ws']=mvmobj['Ss']
if ((mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls')) and not(isinstance(material, bool) ):
mvmobj['Ws']=mvmobj['Ssi'][mvmobj['materials'].index(material)]
mvmobj['varidX']=mvmobj['varidXi'][mvmobj['materials'].index(material) ]
elif (mvmobj['type']=='tpls') and zspace :
mvmobj['varidX']=mvmobj['varidZ']
else:
num_varX=mvmobj['P'].shape[0]
if 'Q' in mvmobj:
lv_prefix='LV #'
lv_labels = []
for a in list(np.arange(A)+1):
lv_labels.append(lv_prefix+str(a))
if 'varidX' in mvmobj:
XVar=mvmobj['varidX']
else:
XVar = []
for n in list(np.arange(num_varX)+1):
XVar.append('XVar #'+str(n))
num_varY=mvmobj['Q'].shape[0]
if 'varidY' in mvmobj:
YVar=mvmobj['varidY']
else:
YVar = []
for n in list(np.arange(num_varY)+1):
YVar.append('YVar #'+str(n))
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings Map"+rnd_num+".html",title='Loadings Map',mode='inline')
x_ws = mvmobj['Ws'][:,dims[0]-1]
x_ws = x_ws/np.max(np.abs(x_ws))
y_ws = mvmobj['Ws'][:,dims[1]-1]
y_ws = y_ws/np.max(np.abs(y_ws))
x_q = mvmobj['Q'][:,dims[0]-1]
x_q = x_q/np.max(np.abs(x_q))
y_q = mvmobj['Q'][:,dims[1]-1]
y_q = y_q/np.max(np.abs(y_q))
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("index", "$index"),
("(x,y)", "($x, $y)"),
("Variable:","@names")
]
source1 = ColumnDataSource(data=dict(x=x_ws, y=y_ws,names=XVar))
source2 = ColumnDataSource(data=dict(x=x_q, y=y_q,names=YVar))
p = figure(tools=TOOLS, tooltips=TOOLTIPS,width=plotwidth, title="Loadings Map LV["+str(dims[0])+"] - LV["+str(dims[1])+"] "+addtitle,
x_range=(-1.5,1.5),y_range=(-1.5,1.5))
p.circle('x', 'y', source=source1,size=10,color='darkblue')
p.circle('x', 'y', source=source2,size=10,color='red')
p.xaxis.axis_label = lv_labels [dims[0]-1]
p.yaxis.axis_label = lv_labels [dims[1]-1]
labelsX = LabelSet(x='x', y='y', text='names',
level='glyph',x_offset=5, y_offset=5,
source=source1,text_color='darkgray',
text_alpha=textalpha )
labelsY = LabelSet(x='x', y='y', text='names',
level='glyph',x_offset=5, y_offset=5,
source=source2,text_color='darkgray',
text_alpha=textalpha )
p.add_layout(labelsX)
p.add_layout(labelsY)
vline = Span(location=0, dimension='height', line_color='black', line_width=2)
# Horizontal line
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([vline, hline])
show(p)
else:
lv_prefix='PC #'
lv_labels = []
for a in list(np.arange(A)+1):
lv_labels.append(lv_prefix+str(a))
if 'varidX' in mvmobj:
XVar=mvmobj['varidX']
else:
XVar = []
for n in list(np.arange(num_varX)+1):
XVar.append('XVar #'+str(n))
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings Map"+rnd_num+".html",title='Loadings Map',mode='inline')
x_p = mvmobj['P'][:,dims[0]-1]
y_p = mvmobj['P'][:,dims[1]-1]
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("index", "$index"),
("(x,y)", "($x, $y)"),
("Variable:","@names")
]
source1 = ColumnDataSource(data=dict(x=x_p, y=y_p,names=XVar))
p = figure(tools=TOOLS, tooltips=TOOLTIPS,width=plotwidth, title="Loadings Map PC["+str(dims[0])+"] - PC["+str(dims[1])+"] "+addtitle, x_range=(-1.5,1.5),y_range=(-1.5,1.5))
p.circle('x', 'y', source=source1,size=10,color='darkblue')
p.xaxis.axis_label = lv_labels [dims[0]-1]
p.yaxis.axis_label = lv_labels [dims[1]-1]
labelsX = LabelSet(x='x', y='y', text='names', level='glyph',x_offset=5, y_offset=5, source=source1,
text_color='darkgray',text_alpha=textalpha)
p.add_layout(labelsX)
vline = Span(location=0, dimension='height', line_color='black', line_width=2)
# Horizontal line
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([vline, hline])
show(p)
return
def weighted_loadings(mvm_obj,*,plotwidth=600,xgrid=False,addtitle='',material=False,zspace=False):
"""
Column plots of loadings weighted by r2x/r2y correspondingly
by Salvador Garcia-Munoz
mvm_obj: A model created with phi.pca or phi.pls
"""
mvmobj=mvm_obj.copy()
A= mvmobj['T'].shape[1]
space_lbl='X'
if (mvmobj['type']=='lpls') or (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls'):
loading_lbl='S*'
if (mvmobj['type']=='lpls'):
mvmobj['Ws']=mvmobj['Ss']
if isinstance(material, bool) and not(zspace):
mvmobj['Ws']=mvmobj['Ss']
if ((mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls')) and not(isinstance(material, bool) ):
mvmobj['Ws']=mvmobj['Ssi'][mvmobj['materials'].index(material)]
mvmobj['varidX']=mvmobj['varidXi'][mvmobj['materials'].index(material) ]
mvmobj['r2xpv']=mvmobj['r2xpvi'][mvmobj['materials'].index(material) ]
elif (mvmobj['type']=='tpls') and zspace:
mvmobj['varidX']=mvmobj['varidZ']
mvmobj['r2xpv']=mvmobj['r2zpv']
loading_lbl='Wz*'
space_lbl='Z'
else:
num_varX=mvmobj['P'].shape[0]
loading_lbl='W*'
if 'Q' in mvmobj:
is_pls=True
lv_prefix='LV #'
else:
is_pls=False
lv_prefix='PC #'
lv_labels = []
for a in list(np.arange(A)+1):
lv_labels.append(lv_prefix+str(a))
if 'varidX' in mvmobj:
X_loading_dict = {'XVar': mvmobj['varidX']}
XVar=mvmobj['varidX']
else:
XVar = []
for n in list(np.arange(num_varX)+1):
XVar.append('XVar #'+str(n))
X_loading_dict = {'XVar': XVar}
if 'Q' in mvmobj:
for i in list(np.arange(A)):
X_loading_dict.update({lv_labels[i] : mvmobj['Ws'][:,i].tolist()})
num_varY=mvmobj['Q'].shape[0]
if 'varidY' in mvmobj:
Q_dict = {'YVar': mvmobj['varidY']}
YVar=mvmobj['varidY']
else:
YVar = []
for n in list(np.arange(num_varY)+1):
YVar.append('YVar #'+str(n))
Q_dict = {'YVar': YVar}
for i in list(np.arange(A)):
Q_dict.update({lv_labels[i] : mvmobj['Q'][:,i].tolist()})
else:
for i in list(np.arange(A)):
X_loading_dict.update({lv_labels[i] : mvmobj['P'][:,i].tolist()})
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("Variable:","@names")
]
if is_pls:
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings "+space_lbl+" Space_"+rnd_num+".html",title=space_lbl+' Weighted Loadings PLS',mode='inline')
for i in list(np.arange(A)):
p = figure(x_range=XVar, title=space_lbl+" Space Weighted Loadings "+lv_labels[i]+addtitle,
tools=TOOLS,tooltips=TOOLTIPS,width=plotwidth)
source1 = ColumnDataSource(data=dict(x_=XVar, y_=(mvmobj['r2xpv'][:,i] * mvmobj['Ws'][:,i]).tolist(),names=XVar))
#p.vbar(x=XVar, top=(mvmobj['r2xpv'][:,i] * mvmobj['Ws'][:,i]).tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
p.ygrid.grid_line_color = None
if xgrid:
p.xgrid.grid_line_color = 'lightgray'
else:
p.xgrid.grid_line_color = None
p.yaxis.axis_label = loading_lbl+' x R2'+space_lbl+' ['+str(i+1)+']'
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([hline])
p.xaxis.major_label_orientation = 45
if i==0:
p_list=[p]
else:
p_list.append(p)
show(column(p_list))
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings Y Space_"+rnd_num+".html",title='Y Weighted Loadings PLS',mode='inline')
for i in list(np.arange(A)):
p = figure(x_range=YVar, title="Y Space Weighted Loadings "+lv_labels[i]+addtitle,
tools=TOOLS,tooltips=TOOLTIPS,width=plotwidth)
source1 = ColumnDataSource(data=dict(x_=YVar, y_=(mvmobj['r2ypv'][:,i] * mvmobj['Q'][:,i]).tolist(),names=YVar))
#p.vbar(x=YVar, top=(mvmobj['r2ypv'][:,i] * mvmobj['Q'][:,i]).tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
p.ygrid.grid_line_color = None
if xgrid:
p.xgrid.grid_line_color = 'lightgray'
else:
p.xgrid.grid_line_color = None
p.yaxis.axis_label = 'Q x R2Y ['+str(i+1)+']'
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([hline])
p.xaxis.major_label_orientation = 45
if i==0:
p_list=[p]
else:
p_list.append(p)
show(column(p_list))
else:
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Loadings X Space_"+rnd_num+".html",title='X Weighted Loadings PCA',mode='inline')
for i in list(np.arange(A)):
p = figure(x_range=XVar, title="X Space Weighted Loadings "+lv_labels[i]+addtitle,
tools=TOOLS,tooltips=TOOLTIPS,width=plotwidth)
source1 = ColumnDataSource(data=dict(x_=XVar, y_=(mvmobj['r2xpv'][:,i] * mvmobj['P'][:,i]).tolist(),names=XVar))
#p.vbar(x=XVar, top=(mvmobj['r2xpv'][:,i] * mvmobj['P'][:,i]).tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
p.ygrid.grid_line_color = None
if xgrid:
p.xgrid.grid_line_color = 'lightgray'
else:
p.xgrid.grid_line_color = None
p.yaxis.axis_label = 'P x R2X['+str(i+1)+']'
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([hline])
p.xaxis.major_label_orientation = 45
if i==0:
p_list=[p]
else:
p_list.append(p)
show(column(p_list))
return
def vip(mvm_obj,*,plotwidth=600,material=False,zspace=False,addtitle=''):
"""
Very Important to the Projection (VIP) plot
by Salvador Garcia-Munoz
mvm_obj: A model created with phi.pls
"""
mvmobj=mvm_obj.copy()
if 'Q' in mvmobj:
if (mvmobj['type']=='lpls') or (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls'):
if (mvmobj['type']=='lpls'):
mvmobj['Ws']=mvmobj['Ss']
if isinstance(material, bool) and not(zspace):
mvmobj['Ws']=mvmobj['Ss']
if ((mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls')) and not(isinstance(material, bool) ):
mvmobj['Ws']=mvmobj['Ssi'][mvmobj['materials'].index(material)]
mvmobj['varidX']=mvmobj['varidXi'][mvmobj['materials'].index(material) ]
elif (mvmobj['type']=='tpls') and zspace:
mvmobj['varidX']=mvmobj['varidZ']
else:
num_varX=mvmobj['P'].shape[0]
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("VIP_"+rnd_num+".html",title='VIP Coefficient',mode='inline')
if 'varidX' in mvmobj:
XVar=mvmobj['varidX']
else:
XVar = []
for n in list(np.arange(num_varX)+1):
XVar.append('XVar #'+str(n))
vip=np.sum(np.abs(mvmobj['Ws'] * np.tile(mvmobj['r2y'],(mvmobj['Ws'].shape[0],1)) ),axis=1)
vip=np.reshape(vip,(len(vip),-1))
sort_indx=np.argsort(-vip,axis=0)
vip=vip[sort_indx]
sorted_XVar=[]
for i in sort_indx[:,0]:
sorted_XVar.append(XVar[i])
TOOLTIPS = [
("Variable","@names")
]
p = figure(x_range=sorted_XVar, title="VIP "+addtitle,
tools="save,box_zoom,pan,reset",tooltips=TOOLTIPS,width=plotwidth)
source1 = ColumnDataSource(data=dict(x_=sorted_XVar, y_=vip.tolist(),names=sorted_XVar))
#p.vbar(x=sorted_XVar, top=vip.tolist(), width=0.5)
p.vbar(x='x_', top='y_', source=source1,width=0.5)
p.xgrid.grid_line_color = None
p.yaxis.axis_label = 'Very Important to the Projection'
p.xaxis.major_label_orientation = 45
show(p)
return
def _create_classid_(df,column,*,bins=5):
'''
Internal routine to create a CLASSID dataframe from values in a column
'''
hist,bin_edges=np.histogram(df[column].values[np.logical_not(np.isnan(df[column].values))],bins=5 )
range_list=[]
for i,e in enumerate(bin_edges[:-1]):
range_list.append(str(np.round(bin_edges[i],3))+' to '+ str(np.round(bin_edges[i+1],3)))
range_list.append('NaN')
membership_=np.digitize(df[column].values,bin_edges)
membership=[]
for m in membership_:
membership.append(range_list[m-1])
classid_df=df[df.columns[0]].to_frame()
classid_df.insert(1,column,membership)
return classid_df
def score_scatter(mvm_obj,xydim,*,CLASSID=False,colorby=False,Xnew=False,
add_ci=False,add_labels=False,add_legend=True,legend_cols=1,
addtitle='',plotwidth=600,plotheight=600,
rscores=False,material=False,marker_size=7,nbins=False,include_model=False):
'''
Score scatter plot
by Salvador Garcia-Munoz
mvm_obj : PLS or PCA object from phyphi
xydim : LV to plot on x and y axes. eg [1,2] will plot t1 vs t2
CLASSID : Pandas DataFrame with CLASSIDS
colorby : Category (one of the CLASSIDS) to color by
Xnew : New data for which to make the score plot this routine evaluates and plots
add_ci : when = True will add confidence intervals
add_labels : When = True labels each point with Obs ID
add_legend : When = True will add a legend with classid labels
legend_cols: Number of columns for legend
addtitle : Additional text to be added to title
plotwidth : If omitted, width is 600
plotheight : If omitted, height is 600
rscores : Plot scores for all material space in lpls|jrpls|tpls
material : Label for specific material to plot scores for in lpls|jrpls|tpls
'''
# if not(isinstance(nbins, bool)):
# if colorby in df.columns.to_list():
mvmobj=mvm_obj.copy()
if ((mvmobj['type']=='lpls') or (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls')) and (not(isinstance(Xnew,bool))):
Xnew=False
print('score scatter does not take Xnew for jrpls or lpls for now')
if isinstance(Xnew,bool):
if 'obsidX' in mvmobj:
ObsID_=mvmobj['obsidX']
else:
ObsID_ = []
for n in list(np.arange(mvmobj['T'].shape[0])+1):
ObsID_.append('Obs #'+str(n))
T_matrix=mvmobj['T']
if not(rscores):
if (mvmobj['type']=='lpls'):
ObsID_=mvmobj['obsidR']
if (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls') :
ObsID_=mvmobj['obsidRi'][0]
else:
if (mvmobj['type']=='lpls'):
ObsID_=mvmobj['obsidX']
T_matrix=mvmobj['Rscores']
if (mvmobj['type']=='jrpls') or (mvmobj['type']=='tpls') :
if isinstance(material,bool):
allobsids=[y for x in mvmobj['obsidXi'] for y in x]
ObsID_=allobsids
clssid_obs=[]
clssid_class=[]
for i,R_ in enumerate(mvmobj['Rscores']):
clssid_obs.extend(mvmobj['obsidXi'][i])
clssid_class.extend([mvmobj['materials'][i]]*len( mvmobj['obsidXi'][i]))
if i==0:
allrscores=R_
else:
allrscores=np.vstack((allrscores,R_))
classid=pd.DataFrame(clssid_class,columns=['material'])
classid.insert(0,'obs',clssid_obs)
CLASSID=classid
colorby='material'
T_matrix=allrscores
else:
ObsID_ = mvmobj['obsidXi'][mvmobj['materials'].index(material) ]
T_matrix = mvmobj['Rscores'][mvmobj['materials'].index(material) ]
else:
if isinstance(Xnew,np.ndarray):
X_=Xnew.copy()
ObsID_ = []
for n in list(np.arange(Xnew.shape[0])+1):
ObsID_.append('Obs #'+str(n))
elif isinstance(Xnew,pd.DataFrame):
X_=np.array(Xnew.values[:,1:]).astype(float)
ObsID_ = Xnew.values[:,0].astype(str)
ObsID_ = ObsID_.tolist()
if 'Q' in mvmobj:
xpred=phi.pls_pred(X_,mvmobj)
else:
xpred=phi.pca_pred(X_,mvmobj)
T_matrix=xpred['Tnew']
if include_model:
if 'obsidX' in mvmobj:
ObsID__=mvmobj['obsidX'].copy()
else:
ObsID__ = []
for n in list(np.arange(mvmobj['T'].shape[0])+1):
ObsID__.append('Model Obs #'+str(n))
T_matrix_=mvmobj['T'].copy()
if isinstance(CLASSID,bool): #If there are no classids I need to create one
source=(['Model']*T_matrix_.shape[0])
source.extend(['New']*T_matrix.shape[0])
ObsID__.extend(ObsID_)
CLASSID=pd.DataFrame.from_dict( {'ObsID':ObsID__,'_Source_':source })
colorby='_Source_'
else: #IF there are I need to augment it
source=['Model']*T_matrix_.shape[0]
CLASSID_=pd.DataFrame.from_dict( {CLASSID.columns[0]:ObsID__,colorby:source })
ObsID__.extend(ObsID_)
CLASSID = pd.concat([CLASSID_,CLASSID])
ObsID_=ObsID__.copy()
T_matrix=np.vstack((T_matrix_,T_matrix ))
ObsNum_=[]
for n in list(range(1,len(ObsID_)+1)):
ObsNum_.append(str(n))
if isinstance(CLASSID,bool): # No CLASSIDS
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Score_Scatter_"+rnd_num+".html",title='Score Scatter t['+str(xydim[0])+'] - t['+str(xydim[1])+ ']',mode='inline')
x_=T_matrix[:,[xydim[0]-1]]
y_=T_matrix[:,[xydim[1]-1]]
source = ColumnDataSource(data=dict(x=x_, y=y_,ObsID=ObsID_,ObsNum=ObsNum_))
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("Obs #", "@ObsNum"),
("(x,y)", "($x, $y)"),
("Obs: ","@ObsID")
]
p = figure(tools=TOOLS, tooltips=TOOLTIPS,width=plotwidth,height=plotheight, title='Score Scatter t['+str(xydim[0])+'] - t['+str(xydim[1])+ '] '+addtitle)
p.circle('x', 'y', source=source,size=marker_size)
if add_ci:
T_aux1=mvmobj['T'][:,[xydim[0]-1]]
T_aux2=mvmobj['T'][:,[xydim[1]-1]]
T_aux = np.hstack((T_aux1,T_aux2))
st=(T_aux.T @ T_aux)/T_aux.shape[0]
[xd95,xd99,yd95p,yd95n,yd99p,yd99n]=phi.scores_conf_int_calc(st,mvmobj['T'].shape[0])
p.line(xd95,yd95p,line_color="gold",line_dash='dashed')
p.line(xd95,yd95n,line_color="gold",line_dash='dashed')
p.line(xd99,yd99p,line_color="red",line_dash='dashed')
p.line(xd99,yd99n,line_color="red",line_dash='dashed')
if add_labels:
labelsX = LabelSet(x='x', y='y', text='ObsID', level='glyph',x_offset=5, y_offset=5, source=source)
p.add_layout(labelsX)
if not(rscores):
p.xaxis.axis_label = 't ['+str(xydim[0])+']'
p.yaxis.axis_label = 't ['+str(xydim[1])+']'
else:
p.xaxis.axis_label = 'r ['+str(xydim[0])+']'
p.yaxis.axis_label = 'r ['+str(xydim[1])+']'
# Vertical line
vline = Span(location=0, dimension='height', line_color='black', line_width=2)
# Horizontal line
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([vline, hline])
show(p)
else: # YES CLASSIDS
#Classes_=np.unique(CLASSID[colorby]).tolist()
Classes_=phi.unique(CLASSID,colorby)
A=len(Classes_)
#colormap =cm.get_cmap("rainbow")
colormap = matplotlib.colormaps['rainbow']
different_colors=A
color_mapping=colormap(np.linspace(0,1,different_colors),1,True)
#Test code to overwrite "Model" Category with light Cyan
if Classes_[0]=='Model':
color_mapping=colormap(np.linspace(0,1,different_colors-1),1,True)
color_mapping=np.vstack((np.array([225,225,225,255]),color_mapping))
bokeh_palette=["#%02x%02x%02x" % (r, g, b) for r, g, b in color_mapping[:,0:3]]
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Score_Scatter_"+rnd_num+".html",title='Score Scatter t['+str(xydim[0])+'] - t['+str(xydim[1])+ ']',mode='inline')
x_=T_matrix[:,[xydim[0]-1]]
y_=T_matrix[:,[xydim[1]-1]]
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("Obs #", "@ObsNum"),
("(x,y)", "($x, $y)"),
("Obs: ","@ObsID"),
("Class:","@Class")
]
classid_=list(CLASSID[colorby])
legend_it = []
p = figure(tools=TOOLS, tooltips=TOOLTIPS,toolbar_location="above",width=plotwidth,height=plotheight,title='Score Scatter t['+str(xydim[0])+'] - t['+str(xydim[1])+ '] '+addtitle)
for classid_in_turn in Classes_:
x_aux = []
y_aux = []
obsid_aux = []
obsnum_aux = []
classid_aux = []
for i in list(range(len(ObsID_))):
if classid_[i]==classid_in_turn:
x_aux.append(x_[i][0])
y_aux.append(y_[i][0])
obsid_aux.append(ObsID_[i])
obsnum_aux.append(ObsNum_[i])
classid_aux.append(classid_in_turn)
source = ColumnDataSource(data=dict(x=x_aux, y=y_aux,ObsID=obsid_aux,ObsNum=obsnum_aux, Class=classid_aux))
color_=bokeh_palette[Classes_.index(classid_in_turn)]
if add_legend:
c = p.circle('x','y',source=source,color=color_,size=marker_size)
aux_=classid_in_turn
if isinstance(aux_,(float,int)):
aux_=str(aux_)
#legend_it.append((classid_in_turn, [c]))
legend_it.append((aux_, [c]))
else:
p.circle('x','y',source=source,color=color_,size=marker_size)
if add_labels:
labelsX = LabelSet(x='x', y='y', text='ObsID', level='glyph',x_offset=5, y_offset=5, source=source)
p.add_layout(labelsX)
if add_ci:
T_aux1=mvmobj['T'][:,[xydim[0]-1]]
T_aux2=mvmobj['T'][:,[xydim[1]-1]]
T_aux = np.hstack((T_aux1,T_aux2))
st=(T_aux.T @ T_aux)/T_aux.shape[0]
[xd95,xd99,yd95p,yd95n,yd99p,yd99n]=phi.scores_conf_int_calc(st,mvmobj['T'].shape[0])
p.line(xd95,yd95p,line_color="gold",line_dash='dashed')
p.line(xd95,yd95n,line_color="gold",line_dash='dashed')
p.line(xd99,yd99p,line_color="red",line_dash='dashed')
p.line(xd99,yd99n,line_color="red",line_dash='dashed')
if not(rscores):
p.xaxis.axis_label = 't ['+str(xydim[0])+']'
p.yaxis.axis_label = 't ['+str(xydim[1])+']'
else:
p.xaxis.axis_label = 'r ['+str(xydim[0])+']'
p.yaxis.axis_label = 'r ['+str(xydim[1])+']'
# Vertical line
vline = Span(location=0, dimension='height', line_color='black', line_width=2)
# Horizontal line
hline = Span(location=0, dimension='width', line_color='black', line_width=2)
p.renderers.extend([vline, hline])
if add_legend:
#legend_cols=1
ipc=[np.round(len(legend_it)/legend_cols)]*legend_cols
ipc[-1]=len(legend_it)-sum(ipc[:-1])
pastit=0
for it in ipc:
leg_ = Legend(
items=legend_it[int(0+pastit):int(pastit+it)])
#location=(0,15+pastit*5))
pastit+=it
p.add_layout(leg_, 'right')
leg_.click_policy="hide"
#legend = Legend(items=legend_it, location='top_right')
#p.add_layout(legend, 'right')
show(p)
return
def score_line(mvmobj,dim,*,CLASSID=False,colorby=False,Xnew=False,add_ci=False,add_labels=False,add_legend=True,plotline=True,plotwidth=600,plotheight=600):
'''
Score scatter plot
by Salvador Garcia-Munoz
mvmobj : PLS or PCA object from phyphi
dim : LV to plot eg "1" will plot t1 vs observation #
CLASSID : Pandas DataFrame with CLASSIDS
colorby : Category (one of the CLASSIDS) to color by
Xnew : New data for which to make the score plot this routine evaluates and plots
add_ci : When = True will add confidence intervals
add_labels : When =True will display Obs ID per point
plotwidth : When Omitted is = 600
plotline : Adds a conecting line between dots [True by default]
'''
if not(isinstance(dim,list)):
if isinstance(dim, int):
dim=[dim]
if isinstance(Xnew,bool):
if 'obsidX' in mvmobj:
ObsID_=mvmobj['obsidX']
else:
ObsID_ = []
for n in list(np.arange(mvmobj['T'].shape[0])+1):
ObsID_.append('Obs #'+str(n))
T_matrix=mvmobj['T']
else:
if isinstance(Xnew,np.ndarray):
X_=Xnew.copy()
ObsID_ = []
for n in list(np.arange(Xnew.shape[0])+1):
ObsID_.append('Obs #'+str(n))
elif isinstance(Xnew,pd.DataFrame):
X_=np.array(Xnew.values[:,1:]).astype(float)
ObsID_ = Xnew.values[:,0].astype(str)
ObsID_ = ObsID_.tolist()
if 'Q' in mvmobj:
xpred=phi.pls_pred(X_,mvmobj)
else:
xpred=phi.pca_pred(X_,mvmobj)
T_matrix=xpred['Tnew']
ObsNum_=[]
for n in list(range(1,len(ObsID_)+1)):
ObsNum_.append('Obs #'+str(n))
if isinstance(CLASSID,bool): # No CLASSIDS
rnd_num=str(int(np.round(1000*np.random.random_sample())))
output_file("Score_Line_"+rnd_num+".html",title='Score Line t['+str(dim[0])+ ']',mode='inline')
y_=T_matrix[:,[dim[0]-1]]
x_=list(range(1,y_.shape[0]+1))
source = ColumnDataSource(data=dict(x=x_, y=y_,ObsID=ObsID_,ObsNum=ObsNum_))
TOOLS = "save,wheel_zoom,box_zoom,pan,reset,box_select,lasso_select"
TOOLTIPS = [
("Obs#", "@ObsNum"),
("(x,y)", "($x, $y)"),
("Obs: ","@ObsID")
]
p = figure(tools=TOOLS, tooltips=TOOLTIPS,width=plotwidth,height=plotheight, title='Score Line t['+str(dim[0])+']' )
p.circle('x', 'y', source=source,size=7)