-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpyphi_batch.py
2335 lines (2032 loc) · 102 KB
/
pyphi_batch.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 -*-
"""
Created on Mon Apr 11 14:58:35 2022
Batch data is assumed to come in an excel file
with first column being batch identifier and following columns
being process variables.
Optionally the second column labeled 'PHASE','Phase' or 'phase' indicating
the phase of exceution
Change log:
* added Dec 28 2023 Titles can be sent to contribution plots via plot_title flag
Monitoring diagnostics are also plotted against sample starting with 1
* added Dec 27 2023 Corrected plots to use correct xaxis starting with sample =1
Ammended indicator variable alignment not to replace the IV with a linear sequence but to keep orginal data
* added Dec 4 2023 Added a BatchVIP calculation
* added Apr 23 2023 Corrected a very dumb mistake I made coding when tired
* added Apr 18 2023 Added descriptors routine to obtain landmarks of the batch
such as min,max,ave of a variable [during a phase if indicated so]
Modifed plot_var_all_batches to plot against the values in a Time column
and also add the legend for the BatchID
* added Apr 10 2023 Added batch contribution plots
Added build_rel_time to create a tag of relative
run time from a timestamp
* added Apr 7 2023 Added alignment using indicator variable per phase
* added Apr 5 2023 Added the capability to monitor a variable in "Soft Sensor" mode
which implies there are no measurements for it (pure prediction)
as oppose to a forecast where there are new measurments coming in time.
* added Jul 20 2022 Distribution of number of samples per phase plot
* added Aug 10 2022 refold_horizontal | clean_empty_rows | predict
* added Aug 12 2022 replicate_batch
@author: S. Garcia-Munoz [email protected] [email protected]
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pyphi as phi
# Sequence of color blind friendly colors.
cb_color_seq=['b','r','m','navy','bisque','silver','aqua','pink','gray']
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=cb_color_seq)
def unique(df,colid):
''' Replacement of the np.unique routine, specifically for dataframes
unique(df,colid)
Args:
df: A pandas dataframe
colid: Column identifier
Returns:
A list with unique values in the order found in the dataframe
by Salvador Garcia ([email protected])
'''
aux=df.drop_duplicates(subset=colid,keep='first')
unique_entries=aux[colid].values.tolist()
return unique_entries
def mean(X,axis):
X_nan_map = np.isnan(X)
X_ = X.copy()
if X_nan_map.any():
X_nan_map = X_nan_map*1
X_[X_nan_map==1] = 0
#Calculate mean without accounting for NaN'
if axis==0:
aux = np.sum(X_nan_map,axis=0)
x_mean = np.sum(X_,axis=0,keepdims=1)/(np.ones((1,X_.shape[1]))*X_.shape[0]-aux)
else:
aux = np.sum(X_nan_map,axis=1)
x_mean = np.sum(X_,axis=1,keepdims=1)/(np.ones((X_.shape[0],1))*X_.shape[1]-aux)
else:
x_mean = np.mean(X_,axis=axis,keepdims=1)
return x_mean.reshape(-1)
def simple_align(bdata,nsamples):
''' Simple alignment for bacth data using row number to linearly interpolate
to the same number of samples
bdata_aligned= simple_align(bdata,nsamples)
Args:
bdata is a Pandas DataFrame where 1st column is Batch Identifier
and following columns are variables, each row is a new
time sample. Batches are concatenated vertically.
nsamples is the new number of samples to generate per batch
irrespective of phase
Returns:
A pandas dataframe with batch data resampled to nsamples
for all batches
by Salvador Garcia Munoz ([email protected], [email protected])
'''
bdata_a=[]
if (bdata.columns[1]=='PHASE') or \
(bdata.columns[1]=='phase') or \
(bdata.columns[1]=='Phase'):
phase=True
else:
phase = False
aux=bdata.drop_duplicates(subset=bdata.columns[0],keep='first')
unique_batches=aux[aux.columns[0]].values.tolist()
for b in unique_batches:
data_=bdata[bdata[bdata.columns[0]]==b]
indx=np.arange(data_.shape[0])
new_indx=np.linspace(0,data_.shape[0]-1,nsamples)
bname_rs=[data_[bdata.columns[0]].values[0]]*nsamples
if phase:
phase_list=data_[bdata.columns[1]].values.tolist()
roundindx=np.round(new_indx).astype('int').tolist()
phase_rs=[]
for i in roundindx:
phase_rs.append(phase_list[i])
vals=data_.values[:,2:]
cols=data_.columns[2:]
else:
vals=data_.values[:,1:]
cols=data_.columns[1:]
vals_rs=np.zeros((nsamples,vals.shape[1]))
for i in np.arange(vals.shape[1]):
vals_rs[:,i]=np.interp(new_indx,indx.astype('float'),vals[:,i].astype('float'))
df_=pd.DataFrame(vals_rs,columns=cols)
if phase:
df_.insert(0,bdata.columns[1],phase_rs)
df_.insert(0,bdata.columns[0],bname_rs)
bdata_a.append(df_)
bdata_a=pd.concat(bdata_a)
return bdata_a
def phase_simple_align(bdata,nsamples):
''' Simple batch alignment (0 to 100%) per phase
bdata_aligned = phase_simple_align(bdata,nsamples)
Args:
bdata: is a Pandas DataFrame where 1st column is Batch Identifier
the second column is a phase indicator
and following columns are variables, each row is a new
time sample. Batches are concatenated vertically.
nsamples: if integer: Number of samples to collect per phase
if dictionary: samples to generate per phase e.g.
nsamples = {'Heating':100,'Reaction':200,'Cooling':10}
resampling is linear with respect to row number
Returns:
a pandas dataframe with batch data resampled (aligned)
by Salvador Garcia Munoz
'''
bdata_a=[]
if (bdata.columns[1]=='PHASE') or \
(bdata.columns[1]=='phase') or \
(bdata.columns[1]=='Phase'):
phase=True
else:
phase = False
if phase:
aux=bdata.drop_duplicates(subset=bdata.columns[0],keep='first')
unique_batches=aux[aux.columns[0]].values.tolist()
for b in unique_batches:
data_=bdata[bdata[bdata.columns[0]]==b]
vals_rs=[]
bname_rs=[]
phase_rs=[]
firstone=True
for p in nsamples.keys():
p_data= data_[data_[data_.columns[1]]==p]
samps=nsamples[p]
indx=np.arange(p_data.shape[0])
new_indx=np.linspace(0,p_data.shape[0]-1,samps)
bname_rs_=[p_data[p_data.columns[0]].values[0]]*samps
phase_rs_=[p_data[p_data.columns[1]].values[0]]*samps
vals=p_data.values[:,2:]
cols=p_data.columns[2:]
vals_rs_=np.zeros((samps,vals.shape[1]))
for i in np.arange(vals.shape[1]):
vals_rs_[:,i]=np.interp(new_indx,indx.astype('float'),vals[:,i].astype('float'))
if firstone:
vals_rs=vals_rs_
firstone=False
else:
vals_rs=np.vstack((vals_rs,vals_rs_))
bname_rs.extend(bname_rs_)
phase_rs.extend(phase_rs_)
df_=pd.DataFrame(vals_rs,columns=cols)
df_.insert(0,bdata.columns[1],phase_rs)
df_.insert(0,bdata.columns[0],bname_rs)
bdata_a.append(df_)
bdata_a=pd.concat(bdata_a)
return bdata_a
def phase_iv_align(bdata,nsamples):
''' Batch alignment using an indicator variable
batch_aligned_data = phase_iv_align(bdata,nsamples)
Args:
bdata is a Pandas DataFrame where 1st column is Batch Identifier
the second column is a phase indicator
and following columns are variables, each row is a new
time sample. Batches are concatenated vertically.
nsamples:
if nsamples is a dictionary: samples to generate per phase e.g.
nsamples = {'Heating':100,'Reaction':200,'Cooling':10}
* If an indicator variable is used, with known start and end values
indicate it with a list like this:
[IVarID,num_samples,start_value,end_value]
example:
nsamples = {'Heating':['TIC101',100,30,50],'Reaction':200,'Cooling':10}
During the 'Heating' phase use TIC101 as an indicator variable
take 100 samples equidistant from TIC101=30 to TIC101=50
and align against that variable as a measure of batch evolution (instead of time)
* If an indicator variable is used, with unknown start but known end values
indicate it with a list like this:
[IVarID,num_samples,end_value]
example:
nsamples = {'Heating':['TIC101',100,50],'Reaction':200,'Cooling':10}
During the 'Heating' phase use TIC101 as an indicator variable
take 100 samples equidistant from the value of TIC101 at the start of the phase
to the point when TIC101=50 and align against that variable as a measure
of batch evolution (instead of time)
If no IV is sent, the resampling is linear with respect to row number per phase
Returns:
A pandas dataframe with batch data resampled (aligned)
by Salvador Garcia Munoz
'''
bdata_a=[]
if (bdata.columns[1]=='PHASE') or \
(bdata.columns[1]=='phase') or \
(bdata.columns[1]=='Phase'):
phase=True
else:
phase = False
if phase:
aux=bdata.drop_duplicates(subset=bdata.columns[0],keep='first')
unique_batches=aux[aux.columns[0]].values.tolist()
for b in unique_batches:
data_=bdata[bdata[bdata.columns[0]]==b]
vals_rs=[]
bname_rs=[]
phase_rs=[]
firstone=True
for p in nsamples.keys():
p_data= data_[data_[data_.columns[1]]==p]
samps=nsamples[p]
if not(isinstance(samps,list)): #Linear alignment
indx=np.arange(p_data.shape[0])
new_indx=np.linspace(0,p_data.shape[0]-1,samps)
bname_rs_=[p_data[p_data.columns[0]].values[0]]*samps
phase_rs_=[p_data[p_data.columns[1]].values[0]]*samps
vals=p_data.values[:,2:]
cols=p_data.columns[2:]
vals_rs_=np.zeros((samps,vals.shape[1]))
for i in np.arange(vals.shape[1]):
x_=indx.astype('float')
y_=vals[:,i].astype('float')
x_=x_[~np.isnan(y_)]
y_=y_[~np.isnan(y_)]
#vals_rs_[:,i]=np.interp(new_indx,indx.astype('float'),vals[:,i].astype('float'))
if len(y_)==0:
vals_rs_[:,i]=np.nan
else:
vals_rs_[:,i]=np.interp(new_indx,x_,y_,left=np.nan,right=np.nan)
elif isinstance(samps,list): #align this phase with IV
if len(samps)==4:
iv_id=samps[0]
nsamp=samps[1]
start=samps[2]
end =samps[3]
new_indx=np.linspace(start,end,nsamp)
iv = p_data[iv_id].values.astype(float)
if len(samps)==3 :
iv_id = samps[0]
nsamp = samps[1]
end = samps[2]
if (not( isinstance(end,int) or isinstance(end,float)) and (isinstance(end,dict))
and not(firstone)):
#end is model to estimate the end value based on previous trajectory
cols=p_data.columns[2:].tolist()
fakebatch=pd.DataFrame(vals_rs,columns=cols)
fakebatch.insert(0,'phase',[p]*vals_rs.shape[0])
fakebatch.insert(0,'BatchID',[b]*vals_rs.shape[0])
preds=predict(fakebatch, end)
end_hat=preds['Yhat'][preds['Yhat'].columns[1]].values[0]
iv = p_data[iv_id].values.astype(float)
end_hat = end_hat + iv[0]
new_indx=np.linspace(iv[0],end_hat,nsamp)
else:
iv = p_data[iv_id].values.astype(float)
new_indx=np.linspace(iv[0],end,nsamp)
cols=p_data.columns[2:].tolist()
#indx_2_iv=cols.index(iv_id)
bname_rs_=[p_data[p_data.columns[0]].values[0]]*nsamp
phase_rs_=[p_data[p_data.columns[1]].values[0]]*nsamp
#Check monotonicity
if (np.all(np.diff(iv)<0) or np.all(np.diff(iv)>0)):
indx=iv
vals=p_data.values[:,2:]
#replace the IV with a linear variable (time surrogate)
#linear_indx=np.arange(vals.shape[0])
#vals[:,indx_2_iv]=linear_indx
vals_rs_=np.zeros((nsamp,vals.shape[1]))
for i in np.arange(vals.shape[1]):
x_=indx.astype('float')
y_=vals[:,i].astype('float')
x_=x_[~np.isnan(y_)]
y_=y_[~np.isnan(y_)]
#vals_rs_[:,i]=np.interp(new_indx,indx.astype('float'),vals[:,i].astype('float'))
#vals_rs_[:,i]=np.interp(new_indx,indx ,vals[:,i].astype('float'),left=np.nan,right=np.nan)
if len(y_)==0:
vals_rs_[:,i]=np.nan
else:
vals_rs_[:,i]=np.interp(new_indx,x_,y_,left=np.nan,right=np.nan)
else: #if monotonicity fails try to remove non-monotonic vals
print('Indicator variable '+iv_id+' for batch '+ b +' is not monotinic')
print('this is not ideal, maybe rethink your IV')
print('trying to remove non-monotonic samples')
x=np.arange(0,len(iv))
m=(1/sum(x**2))*sum(x*(iv-iv[0]))
#if iv[0]-iv[-1] > 0 :
if m<0:
expected_direction = -1 #decreasing IV
else:
expected_direction = 1 #increasing IV
vals=p_data.values[:,2:]
new_vals=vals[0,:]
prev_iv=iv[0]
mon_iv=[iv[0]]
for i in np.arange(1,vals.shape[0]):
if (np.sign(iv[i] - prev_iv) * expected_direction)==1: #monotonic
new_vals=np.vstack((new_vals,vals[i,:]))
prev_iv=iv[i]
mon_iv.append(iv[i])
indx=np.array(mon_iv)
vals=new_vals.copy()
#replace the IV with a linear variable (time surrogate)
#linear_indx=np.arange(vals.shape[0])
#vals[:,indx_2_iv]=linear_indx
vals_rs_=np.zeros((nsamp,vals.shape[1]))
for i in np.arange(vals.shape[1]):
x_=indx.astype('float')
y_=vals[:,i].astype('float')
x_=x_[~np.isnan(y_)]
y_=y_[~np.isnan(y_)]
#vals_rs_[:,i]=np.interp(new_indx,indx,vals[:,i].astype('float'),left=np.nan,right=np.nan)
if len(y_)==0:
vals_rs_[:,i]=np.nan
else:
vals_rs_[:,i]=np.interp(new_indx,x_,y_,left=np.nan,right=np.nan)
if firstone:
vals_rs=vals_rs_
firstone=False
else:
vals_rs=np.vstack((vals_rs,vals_rs_))
bname_rs.extend(bname_rs_)
phase_rs.extend(phase_rs_)
df_=pd.DataFrame(vals_rs,columns=cols)
df_.insert(0,bdata.columns[1],phase_rs)
df_.insert(0,bdata.columns[0],bname_rs)
bdata_a.append(df_)
bdata_a=pd.concat(bdata_a)
return bdata_a
def plot_var_all_batches(bdata,*,which_var=False,plot_title='',mkr_style='.-',
phase_samples=False,alpha_=0.2,timecolumn=False,lot_legend=False):
'''Plotting routine for batch data plot data for all batches in a dataset
plot_var_all_batches(bdata,*,which_var=False,plot_title='',mkr_style='.-',
phase_samples=False,alpha_=0.2,timecolumn=False,lot_legend=False):
Args:
bdata: Batch data organized as: column[0] = Batch Identifier column name is unrestricted
column[1] = Phase information per sample must be called 'Phase','phase', or 'PHASE'
this information is optional
column[2:]= Variables measured throughout the batch
The data for each batch is one on top of the other in a vertical matrix
which_var: Which variables are to be plotted, if not sent, all are.
plot_title: Optional text to be used as the title of all figures
phase_samples: information used to align the batch, so that phases are marked in the plot
alpha_: Transparency for the phase dividing line
timecolumn: Name of the column that indicates time, if given all data is plotted against time
lot_legend: Flag to add a legend for the batch identifiers
by Salvador Garcia Munoz
'''
var_list=which_var
if (bdata.columns[1]=='PHASE') or \
(bdata.columns[1]=='phase') or \
(bdata.columns[1]=='Phase'):
if isinstance(var_list,bool):
var_list=bdata.columns[2:].tolist()
else:
if isinstance(var_list,bool):
var_list=bdata.columns[1:].tolist()
if isinstance(var_list,str) and not(isinstance(var_list,list)):
var_list=[var_list]
for v in var_list:
plt.figure()
if not(isinstance(timecolumn,bool)):
dat=bdata[[bdata.columns[0],timecolumn,v]]
else:
dat=bdata[[bdata.columns[0],v]]
for b in np.unique(dat[bdata.columns[0]]):
data_=dat[v][dat[dat.columns[0]]==b]
if not(isinstance(timecolumn,bool)):
tim=dat[timecolumn][dat[dat.columns[0]]==b]
if lot_legend:
plt.plot(tim.values,data_.values,mkr_style,label=b)
else:
plt.plot(tim.values,data_.values,mkr_style)
plt.xlabel(timecolumn)
else:
if lot_legend:
plt.plot(1+np.arange(len(data_.values)),data_.values,mkr_style,label=b)
else:
plt.plot(1+np.arange(len(data_.values)),data_.values,mkr_style)
plt.xlabel('Sample')
plt.ylabel(v)
if lot_legend:
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
if not(isinstance(phase_samples,bool)):
s_txt=1
s_lin=1
plt.axvline(x=1,color='magenta',alpha=alpha_)
for p in phase_samples.keys():
if isinstance(phase_samples[p],list):
s_lin+=phase_samples[p][1]
else:
s_lin+=phase_samples[p]
plt.axvline(x=s_lin,color='magenta',alpha=alpha_)
ylim_=plt.ylim()
plt.annotate(p, (s_txt,ylim_[0]),rotation=90,alpha=0.5,color='magenta')
if isinstance(phase_samples[p],list):
s_txt+=phase_samples[p][1]
else:
s_txt+=phase_samples[p]
plt.title(plot_title)
plt.tight_layout()
def plot_batch(bdata,which_batch,which_var,*,include_mean_exc=False,include_set=False,
phase_samples=False,single_plot=False,plot_title=''):
'''Plotting routine for batch data
plot_batch(bdata,which_batch,which_var,*,include_mean_exc=False,include_set=False,
phase_samples=False,single_plot=False,plot_title='')
Args:
bdata: Batch data organized as: column[0] = Batch Identifier column name is unrestricted
column[1] = Phase information per sample must be called 'Phase','phase', or 'PHASE'
this information is optional
column[2:]= Variables measured throughout the batch
The data for each batch is one on top of the other in a vertical matrix
which_batch: Which batches to plot
which_var: Which variables are to be plotted, if not sent, all are.
include_mean_exc: Include the mean trajectory of the set EXCLUDING the one batch being plotted
include_set: Include all other trajectories (will be colored in light gray)
phase_samples: Information used to align the batch, so that phases are marked in the plot
single_plot: If True => Plot everything in a single axis
plot_title: Optional text to be added to the title of all figures
by Salvador Garcia Munoz
'''
if isinstance(which_batch,str) and not(isinstance(which_batch,list)):
which_batch=[which_batch]
if isinstance(which_var,str) and not(isinstance(which_var,list)):
which_var=[which_var]
if single_plot:
plt.figure()
first_pass=True
for b in which_batch:
this_batch=bdata[bdata[bdata.columns[0]]==b]
all_others=bdata[bdata[bdata.columns[0]]!=b]
for v in which_var:
this_var_this_batch=this_batch[v].values
if not(single_plot):
plt.figure()
x_axis=np.arange(len(this_var_this_batch ))+1
plt.plot(x_axis,this_var_this_batch,'k',label=b)
if include_mean_exc or include_set:
this_var_all_others=[]
max_obs=0
for bb in np.unique(all_others[bdata.columns[0]]):
this_var_all_others.append(all_others[v][all_others[bdata.columns[0]]==bb ].values)
if len(all_others[v][all_others[bdata.columns[0]]==bb ].values ) > max_obs:
max_obs = len(all_others[v][all_others[bdata.columns[0]]==bb ].values )
this_var_all_others_=[]
for bb in np.unique(all_others[bdata.columns[0]]):
_to_append=all_others[v][all_others[bdata.columns[0]]==bb ].values
this_len=len(_to_append)
_to_append=np.append(_to_append,np.tile(np.nan,max_obs-this_len))
this_var_all_others_.append(_to_append)
this_var_all_others_=np.array(this_var_all_others_)
x_axis=np.arange(max_obs)+1
if not(single_plot):
if include_set:
for t in this_var_all_others:
x_axis=np.arange(len(t))+1
plt.plot(x_axis,t,'m',alpha=0.1)
plt.plot(x_axis,this_var_all_others[-1],'m',alpha=0.1,label='rest of set')
if include_mean_exc:
plt.plot(x_axis,mean(this_var_all_others_,axis=0),'r',label='Mean without '+b )
else:
if first_pass:
if include_set:
plt.plot(x_axis,this_var_all_others_.T,'m',alpha=0.1)
plt.plot(x_axis,this_var_all_others_[0,:],'m',alpha=0.1,label='rest of set')
if include_mean_exc:
plt.plot(x_axis,mean(this_var_all_others_,axis=0),'r',label='Mean without '+b )
first_pass=False
if not(isinstance(phase_samples,bool)):
s_txt=1
s_lin=1
plt.axvline(x=1,color='magenta',alpha=0.2)
for p in phase_samples.keys():
if isinstance(phase_samples[p],list):
s_lin+=phase_samples[p][1]
else:
s_lin+=phase_samples[p]
plt.axvline(x=s_lin,color='magenta',alpha=0.2)
ylim_=plt.ylim()
plt.annotate(p, (s_txt,ylim_[0]),rotation=90,alpha=0.5,color='magenta')
if isinstance(phase_samples[p],list):
s_txt+=phase_samples[p][1]
else:
s_txt+=phase_samples[p]
plt.title(b+' ' + plot_title)
plt.xlabel('sample')
plt.ylabel(v)
plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
plt.tight_layout()
def unfold_horizontal(bdata):
if (bdata.columns[1]=='PHASE') or \
(bdata.columns[1]=='phase') or \
(bdata.columns[1]=='Phase'):
phase=True
else:
phase = False
firstone=True
clbl=[]
bid=[]
aux=bdata.drop_duplicates(subset=bdata.columns[0],keep='first')
unique_batches=aux[aux.columns[0]].values.tolist()
for b in unique_batches:
data_=bdata[bdata[bdata.columns[0]]==b]
if phase:
vals=data_.values[:,2:]
cols=data_.columns[2:]
else:
vals=data_.values[:,1:]
cols=data_.columns[1:]
row_=[]
firstone_c=True
for c in np.arange(vals.shape[1]):
r_= vals[:,[c]].reshape(1,-1)
if firstone:
for i in np.arange(1,r_.shape[1]+1):
clbl.append(cols[c]+'_'+str(i))
bid.append(cols[c] )
if firstone_c:
row_=r_
firstone_c=False
else:
row_=np.hstack((row_,r_))
if firstone:
bdata_hor=row_
firstone=False
else:
bdata_hor=np.vstack((bdata_hor,row_))
bdata_hor= pd.DataFrame(bdata_hor,columns=clbl)
bdata_hor.insert(0, bdata.columns[0],unique_batches)
return bdata_hor,clbl,bid
def refold_horizontal(xuf,nvars,nsamples):
#xuf is strictly numberical
Xb=[]
for i in np.arange(xuf.shape[0]):
r=xuf[i,:]
for v in np.arange(nvars):
var=r[:nsamples]
var=var.reshape(-1,1)
if v<(nvars-1):
r=r[nsamples:]
if v==0:
batch=var
else:
batch=np.hstack((batch,var))
if i==0:
Xb=batch
else:
Xb=np.vstack((Xb,batch))
return Xb
def _uf_l(L,spb,vpb):
first_=True
for i in np.arange(L.shape[1]):
col_=L[:,[i]]
s_=np.arange( spb )
first_flag=True
for v in np.arange(vpb):
s_2use=(s_ + v*spb)
if first_flag:
col_rearranged=col_[s_2use]
first_flag=False
else:
col_rearranged = np.hstack((col_rearranged,col_[s_2use]))
col_rearranged = col_rearranged.reshape(1,-1)
if first_:
L_uf_hor_mon = col_rearranged.T
first_ = False
else:
L_uf_hor_mon = np.hstack((L_uf_hor_mon,col_rearranged.T ))
return L_uf_hor_mon
def _uf_hor_mon_loadings(mvmobj):
spb = mvmobj['nsamples']
vpb = mvmobj['nvars']
is_pls=False
if 'Q' in mvmobj:
is_pls=True
ninit=mvmobj['ninit']
if is_pls:
if ninit > 0:
z_ws = mvmobj['Ws'][:ninit,:]
z_w = mvmobj['W'][:ninit,:]
z_p = mvmobj['P'][:ninit,:]
z_mx = mvmobj['mx'][:ninit]
z_sx = mvmobj['sx'][:ninit]
x_ws = mvmobj['Ws'][ninit:,:]
x_w = mvmobj['W'][ninit:,:]
x_p = mvmobj['P'][ninit:,:]
x_mx = mvmobj['mx'][ninit:]
x_sx = mvmobj['sx'][ninit:]
Ws_ufm = np.vstack(( z_ws,_uf_l(x_ws,spb,vpb)))
W_ufm = np.vstack(( z_w ,_uf_l(x_w ,spb,vpb)))
P_ufm = np.vstack(( z_p ,_uf_l(x_p,spb,vpb)))
mx_ufm = np.vstack(( z_mx.reshape(-1,1),_uf_l( x_mx.reshape(-1,1),spb,vpb ))).reshape(-1)
sx_ufm = np.vstack(( z_sx.reshape(-1,1),_uf_l( x_sx.reshape(-1,1),spb,vpb ))).reshape(-1)
else:
Ws_ufm = _uf_l(mvmobj['Ws'],spb,vpb)
W_ufm = _uf_l(mvmobj['W'],spb,vpb)
P_ufm = _uf_l(mvmobj['P'],spb,vpb)
mx_ufm = _uf_l( mvmobj['mx'].reshape(-1,1),spb,vpb ).reshape(-1)
sx_ufm = _uf_l( mvmobj['sx'].reshape(-1,1),spb,vpb ).reshape(-1)
else:
P_ufm = _uf_l(mvmobj['P'],spb,vpb)
mx_ufm = _uf_l( mvmobj['mx'].reshape(-1,1),spb,vpb ).reshape(-1)
sx_ufm = _uf_l( mvmobj['sx'].reshape(-1,1),spb,vpb ).reshape(-1)
if is_pls:
mvmobj['Ws_ufm'] = Ws_ufm
mvmobj['W_ufm'] = W_ufm
mvmobj['P_ufm'] = P_ufm
else:
mvmobj['P_ufm'] = P_ufm
mvmobj['mx_ufm']=mx_ufm
mvmobj['sx_ufm']=sx_ufm
return mvmobj
def loadings(mmvm_obj,dim,*,r2_weighted=False,which_var=False):
''' Plot batch loadings for variables as a function of time/sample
loadings(mmvm_obj,dim,*,r2_weighted=False,which_var=False)
Args:
mmvm_obj: Multiway PCA or PLS object
dim: What component or latent variable to plot
r2_weighted: If True => weight the loading by the R2pv
which_var: Variable for which the plot is done, if not sent all are plotted
by Salvador Garcia Munoz
'''
dim=dim-1
if 'Q' in mmvm_obj:
if mmvm_obj['ninit']==0:
if r2_weighted:
aux_df=pd.DataFrame(mmvm_obj['Ws']*mmvm_obj['r2xpv'])
else:
aux_df=pd.DataFrame(mmvm_obj['Ws'])
aux_df.insert(0,'bid',mmvm_obj['bid'])
if isinstance(which_var,bool):
vars_to_plot=unique(aux_df,'bid')
else:
if isinstance(which_var,str):
vars_to_plot=[which_var]
if isinstance(which_var,list):
vars_to_plot=which_var
for i,v in enumerate(vars_to_plot):
plt.figure()
dat=aux_df[dim][aux_df['bid']==v].values
plt.fill_between(np.arange(mmvm_obj['nsamples'])+1, dat )
plt.xlabel('sample')
if r2_weighted:
plt.ylabel('$W^* * R^2$ ['+str(dim+1)+']')
else:
plt.ylabel('$W^*$ ['+str(dim+1)+']')
plt.title(v)
plt.ylim(mmvm_obj['Ws'][:,dim].min()*1.2,mmvm_obj['Ws'][:,dim].max()*1.2 )
ylim_=plt.ylim()
phase_samples=mmvm_obj['phase_samples']
if not(isinstance(phase_samples,bool)):
s_txt=1
s_lin=1
plt.axvline(x=1,color='magenta',alpha=0.2)
for p in phase_samples.keys():
if isinstance(phase_samples[p],list):
s_lin+=phase_samples[p][1]
else:
s_lin+=phase_samples[p]
plt.axvline(x=s_lin,color='magenta',alpha=0.2)
# ylim_=[mmvm_obj['Ws'][dim,:].min()*1.2,mmvm_obj['Ws'][dim,:].max()*1.2 ]
plt.annotate(p, (s_txt,ylim_[0]),rotation=90,alpha=0.5,color='magenta')
if isinstance(phase_samples[p],list):
s_txt+=phase_samples[p][1]
else:
s_txt+=phase_samples[p]
plt.tight_layout()
else:
z_loadings= mmvm_obj['Ws'] [np.arange(mmvm_obj['ninit'])]
r2pvz = mmvm_obj['r2xpv'] [np.arange(mmvm_obj['ninit']),:]
if r2_weighted:
z_loadings = z_loadings *r2pvz
zvars = mmvm_obj['varidX'][0:mmvm_obj['ninit']]
plt.figure()
plt.bar(zvars,z_loadings[:,dim] )
plt.xticks(rotation=90)
if r2_weighted:
plt.ylabel('$W^* * R^2$ ['+str(dim+1)+']')
else:
plt.ylabel('$W^*$ ['+str(dim+1)+']')
plt.title('Loadings for Initial Conditions')
plt.tight_layout()
rows_=np.arange( mmvm_obj['nsamples']*mmvm_obj['nvars'])+mmvm_obj['ninit']
if r2_weighted:
aux_df=pd.DataFrame(mmvm_obj['Ws'][rows_,:]*mmvm_obj['r2xpv'][rows_,:] )
else:
aux_df=pd.DataFrame(mmvm_obj['Ws'][rows_,:] )
aux_df.insert(0,'bid',mmvm_obj['bid'])
if isinstance(which_var,bool):
vars_to_plot=unique(aux_df,'bid')
else:
if isinstance(which_var,str):
vars_to_plot=[which_var]
if isinstance(which_var,list):
vars_to_plot=which_var
for i,v in enumerate(vars_to_plot):
plt.figure()
dat=aux_df[dim][aux_df['bid']==v].values
plt.fill_between(np.arange(mmvm_obj['nsamples'])+1, dat )
plt.xlabel('sample')
if r2_weighted:
plt.ylabel('$W^* * R^2$ ['+str(dim+1)+']')
else:
plt.ylabel('$W^*$ ['+str(dim+1)+']')
plt.title(v)
plt.ylim(mmvm_obj['Ws'][:,dim].min()*1.2,mmvm_obj['Ws'][:,dim].max()*1.2 )
ylim_=plt.ylim()
phase_samples=mmvm_obj['phase_samples']
if not(isinstance(phase_samples,bool)):
s_txt=1
s_lin=1
plt.axvline(x=1,color='magenta',alpha=0.2)
for p in phase_samples.keys():
if isinstance(phase_samples[p],list):
s_lin+=phase_samples[p][1]
else:
s_lin+=phase_samples[p]
plt.axvline(x=s_lin,color='magenta',alpha=0.2)
# ylim_=[mmvm_obj['Ws'][dim,:].min()*1.2,mmvm_obj['Ws'][dim,:].max()*1.2 ]
plt.annotate(p, (s_txt,ylim_[0]),rotation=90,alpha=0.5,color='magenta')
if isinstance(phase_samples[p],list):
s_txt+=phase_samples[p][1]
else:
s_txt+=phase_samples[p]
plt.tight_layout()
else:
if r2_weighted:
aux_df=pd.DataFrame(mmvm_obj['P']*mmvm_obj['r2xpv'])
else:
aux_df=pd.DataFrame(mmvm_obj['P'])
aux_df.insert(0,'bid',mmvm_obj['bid'])
if isinstance(which_var,bool):
vars_to_plot=unique(aux_df,'bid')
else:
if isinstance(which_var,str):
vars_to_plot=[which_var]
if isinstance(which_var,list):
vars_to_plot=which_var
for i,v in enumerate(vars_to_plot):
plt.figure()
dat=aux_df[dim][aux_df['bid']==v].values
plt.fill_between(np.arange(mmvm_obj['nsamples'])+1, dat )
plt.xlabel('sample')
if r2_weighted:
plt.ylabel('P * $R^2$ ['+str(dim+1)+']')
else:
plt.ylabel('P ['+str(dim+1)+']')
plt.title(v)
plt.ylim(mmvm_obj['P'][:,dim].min()*1.2,mmvm_obj['P'][:,dim].max()*1.2 )
ylim_=plt.ylim()
phase_samples=mmvm_obj['phase_samples']
if not(isinstance(phase_samples,bool)):
s_txt=1
s_lin=1
plt.axvline(x=1,color='magenta',alpha=0.2)
for p in phase_samples.keys():
if isinstance(phase_samples[p],list):
s_lin+=phase_samples[p][1]
else:
s_lin+=phase_samples[p]
plt.axvline(x=s_lin,color='magenta',alpha=0.2)
#ylim_=[mmvm_obj['P'][dim,:].min()*1.2,mmvm_obj['P'][dim,:].max()*1.2 ]
plt.annotate(p, (s_txt,ylim_[0]),rotation=90,alpha=0.5,color='magenta')
if isinstance(phase_samples[p],list):
s_txt+=phase_samples[p][1]
else:
s_txt+=phase_samples[p]
plt.tight_layout()
def loadings_abs_integral(mmvm_obj,*,r2_weighted=False,addtitle=False):
'''Plot the integral of the absolute value of loadings for a batch
loadings_abs_integral(mmvm_obj,*,r2_weighted=False,addtitle=False)
Args:
mmvm_obj: A multiway PCA or PLS model
r2_weighted: Boolean flag, if True then in weights the loading by the R2pv
addtitle: Text to place in the title of the figure
by Salvador Garcia Munoz
'''
if 'Q' in mmvm_obj:
if mmvm_obj['ninit']==0:
if r2_weighted:
aux_df=pd.DataFrame(mmvm_obj['Ws']*mmvm_obj['r2xpv'])
else:
aux_df=pd.DataFrame(mmvm_obj['Ws'])
aux_df.insert(0,'bid',mmvm_obj['bid'])
else:
rows_=np.arange( mmvm_obj['nsamples']*mmvm_obj['nvars'])+mmvm_obj['ninit']
if r2_weighted:
aux_df=pd.DataFrame(mmvm_obj['Ws'][rows_,:]*mmvm_obj['r2xpv'][rows_,:] )
else:
aux_df=pd.DataFrame(mmvm_obj['Ws'][rows_,:] )
aux_df.insert(0,'bid',mmvm_obj['bid'])
integral_of_loadings=[]
aux_vname=[]
for i,v in enumerate(unique(aux_df,'bid')):
dat=aux_df[aux_df['bid']==v].values[:,1:]
integral_of_loadings.append(np.sum(np.abs(dat),axis=0,keepdims=True)[0])
aux_vname.append(v)
integral_of_loadings=np.array(integral_of_loadings)
for a in np.arange(mmvm_obj['T'].shape[1]):
plt.figure()
plt.bar(aux_vname,integral_of_loadings[:,a])
if r2_weighted:
plt.ylabel(r'$\sum (|W^*| * R^2$ ['+str(a+1)+'])')
else:
plt.ylabel(r'$\sum (|W^*|$ ['+str(a+1)+'])')
plt.xticks(rotation=75)
if not(isinstance(addtitle,bool)) and isinstance(addtitle,str):
plt.title(addtitle)
plt.tight_layout()
else:
if r2_weighted:
aux_df=pd.DataFrame(mmvm_obj['P']*mmvm_obj['r2xpv'])
else:
aux_df=pd.DataFrame(mmvm_obj['P'])
aux_df.insert(0,'bid',mmvm_obj['bid'])
integral_of_loadings=[]
aux_vname=[]
for i,v in enumerate(unique(aux_df,'bid')):
dat=aux_df[aux_df['bid']==v].values[:,1:]
integral_of_loadings.append(np.sum(np.abs(dat),axis=0,keepdims=True)[0])
aux_vname.append(v)
integral_of_loadings=np.array(integral_of_loadings)
for a in np.arange(mmvm_obj['T'].shape[1]):
plt.figure()
plt.bar(aux_vname,integral_of_loadings[:,a])
if r2_weighted:
plt.ylabel(r'$\sum (|P| * R^2$ ['+str(a+1)+'])')
else:
plt.ylabel(r'$\sum$ (|P| ['+str(a+1)+'])')
plt.xticks(rotation=75)
if not(isinstance(addtitle,bool)) and isinstance(addtitle,str):
plt.title(addtitle)
plt.tight_layout()
def batch_vip(mmvm_obj,*,addtitle=False):
''' plot the summation across componets of the integral of the absolute value of loadings for a batch
multiplied by the R2 [which kinda mimicks the VIP]
batch_vip(mmvm_obj,*,addtitle=False)
Args:
mmvm_obj: A multiway PCA or PLS model
by Salvador Garcia Munoz
'''
r2_weighted=True
if 'Q' in mmvm_obj: