forked from salvadorgarciamunoz/pyphi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyphi.py
3137 lines (2783 loc) · 127 KB
/
pyphi.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
"""
Phi for Python (pyPhi)
by Salvador Garcia (sgarciam@ic.ac.uk salvadorgarciamunoz@gmail.com)
Release TBD
What was done:
* Fixed a bug in kernel PCA calculations
* Changed the syntax of MBPLS arguments
* Corrected a pretty severe error in pls_pred
* Fixed a really bizzare one in mbpls
Release Dec 5, 2021
What was done:
*Added some small documentation to utilitie routines
Release Jan 15, 2021
What was done:
* Added routine cat_2_matrix to conver categorical classifiers to matrices
* Added Multi-block PLS model
Release Date: NOv 16, 2020
What was done:
* Fixed small bug un clean_low_variances routine
Release Date: Sep 26 2020
What was done:
* Added rotation of loadings so that var(t) for ti>=0 is always larger
than var(t) for ti<0
Release Date: May 27 2020
What was done:
* Added the estimation of PLS models with missind data using
non-linear programming per Journal of Chemometrics, 28(7), pp.575-584.
Release Date: March 30 2020
What was done:
* Added the estimation of PCA models with missing data using
non-linear programming per Lopez-Negrete et al. J. Chemometrics 2010; 24: 301–311
Release Date: Aug 22 2019
What was done:
* This header is now included to track high level changes
* fixed LWPLS it works now for scalar and multivariable Y's
* fixed minor bug in phi.pca and phi.pls when mcsX/Y = False
"""
import numpy as np
import pandas as pd
import datetime
from scipy.special import factorial
from scipy import interpolate
try:
from pyomo.environ import *
pyomo_ok = True
except ImportError:
pyomo_ok = False
gams_ok = False # GAMS is run via pyomo
# Check if an IPOPT binary available is availbale
# shutil was introduced in Python 3.2
from shutil import which
ipopt_ok = bool(which('ipopt'))
# Check for Pyomo/GAMS interface is available
if pyomo_ok:
from pyomo.solvers.plugins.solvers.GAMS import GAMSDirect, GAMSShell
# exeption_flag = True (default) will throw an exception if GAMS
# is not available
gams_ok = (GAMSDirect().available(exception_flag=False)
or GAMSShell().available(exception_flag=False))
def ma57_dummy_check():
"""
Instantiates a trivial NLP to solve with IPOPT and MA57.
Returns:
ma57_ok: boolean, True if IPOPT solved with SolverStaus.ok
"""
m = ConcreteModel()
m.x = Var()
m.Obj = Objective(expr = m.x**2 -1)
s = SolverFactory('ipopt')
s.options['linear_solver'] = 'ma57'
import logging
pyomo_logger = logging.getLogger('pyomo.core')
LOG_DEFAULT = pyomo_logger.level
pyomo_logger.setLevel(logging.ERROR)
r = s.solve(m)
pyomo_logger.setLevel(LOG_DEFAULT)
ma57_ok = r.solver.status == SolverStatus.ok
if ma57_ok:
print("MA57 available to IPOPT")
return ma57_ok
if pyomo_ok and ipopt_ok:
ma57_ok = ma57_dummy_check()
else:
ma57_ok = False
def pca (X,A,*,mcs=True,md_algorithm='nipals',force_nipals=False,shush=False,cross_val=0):
""" Principal Components Analysis routine
by Salvador Garcia-Munoz
(sgarciam@ic.ac.uk ,salvadorgarciamunoz@gmail.com)
Inputs:
X : Either a pandas dataframe, or a Numpy Matrix
A : Number of Principal Components to calculate
mcs: 'True' : Meancenter + autoscale *default if not sent*
'False' : No pre-processing
'center' : Only center
'autoscale' : Only autoscale
md_algorithm: Missing Data algorithm to use
'nipals' *default if not sent*
'nlp' Uses non-linear programming approach by Lopez-Negrete et al. J. Chemometrics 2010; 24: 301–311
force_nipals: If = True will use NIPALS.
= False if X is complete will use SVD. *default if not sent*
shush: If = True supressess all printed output
= False *default if not sent*
cross_val: If sent a scalar between 0 and 100, will cross validate
element wise removing cross_val% of the data every round
if == 0: Bypass cross-validation *default if not sent*
Output:
A dictionary with all PCA loadings, scores and other diagnostics.
"""
if cross_val==0:
pcaobj= pca_(X,A,mcs=mcs,md_algorithm=md_algorithm,force_nipals=force_nipals,shush=shush)
elif (cross_val > 0) and (cross_val<100):
if isinstance(X,np.ndarray):
X_=X.copy()
elif isinstance(X,pd.DataFrame):
X_=np.array(X.values[:,1:]).astype(float)
#Mean center and scale according to flags
if isinstance(mcs,bool):
if mcs:
#Mean center and autoscale
X_,x_mean,x_std = meancenterscale(X_)
else:
x_mean = np.zeros((1,X_.shape[1]))
x_std = np.ones((1,X_.shape[1]))
elif mcs=='center':
#only center
X_,x_mean,x_std = meancenterscale(X_,mcs='center')
elif mcs=='autoscale':
#only autoscale
X_,x_mean,x_std = meancenterscale(X_,mcs='autoscale')
#Generate Missing Data Map
X_nan_map = np.isnan(X_)
not_Xmiss = (np.logical_not(X_nan_map))*1
#Initialize TSS per var vector
X_,Xnanmap=n2z(X_)
TSS = np.sum(X_**2)
TSSpv = np.sum(X_**2,axis=0)
cols = X_.shape[1]
rows = X_.shape[0]
X_ = z2n(X_,Xnanmap)
for a in list(range(A)):
if not(shush):
print('Cross validating PC #'+str(a+1))
#Generate cross-val map starting from missing data
not_removed_map = not_Xmiss.copy()
not_removed_map = np.reshape(not_removed_map,(rows*cols,-1))
#Generate matrix of random numbers and zero out nans
Xrnd = np.random.random(X_.shape)*not_Xmiss
indx = np.argsort(np.reshape(Xrnd,(Xrnd.shape[0]*Xrnd.shape[1])))
elements_to_remove_per_round = np.int(np.ceil((X_.shape[0]*X_.shape[1]) * (cross_val/100)))
error = np.zeros((rows*cols,1))
rounds=1
while np.sum(not_removed_map) > 0 :#While there are still elements to be removed
#if not(shush):
# print('Removing samples round #'+str(rounds)+' for component :'+str(a+1))
rounds=rounds+1
X_copy=X_.copy()
if indx.size > elements_to_remove_per_round:
indx_this_round = indx[0:elements_to_remove_per_round]
indx = indx[elements_to_remove_per_round:]
else:
indx_this_round = indx
#Place NaN's
X_copy = np.reshape(X_copy,(rows*cols,1))
elements_out = X_copy[indx_this_round]
X_copy[indx_this_round] = np.nan
X_copy = np.reshape(X_copy,(rows,cols))
#update map
not_removed_map[indx_this_round] = 0
#look rows of missing data
auxmap = np.isnan(X_copy)
auxmap= (auxmap)*1
auxmap=np.sum(auxmap,axis=1)
indx2 = np.where(auxmap==X_copy.shape[1])
indx2=indx2[0].tolist()
if len(indx2) > 0:
X_copy=np.delete(X_copy,indx2,0)
pcaobj_ = pca_(X_copy,1,mcs=False,shush=True)
xhat = pcaobj_['T'] @ pcaobj_['P'].T
xhat = np.insert(xhat, indx2,np.nan,axis=0)
xhat = np.reshape(xhat,(rows*cols,1))
error[indx_this_round] = elements_out - xhat[indx_this_round]
error = np.reshape(error,(rows,cols))
error,dummy = n2z(error)
PRESSpv = np.sum(error**2,axis=0)
PRESS = np.sum(error**2)
if a==0:
q2 = 1 - PRESS/TSS
q2pv = 1 - PRESSpv/TSSpv
q2pv = q2pv.reshape(-1,1)
else:
q2 = np.hstack((q2,1 - PRESS/TSS))
aux_ = 1-PRESSpv/TSSpv
aux_ = aux_.reshape(-1,1)
q2pv = np.hstack((q2pv,aux_))
#Deflate and go to next PC
X_copy=X_.copy()
pcaobj_ = pca_(X_copy,1,mcs=False,shush=True)
xhat = pcaobj_['T'] @ pcaobj_['P'].T
X_,Xnanmap=n2z(X_)
X_ = (X_ - xhat) * not_Xmiss
if a==0:
r2 = 1-np.sum(X_**2)/TSS
r2pv = 1-np.sum(X_**2,axis=0)/TSSpv
r2pv = r2pv.reshape(-1,1)
else:
r2 = np.hstack((r2,1-np.sum(X_**2)/TSS))
aux_ = 1-np.sum(X_**2,axis=0)/TSSpv
aux_ = aux_.reshape(-1,1)
r2pv = np.hstack((r2pv,aux_))
X_ = z2n(X_,Xnanmap)
# Fit full model
pcaobj = pca_(X,A,mcs=mcs,force_nipals=True,shush=True)
for a in list(range(A-1,0,-1)):
r2[a] = r2[a]-r2[a-1]
r2pv[:,a] = r2pv[:,a]-r2pv[:,a-1]
q2[a] = q2[a]-q2[a-1]
q2pv[:,a] = q2pv[:,a]-q2pv[:,a-1]
r2xc = np.cumsum(r2)
q2xc = np.cumsum(q2)
eigs = np.var(pcaobj['T'],axis=0)
pcaobj['q2'] = q2
pcaobj ['q2pv'] = q2pv
if not(shush):
print('phi.pca using NIPALS and cross validation ('+str(cross_val)+'%) executed on: '+ str(datetime.datetime.now()) )
print('--------------------------------------------------------------')
print('PC # Eig R2X sum(R2X) Q2X sum(Q2X)')
if A>1:
for a in list(range(A)):
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f} {:.3f} {:.3f}".format(eigs[a], r2[a], r2xc[a],q2[a],q2xc[a]))
else:
d1=eigs[0]
d2=r2xc[0]
d3=q2xc[0]
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f} {:.3f} {:.3f}".format(d1, r2, d2,q2,d3))
print('--------------------------------------------------------------')
else:
pcaobj='Cannot cross validate with those options'
return pcaobj
def pca_(X,A,*,mcs=True,md_algorithm='nipals',force_nipals=False,shush=False):
if isinstance(X,np.ndarray):
X_=X.copy()
obsidX = False
varidX = False
elif isinstance(X,pd.DataFrame):
X_=np.array(X.values[:,1:]).astype(float)
obsidX = X.values[:,0].astype(str)
obsidX = obsidX.tolist()
varidX = X.columns.values
varidX = varidX[1:]
varidX = varidX.tolist()
if isinstance(mcs,bool):
if mcs:
#Mean center and autoscale
X_,x_mean,x_std = meancenterscale(X_)
else:
x_mean = np.zeros((1,X_.shape[1]))
x_std = np.ones((1,X_.shape[1]))
elif mcs=='center':
X_,x_mean,x_std = meancenterscale(X_,mcs='center')
#only center
elif mcs=='autoscale':
#only autoscale
X_,x_mean,x_std = meancenterscale(X_,mcs='autoscale')
#Generate Missing Data Map
X_nan_map = np.isnan(X_)
not_Xmiss = (np.logical_not(X_nan_map))*1
if not(X_nan_map.any()) and not(force_nipals) and ((X_.shape[1]/X_.shape[0]>=10) or (X_.shape[0]/X_.shape[1]>=10)):
#no missing elements
if not(shush):
print('phi.pca using SVD executed on: '+ str(datetime.datetime.now()) )
TSS = np.sum(X_**2)
TSSpv = np.sum(X_**2,axis=0)
if X_.shape[1]/X_.shape[0]>=10:
[U,S,Th] = np.linalg.svd(X_ @ X_.T)
T = Th.T
T = T[:,0:A]
P = X_.T @ T
for a in list(range(A)):
P[:,a] = P[:,a]/np.linalg.norm(P[:,a])
T = X_ @ P
elif X_.shape[0]/X_.shape[1]>=10:
[U,S,Ph] = np.linalg.svd(X_.T @ X_)
P = Ph.T
P = P[:,0:A]
T = X_ @ P
for a in list(range(A)):
X_ = X_- T[:,[a]]@P[:,[a]].T
if a==0:
r2 = 1-np.sum(X_**2)/TSS
r2pv = 1-np.sum(X_**2,axis=0)/TSSpv
r2pv = r2pv.reshape(-1,1)
else:
r2 = np.hstack((r2, 1-np.sum(X_**2)/TSS))
aux_ = 1-(np.sum(X_**2,axis=0)/TSSpv)
r2pv = np.hstack((r2pv,aux_.reshape(-1,1)))
for a in list(range(A-1,0,-1)):
r2[a] = r2[a]-r2[a-1]
r2pv[:,a] = r2pv[:,a]-r2pv[:,a-1]
pca_obj={'T':T,'P':P,'r2x':r2,'r2xpv':r2pv,'mx':x_mean,'sx':x_std}
if not isinstance(obsidX,bool):
pca_obj['obsidX']=obsidX
pca_obj['varidX']=varidX
eigs = np.var(T,axis=0);
r2xc = np.cumsum(r2)
if not(shush):
print('--------------------------------------------------------------')
print('PC # Eig R2X sum(R2X) ')
if A>1:
for a in list(range(A)):
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f}".format(eigs[a], r2[a], r2xc[a]))
else:
d1=eigs[0]
d2=r2xc[0]
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f}".format(d1, r2, d2))
print('--------------------------------------------------------------')
T2 = hott2(pca_obj,Tnew=T)
n = T.shape[0]
T2_lim99 = (((n-1)*(n+1)*A)/(n*(n-A)))*f99(A,(n-A))
T2_lim95 = (((n-1)*(n+1)*A)/(n*(n-A)))*f95(A,(n-A))
speX = np.sum(X_**2,axis=1,keepdims=1)
speX_lim95,speX_lim99 = spe_ci(speX)
pca_obj['T2'] = T2
pca_obj['T2_lim99']= T2_lim99
pca_obj['T2_lim95']= T2_lim95
pca_obj['speX']= speX
pca_obj['speX_lim99']= speX_lim99
pca_obj['speX_lim95']= speX_lim95
return pca_obj
else:
if md_algorithm=='nipals':
#use nipals
if not(shush):
print('phi.pca using NIPALS executed on: '+ str(datetime.datetime.now()) )
X_,dummy=n2z(X_)
epsilon=1E-10
maxit=5000
TSS = np.sum(X_**2)
TSSpv = np.sum(X_**2,axis=0)
#T=[];
#P=[];
#r2=[];
#r2pv=[];
#numIT=[];
for a in list(range(A)):
# Select column with largest variance as initial guess
ti = X_[:,[np.argmax(std(X_))]]
Converged=False
num_it=0
while Converged==False:
#Step 1. p(i)=t' x(i)/t't
timat=np.tile(ti,(1,X_.shape[1]))
pi=(np.sum(X_*timat,axis=0))/(np.sum((timat*not_Xmiss)**2,axis=0))
#Step 2. Normalize p to unit length.
pi=pi/np.linalg.norm(pi)
#Step 3. tnew= (x*p) / (p'p);
pimat=np.tile(pi,(X_.shape[0],1))
tn= X_ @ pi.T
ptp=np.sum((pimat*not_Xmiss)**2,axis=1)
tn=tn/ptp
pi=pi.reshape(-1,1)
if abs((np.linalg.norm(ti)-np.linalg.norm(tn)))/(np.linalg.norm(ti)) < epsilon:
Converged=True
if num_it > maxit:
Converged=True
if Converged:
if np.var(ti[ti<0]) > np.var(ti[ti>=0]):
tn=-tn
ti=-ti
pi=-pi
if not(shush):
print('# Iterations for PC #'+str(a+1)+': ',str(num_it))
if a==0:
T=tn.reshape(-1,1)
P=pi
else:
T=np.hstack((T,tn.reshape(-1,1)))
P=np.hstack((P,pi))
# Deflate X leaving missing as zeros (important!)
X_=(X_- ti @ pi.T)*not_Xmiss
if a==0:
r2 = 1-np.sum(X_**2)/TSS
r2pv = 1-np.sum(X_**2,axis=0)/TSSpv
r2pv = r2pv.reshape(-1,1)
else:
r2 = np.hstack((r2,1-np.sum(X_**2)/TSS))
aux_ = 1-np.sum(X_**2,axis=0)/TSSpv
aux_ = aux_.reshape(-1,1)
r2pv = np.hstack((r2pv,aux_))
else:
num_it = num_it + 1
ti = tn.reshape(-1,1)
if a==0:
numIT=num_it
else:
numIT=np.hstack((numIT,num_it))
for a in list(range(A-1,0,-1)):
r2[a] = r2[a]-r2[a-1]
r2pv[:,a] = r2pv[:,a]-r2pv[:,a-1]
eigs = np.var(T,axis=0);
r2xc = np.cumsum(r2)
if not(shush):
print('--------------------------------------------------------------')
print('PC # Eig R2X sum(R2X) ')
if A>1:
for a in list(range(A)):
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f}".format(eigs[a], r2[a], r2xc[a]))
else:
d1=eigs[0]
d2=r2xc[0]
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f}".format(d1, r2, d2))
print('--------------------------------------------------------------')
pca_obj={'T':T,'P':P,'r2x':r2,'r2xpv':r2pv,'mx':x_mean,'sx':x_std}
if not isinstance(obsidX,bool):
pca_obj['obsidX']=obsidX
pca_obj['varidX']=varidX
T2 = hott2(pca_obj,Tnew=T)
n = T.shape[0]
T2_lim99 = (((n-1)*(n+1)*A)/(n*(n-A)))*f99(A,(n-A))
T2_lim95 = (((n-1)*(n+1)*A)/(n*(n-A)))*f95(A,(n-A))
speX = np.sum(X_**2,axis=1,keepdims=1)
speX_lim95,speX_lim99 = spe_ci(speX)
pca_obj['T2'] = T2
pca_obj['T2_lim99']= T2_lim99
pca_obj['T2_lim95']= T2_lim95
pca_obj['speX']= speX
pca_obj['speX_lim99']= speX_lim99
pca_obj['speX_lim95']= speX_lim95
return pca_obj
elif md_algorithm=='nlp' and pyomo_ok:
#use NLP per Lopez-Negrete et al. J. Chemometrics 2010; 24: 301–311
if not(shush):
print('phi.pca using NLP with Ipopt executed on: '+ str(datetime.datetime.now()) )
pcaobj_= pca_(X,A,mcs=mcs,md_algorithm='nipals',shush=True)
pcaobj_= prep_pca_4_MDbyNLP(pcaobj_,X_)
TSS = np.sum(X_**2)
TSSpv = np.sum(X_**2,axis=0)
#Set up the model in Pyomo
model = ConcreteModel()
model.A = Set(initialize = pcaobj_['pyo_A'] )
model.N = Set(initialize = pcaobj_['pyo_N'] )
model.O = Set(initialize = pcaobj_['pyo_O'] )
model.P = Var(model.N,model.A, within = Reals,initialize = pcaobj_['pyo_P_init'])
model.T = Var(model.O,model.A, within = Reals,initialize = pcaobj_['pyo_T_init'])
model.psi = Param(model.O,model.N,initialize = pcaobj_['pyo_psi'])
model.X = Param(model.O,model.N,initialize = pcaobj_['pyo_X'])
model.delta = Param(model.A, model.A, initialize=lambda model, a1, a2: 1.0 if a1==a2 else 0)
# Constraints 20b
def _c20b_con(model, a1, a2):
return sum(model.P[j, a1] * model.P[j, a2] for j in model.N) == model.delta[a1, a2]
model.c20b = Constraint(model.A, model.A, rule=_c20b_con)
# Constraints 20c
def _20c_con(model, a1, a2):
if a2 < a1:
return sum(model.T[o, a1] * model.T[o, a2] for o in model.O) == 0
else:
return Constraint.Skip
model.c20c = Constraint(model.A, model.A, rule=_20c_con)
# Constraints 20d
def mean_zero(model,i):
return sum (model.T[o,i] for o in model.O )==0
model.eq3 = Constraint(model.A,rule=mean_zero)
def _eq_20a_obj(model):
return sum(sum((model.X[o,n]- model.psi[o,n] * sum(model.T[o,a] * model.P[n,a] for a in model.A))**2 for n in model.N) for o in model.O)
model.obj = Objective(rule=_eq_20a_obj)
# Setup our solver as either local ipopt, gams:ipopt, or neos ipopt:
if (ipopt_ok):
print("Solving NLP using local IPOPT executable")
solver = SolverFactory('ipopt')
if (ma57_ok):
solver.options['linear_solver'] = 'ma57'
results = solver.solve(model,tee=True)
elif (gams_ok):
print("Solving NLP using GAMS/IPOPT interface")
# 'just 'ipopt' could work, if no binary in path
solver = SolverFactory('gams:ipopt')
# It doesn't seem to notice the opt file when I write it
results = solver.solve(model, tee=True)
else:
print("Solving NLP using IPOPT on remote NEOS server")
solver_manager = SolverManagerFactory('neos')
results = solver_manager.solve(model, opt='ipopt', tee=True)
T=[]
for o in model.O:
t=[]
for a in model.A:
t.append(value(model.T[o,a]))
T.append(t)
T=np.array(T)
P=[]
for n in model.N:
p=[]
for a in model.A:
p.append(value(model.P[n,a]))
P.append(p)
P=np.array(P)
# Calculate R2
for a in list(range(0, A)):
ti=T[:,[a]]
pi=P[:,[a]]
if np.var(ti[ti<0]) > np.var(ti[ti>=0]):
ti=-ti
pi=-pi
T[:,[a]]=-T[:,[a]]
P[:,[a]]=-P[:,[a]]
X_=(X_- ti @ pi.T)*not_Xmiss
if a==0:
r2 = 1-np.sum(X_**2)/TSS
r2pv = 1-np.sum(X_**2,axis=0)/TSSpv
r2pv = r2pv.reshape(-1,1)
else:
r2 = np.hstack((r2,1-np.sum(X_**2)/TSS))
aux_ = 1-np.sum(X_**2,axis=0)/TSSpv
aux_ = aux_.reshape(-1,1)
r2pv = np.hstack((r2pv,aux_))
for a in list(range(A-1,0,-1)):
r2[a] = r2[a]-r2[a-1]
r2pv[:,a] = r2pv[:,a]-r2pv[:,a-1]
eigs = np.var(T,axis=0);
r2xc = np.cumsum(r2)
if not(shush):
print('--------------------------------------------------------------')
print('PC # Eig R2X sum(R2X) ')
if A>1:
for a in list(range(A)):
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f}".format(eigs[a], r2[a], r2xc[a]))
else:
d1=eigs[0]
d2=r2xc[0]
print("PC #"+str(a+1)+": {:8.3f} {:.3f} {:.3f}".format(d1, r2, d2))
print('--------------------------------------------------------------')
pca_obj={'T':T,'P':P,'r2x':r2,'r2xpv':r2pv,'mx':x_mean,'sx':x_std}
if not isinstance(obsidX,bool):
pca_obj['obsidX']=obsidX
pca_obj['varidX']=varidX
T2 = hott2(pca_obj,Tnew=T)
n = T.shape[0]
T2_lim99 = (((n-1)*(n+1)*A)/(n*(n-A)))*f99(A,(n-A))
T2_lim95 = (((n-1)*(n+1)*A)/(n*(n-A)))*f95(A,(n-A))
speX = np.sum(X_**2,axis=1,keepdims=1)
speX_lim95,speX_lim99 = spe_ci(speX)
pca_obj['T2'] = T2
pca_obj['T2_lim99']= T2_lim99
pca_obj['T2_lim95']= T2_lim95
pca_obj['speX']= speX
pca_obj['speX_lim99']= speX_lim99
pca_obj['speX_lim95']= speX_lim95
return pca_obj
elif md_algorithm=='nlp' and not( pyomo_ok):
print('Pyomo was not found in your system sorry')
print('visit http://www.pyomo.org/ ')
pca_obj=1
return pca_obj
def pls(X,Y,A,*,mcsX=True,mcsY=True,md_algorithm='nipals',force_nipals=False,shush=False,cross_val=0,cross_val_X=False):
""" Projection to Latent Structures routine
by Salvador Garcia-Munoz
(sgarciam@ic.ac.uk ,salvadorgarciamunoz@gmail.com)
Inputs:
X,Y : Either a pandas dataframe, or a Numpy Matrix
A : Number of Principal Components to calculate
mcsX/mcsY: 'True' : Will meancenter and autoscale the data *default if not sent*
'False' : No pre-processing
'center' : Will only center
'autoscale' : Will only autoscale
md_algorithm: 'nipals' *default*
'nlp' Uses algorithm described in Journal of Chemometrics, 28(7), pp.575-584.
force_nipals: If set to True and if X is complete, will use NIPALS.
Otherwise, if X is complete will use SVD.
shush: If set to True supressess all printed output.
cross_val: If sent a scalar between 0 and 100, will cross validate
element wise removing cross_val% of the data every round
if == 0: Bypass cross-validation *default if not sent*
cross_val_X: 'True' : Calculates Q2 values for the X and Y matrices
'False': Cross-validation strictly on Y matrix *default if not sent*
Output:
A dictionary with all PLS loadings, scores and other diagnostics.
"""
if cross_val==0:
plsobj = pls_(X,Y,A,mcsX=mcsX,mcsY=mcsY,md_algorithm=md_algorithm,force_nipals=force_nipals,shush=shush)
elif (cross_val > 0) and (cross_val<100):
if isinstance(X,np.ndarray):
X_=X.copy()
elif isinstance(X,pd.DataFrame):
X_=np.array(X.values[:,1:]).astype(float)
#Mean center and scale according to flags
if isinstance(mcsX,bool):
if mcsX:
#Mean center and autoscale
X_,x_mean,x_std = meancenterscale(X_)
else:
x_mean = np.zeros((1,X_.shape[1]))
x_std = np.ones((1,X_.shape[1]))
elif mcsX=='center':
#only center
X_,x_mean,x_std = meancenterscale(X_,mcs='center')
elif mcsX=='autoscale':
#only autoscale
X_,x_mean,x_std = meancenterscale(X_,mcs='autoscale')
#Generate Missing Data Map
X_nan_map = np.isnan(X_)
not_Xmiss = (np.logical_not(X_nan_map))*1
if isinstance(Y,np.ndarray):
Y_=Y.copy()
elif isinstance(Y,pd.DataFrame):
Y_=np.array(Y.values[:,1:]).astype(float)
#Mean center and scale according to flags
if isinstance(mcsY,bool):
if mcsY:
#Mean center and autoscale
Y_,y_mean,y_std = meancenterscale(Y_)
else:
y_mean = np.zeros((1,Y_.shape[1]))
y_std = np.ones((1,Y_.shape[1]))
elif mcsY=='center':
#only center
Y_,y_mean,y_std = meancenterscale(Y_,mcs='center')
elif mcsY=='autoscale':
#only autoscale
Y_,y_mean,y_std = meancenterscale(Y_,mcs='autoscale')
#Generate Missing Data Map
Y_nan_map = np.isnan(Y_)
not_Ymiss = (np.logical_not(Y_nan_map))*1
#Initialize TSS per var vector
X_,Xnanmap=n2z(X_)
TSSX = np.sum(X_**2)
TSSXpv = np.sum(X_**2,axis=0)
colsX = X_.shape[1]
rowsX = X_.shape[0]
X_ = z2n(X_,Xnanmap)
Y_,Ynanmap=n2z(Y_)
TSSY = np.sum(Y_**2)
TSSYpv = np.sum(Y_**2,axis=0)
colsY = Y_.shape[1]
rowsY = Y_.shape[0]
Y_ = z2n(Y_,Ynanmap)
for a in list(range(A)):
if not(shush):
print('Cross validating LV #'+str(a+1))
#Generate cross-val map starting from missing data
not_removed_mapY = not_Ymiss.copy()
not_removed_mapY = np.reshape(not_removed_mapY,(rowsY*colsY,-1))
#Generate matrix of random numbers and zero out nans
Yrnd = np.random.random(Y_.shape)*not_Ymiss
indxY = np.argsort(np.reshape(Yrnd,(Yrnd.shape[0]*Yrnd.shape[1])))
elements_to_remove_per_roundY = np.int(np.ceil((Y_.shape[0]*Y_.shape[1]) * (cross_val/100)))
errorY = np.zeros((rowsY*colsY,1))
if cross_val_X:
#Generate cross-val map starting from missing data
not_removed_mapX = not_Xmiss.copy()
not_removed_mapX = np.reshape(not_removed_mapX,(rowsX*colsX,-1))
#Generate matrix of random numbers and zero out nans
Xrnd = np.random.random(X_.shape)*not_Xmiss
indxX = np.argsort(np.reshape(Xrnd,(Xrnd.shape[0]*Xrnd.shape[1])))
elements_to_remove_per_roundX = np.int(np.ceil((X_.shape[0]*X_.shape[1]) * (cross_val/100)))
errorX = np.zeros((rowsX*colsX,1))
else:
not_removed_mapX=0
number_of_rounds=1
while np.sum(not_removed_mapX) > 0 or np.sum(not_removed_mapY) > 0 :#While there are still elements to be removed
#if not(shush):
# print('Random removal round #'+ str(number_of_rounds))
number_of_rounds=number_of_rounds+1
X_copy=X_.copy()
if cross_val_X:
if indxX.size > elements_to_remove_per_roundX:
indx_this_roundX = indxX[0:elements_to_remove_per_roundX]
indxX = indxX[elements_to_remove_per_roundX:]
else:
indx_this_roundX = indxX
#Place NaN's
X_copy = np.reshape(X_copy,(rowsX*colsX,1))
elements_outX = X_copy[indx_this_roundX]
X_copy[indx_this_roundX] = np.nan
X_copy = np.reshape(X_copy,(rowsX,colsX))
#update map
not_removed_mapX[indx_this_roundX] = 0
#look rows of missing data
auxmap = np.isnan(X_copy)
auxmap= (auxmap)*1
auxmap=np.sum(auxmap,axis=1)
indx2 = np.where(auxmap==X_copy.shape[1])
indx2=indx2[0].tolist()
else:
indx2=[];
Y_copy=Y_.copy()
if indxY.size > elements_to_remove_per_roundY:
indx_this_roundY = indxY[0:elements_to_remove_per_roundY]
indxY = indxY[elements_to_remove_per_roundY:]
else:
indx_this_roundY = indxY
#Place NaN's
Y_copy = np.reshape(Y_copy,(rowsY*colsY,1))
elements_outY = Y_copy[indx_this_roundY]
Y_copy[indx_this_roundY] = np.nan
Y_copy = np.reshape(Y_copy,(rowsY,colsY))
#update map
not_removed_mapY[indx_this_roundY] = 0
#look rows of missing data
auxmap = np.isnan(Y_copy)
auxmap = (auxmap)*1
auxmap = np.sum(auxmap,axis=1)
indx3 = np.where(auxmap==Y_copy.shape[1])
indx3 = indx3[0].tolist()
indx4 = np.unique(indx3+indx2)
indx4 = indx4.tolist()
if len(indx4) > 0:
X_copy=np.delete(X_copy,indx4,0)
Y_copy=np.delete(Y_copy,indx4,0)
#print('Running PLS')
plsobj_ = pls_(X_copy,Y_copy,1,mcsX=False,mcsY=False,shush=True)
#print('Done with PLS')
plspred = pls_pred(X_,plsobj_)
if cross_val_X:
xhat = plspred['Tnew'] @ plsobj_['P'].T
xhat = np.reshape(xhat,(rowsX*colsX,1))
errorX[indx_this_roundX] = elements_outX - xhat[indx_this_roundX]
yhat = plspred['Tnew'] @ plsobj_['Q'].T
yhat = np.reshape(yhat,(rowsY*colsY,1))
errorY[indx_this_roundY] = elements_outY - yhat[indx_this_roundY]
if cross_val_X:
errorX = np.reshape(errorX,(rowsX,colsX))
errorX,dummy = n2z(errorX)
PRESSXpv = np.sum(errorX**2,axis=0)
PRESSX = np.sum(errorX**2)
errorY = np.reshape(errorY,(rowsY,colsY))
errorY,dummy = n2z(errorY)
PRESSYpv = np.sum(errorY**2,axis=0)
PRESSY = np.sum(errorY**2)
if a==0:
q2Y = 1 - PRESSY/TSSY
q2Ypv = 1 - PRESSYpv/TSSYpv
q2Ypv = q2Ypv.reshape(-1,1)
if cross_val_X:
q2X = 1 - PRESSX/TSSX
q2Xpv = 1 - PRESSXpv/TSSXpv
q2Xpv = q2Xpv.reshape(-1,1)
else:
q2Y = np.hstack((q2Y,1 - PRESSY/TSSY))
aux_ = 1-PRESSYpv/TSSYpv
aux_ = aux_.reshape(-1,1)
q2Ypv = np.hstack((q2Ypv,aux_))
if cross_val_X:
q2X = np.hstack((q2X,1 - PRESSX/TSSX))
aux_ = 1-PRESSXpv/TSSXpv
aux_ = aux_.reshape(-1,1)
q2Xpv = np.hstack((q2Xpv,aux_))
#Deflate and go to next PC
X_copy=X_.copy()
Y_copy=Y_.copy()
plsobj_ = pls_(X_copy,Y_copy,1,mcsX=False,mcsY=False,shush=True)
xhat = plsobj_['T'] @ plsobj_['P'].T
yhat = plsobj_['T'] @ plsobj_['Q'].T
X_,Xnanmap=n2z(X_)
Y_,Ynanmap=n2z(Y_)
X_ = (X_ - xhat) * not_Xmiss
Y_ = (Y_ - yhat) * not_Ymiss
if a==0:
r2X = 1-np.sum(X_**2)/TSSX
r2Xpv = 1-np.sum(X_**2,axis=0)/TSSXpv
r2Xpv = r2Xpv.reshape(-1,1)
r2Y = 1-np.sum(Y_**2)/TSSY
r2Ypv = 1-np.sum(Y_**2,axis=0)/TSSYpv
r2Ypv = r2Ypv.reshape(-1,1)
else:
r2X = np.hstack((r2X,1-np.sum(X_**2)/TSSX))
aux_ = 1-np.sum(X_**2,axis=0)/TSSXpv
aux_ = aux_.reshape(-1,1)
r2Xpv = np.hstack((r2Xpv,aux_))
r2Y = np.hstack((r2Y,1-np.sum(Y_**2)/TSSY))
aux_ = 1-np.sum(Y_**2,axis=0)/TSSYpv
aux_ = aux_.reshape(-1,1)
r2Ypv = np.hstack((r2Ypv,aux_))
X_ = z2n(X_,Xnanmap)
Y_ = z2n(Y_,Ynanmap)
# Fit full model
plsobj = pls_(X,Y,A,mcsX=mcsX,mcsY=mcsY,shush=True)
for a in list(range(A-1,0,-1)):
r2X[a] = r2X[a]-r2X[a-1]
r2Xpv[:,a] = r2Xpv[:,a]-r2Xpv[:,a-1]
if cross_val_X:
q2X[a] = q2X[a]-q2X[a-1]
q2Xpv[:,a] = q2Xpv[:,a]-q2Xpv[:,a-1]
else:
q2X = False
q2Xpv = False
r2Y[a] = r2Y[a]-r2Y[a-1]
r2Ypv[:,a] = r2Ypv[:,a]-r2Ypv[:,a-1]
q2Y[a] = q2Y[a]-q2Y[a-1]
q2Ypv[:,a] = q2Ypv[:,a]-q2Ypv[:,a-1]
r2xc = np.cumsum(r2X)
r2yc = np.cumsum(r2Y)
if cross_val_X:
q2xc = np.cumsum(q2X)
else:
q2xc = False
q2yc = np.cumsum(q2Y)
eigs = np.var(plsobj['T'],axis=0)
plsobj['q2Y'] = q2Y
plsobj['q2Ypv'] = q2Ypv
if cross_val_X:
plsobj['q2X'] = q2X
plsobj['q2Xpv'] = q2Xpv
if not(shush):
print('phi.pls using NIPALS and cross-validation ('+str(cross_val)+'%) executed on: '+ str(datetime.datetime.now()) )
if not(cross_val_X):
print('---------------------------------------------------------------------------------')
print('PC # Eig R2X sum(R2X) R2Y sum(R2Y) Q2Y sum(Q2Y)')
if A>1:
for a in list(range(A)):
print("PC #"+str(a+1)+":{:8.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}".format(eigs[a], r2X[a], r2xc[a], r2Y[a], r2yc[a],q2Y[a],q2yc[a]))
else:
d1=eigs[0]
d2=r2xc[0]
d3=r2yc[0]
d4=q2yc[0]
print("PC #"+str(a+1)+":{:8.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}".format(d1, r2X, d2,r2Y,d3,q2Y,d4))
print('---------------------------------------------------------------------------------')
else:
print('-------------------------------------------------------------------------------------------------------')
print('PC # Eig R2X sum(R2X) Q2X sum(Q2X) R2Y sum(R2Y) Q2Y sum(Q2Y)')
if A>1:
for a in list(range(A)):
print("PC #"+str(a+1)+":{:8.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}".format(eigs[a], r2X[a], r2xc[a],q2X[a],q2xc[a], r2Y[a], r2yc[a],q2Y[a],q2yc[a]))
else:
d1=eigs[0]
d2=r2xc[0]
d3=q2xc[0]
d4=r2yc[0]
d5=q2yc[0]
print("PC #"+str(a+1)+":{:8.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}".format(d1, r2X, d2,q2X,d3,r2Y,d4,q2Y,d5))
print('-------------------------------------------------------------------------------------------------------')
elif cross_val==100:
if isinstance(X,np.ndarray):
X_=X.copy()
elif isinstance(X,pd.DataFrame):
X_=np.array(X.values[:,1:]).astype(float)
#Mean center and scale according to flags
if isinstance(mcsX,bool):
if mcsX:
#Mean center and autoscale
X_,x_mean,x_std = meancenterscale(X_)
else:
x_mean = np.zeros((1,X_.shape[1]))
x_std = np.ones((1,X_.shape[1]))
elif mcsX=='center':
#only center
X_,x_mean,x_std = meancenterscale(X_,mcs='center')
elif mcsX=='autoscale':
#only autoscale
X_,x_mean,x_std = meancenterscale(X_,mcs='autoscale')
#Generate Missing Data Map
X_nan_map = np.isnan(X_)
not_Xmiss = (np.logical_not(X_nan_map))*1
if isinstance(Y,np.ndarray):
Y_=Y.copy()
elif isinstance(Y,pd.DataFrame):
Y_=np.array(Y.values[:,1:]).astype(float)
#Mean center and scale according to flags
if isinstance(mcsY,bool):
if mcsY:
#Mean center and autoscale
Y_,y_mean,y_std = meancenterscale(Y_)
else:
y_mean = np.zeros((1,Y_.shape[1]))
y_std = np.ones((1,Y_.shape[1]))
elif mcsY=='center':
#only center
Y_,y_mean,y_std = meancenterscale(Y_,mcs='center')
elif mcsY=='autoscale':
#only autoscale
Y_,y_mean,y_std = meancenterscale(Y_,mcs='autoscale')
#Generate Missing Data Map
Y_nan_map = np.isnan(Y_)
not_Ymiss = (np.logical_not(Y_nan_map))*1
#Initialize TSS per var vector
X_,Xnanmap=n2z(X_)
TSSX = np.sum(X_**2)
TSSXpv = np.sum(X_**2,axis=0)
colsX = X_.shape[1]
rowsX = X_.shape[0]
X_ = z2n(X_,Xnanmap)
Y_,Ynanmap=n2z(Y_)
TSSY = np.sum(Y_**2)
TSSYpv = np.sum(Y_**2,axis=0)
colsY = Y_.shape[1]
rowsY = Y_.shape[0]
Y_ = z2n(Y_,Ynanmap)
for a in list(range(A)):
errorY = np.zeros((rowsY*colsY,1))
if cross_val_X:
errorX = np.zeros((rowsX*colsX,1))