-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_functions_lookahead_linocs.py
2408 lines (1854 loc) · 94.8 KB
/
main_functions_lookahead_linocs.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 -*-
# NOTES:
# !!!!!!!!!! LINEAR !!!!!!!!!!!!:
# opt_A, opt_b,b_hats = train_linear_system_opt_A(x_1step, max_ord, Bs_main = [], constraint = [], w_offset = True, cal_offset=True, weights=w, infer_b_way='each', K_b= K_b, w_b = w_b
# train_LOOKAHEAD - NON LINEAR
#
########################################################
# NAIVE FINDER
########################################################
import numpy as np
from scipy.optimize import least_squares
from basic_function_lookahead import *
from scipy.linalg import fractional_matrix_power
import seaborn as sns
global today
from datetime import datetime as datetime2
today = str(datetime2.today()).split()[0].replace('-','_')
def find_operators_h1_no_reg(data):
return np.dstack([ data[:,t+1].reshape((-1,1)) @
np.linalg.pinv(data[:,t].reshape((-1,1)) ).reshape((1,-1))
for t in range(data.shape[1]-1 ) ])
def find_operators_h1_l2_reg(data, l2_w, smooth_w):
if smooth_w == 0:
return np.dstack([ find_operator_under_l2_or_smoothness(data[:,t+1], data[:,t], l2_w,
smooth_w, t = t, A_minus = [])
for t in range(data.shape[1]-1 ) ])
else:
As = []
for t in range(data.shape[1]-1 ):
if t > 0 : A_minus = A_next
else: A_minus = []
A_next = find_operator_under_l2_or_smoothness(data[:,t+1], data[:,t], l2_w,
smooth_w, t = t, A_minus = A_minus)
As.append(A_next)
return np.dstack(As)
def find_c_from_operators(operators, F):
F_mat = np.hstack([F_i.flatten().reshape((-1,1)) for F_i in F])
F_mat_inv = np.linalg.pinv(F_mat)
operators_stack = np.hstack([operators[:,:,t].flatten().reshape((-1,1)) for t in range(operators.shape[2])])
return F_mat_inv @ operators_stack
def find_operators_under_l0( data, params_thres = {'thres':1, 'num':True, 'perc':False}):
if params_thres['thres'] == 0:
return find_operators_h1_no_reg(data)
else:
As = []
for t in range(data.shape[1]-1 ):
A_next = data[:,t+1].reshape((-1,1)) @ np.linalg.pinv(data[:,t].reshape((-1,1)) ).reshape((1,-1))
A_next = keep_thres_only(A_next, direction = 'lower' , **params_thres)
As.append(A_next)
return np.dstack(As)
def k_step_prediction(x, As, K, store_mid = True, t = -1, offset = []):
if len(As.shape) == 2 or (len(As.shape) == 3 and As.shape[-1] == 1):
if (len(As.shape) == 3 and As.shape[-1] == 1):
As = As[:,:,0]
return k_step_prediction_linear(x, As, K, store_mid , t , offset)
else:
if not checkEmptyList(offset):
raise ValueError('future offset')
if is_1d(x):
x = x.reshape((-1,1))
if store_mid:
stores = []
for k in range(K):
print('k')
print(k)
#stores.append(x)
x = As[:,:,k] @ x
if is_1d(x):
x = x.reshape((-1,1))
if store_mid:
stores.append(x)
if store_mid:
return x, stores
return x
def find_operator_under_l1(data, l1_w, seed = 0, params = {} ):
params ={**{'threshkind':'soft','solver':'spgl1','num_iters':10},**params}
p = data.shape[0]
As = []
for t in range(data.shape[1]-1 ):
#if per_row:
A_cur = []
for el in range(p):
cur_b = np.array([data[el,t+1]]).reshape((1,-1))
cur_A = data[:,t].reshape((1,-1))
A_cur.append(solve_Lasso_style(cur_A, cur_b, l1_w,
params = params, lasso_params = {}, random_state = seed).reshape((1,-1)))
As.append(np.vstack(A_cur))
# else:
# cur_b = np.array([data[:,t+1]]).reshape((1,-1))
# cur_A = data[:,t].reshape((1,-1))
return np.dstack(As)
# raise ValueError('HEREHERE FUTURE')
# #
# if l1_w == 0:
# return find_operators_h1_no_reg(data)
# else:
# As = []
# for t in range(data.shape[1]-1 ):
# if t > 0 : A_minus = A_next
# else: A_minus = []
# A_next = find_operator_under_l2_or_smoothness(data[:,t+1], data[:,t], l2_w,
# smooth_w, t = t, A_minus = A_minus)
# As.append(A_next)
# return np.dstack(As)
def find_operator_under_l2_or_smoothness( y_plus, y_minus, l2_w = 0, smooth_w = 0, t = 0,
A_minus = [], reeval = False, mask = []):
if reeval and checkEmptyList(mask):
raise ValueError('you must provide a mask if reeval')
# this function is not being durectly called
if reeval:
A_minus[mask == False] = 0
if is_1d(y_plus):
y_plus = y_plus.reshape((-1,1))
if is_1d(y_minus):
y_minus = y_minus.reshape((-1,1))
if (l2_w == 0 and smooth_w == 0) or (t == 0 and l2_w == 0):
print('pay attention - no reg')
return y_plus @ np.linalg.pinv( y_minus ).reshape((1,-1))
if smooth_w > 0 and checkEmptyList(A_minus) and t > 0:
raise ValueError('you must provide A_minus')
else:
if is_1d(y_plus):
A_shape = (len(y_plus.flatten()), len(y_plus.flatten()))
else:
A_shape = (y_plus.shape[0], y_plus.shape[0])
if l2_w > 0 and smooth_w > 0 and t > 0:
plus_addition = np.hstack([np.zeros(A_shape)*l2_w , A_minus*smooth_w ])
minus_addition = np.hstack( [np.eye(A_shape[0]) , np.eye(A_shape[0])*smooth_w ])
elif smooth_w > 0 and t > 0:
plus_addition = A_minus*smooth_w
minus_addition = np.eye(A_shape[0])*smooth_w
elif l2_w > 0:
plus_addition = np.zeros(A_shape)*l2_w
minus_addition = np.eye(A_shape[0])*l2_w
#print(plus_addition.shape )
#print(y_plus.shape)
y_plus = np.hstack([y_plus, plus_addition ] )
y_minus = np.hstack( [y_minus, minus_addition ] )
#print(y_plus)
#print(y_minus)
#A1 = np.linalg.lstsq(y_minus.T, y_plus.T)[0]
#A2 =
#print(A2)
#print('-----------------------')
return y_plus @ np.linalg.pinv(y_minus)
def plot_elements_of_mov( mat, ax = [] , fig = [],colors = [], legend_params = {}, plot_params = {}, to_legend = False,
type_plot = 'plot'):
if checkEmptyList(colors):
colors = create_colors(len(mat[:,:,0].flatten()))
if is_1d(colors):
colors = colors.reshape((mat[:,:,0].shape[0],mat[:,:,0].shape[1]))
else:
colors = colors.reshape((mat[:,:,0].shape[0],mat[:,:,0].shape[1],3))
# 3d mat
if checkEmptyList(ax):
fig, ax = plt.subplots()
if type_plot == 'plot':
[
[
ax.plot( mat[i,j,:], color = colors[i,j], label = '%d'%(mat.shape[0]*j + i), **plot_params)
for j in range(mat.shape[1])
] for i in range(mat.shape[0])
]
if to_legend:
ax.legend(**legend_params)
elif type_plot == 'heatmap':
mat_2d = np.vstack([
np.vstack([
mat[i,j,:]
for j in range(mat.shape[1])
]) for i in range(mat.shape[0])
] )
sns.heatmap(mat_2d, ax = ax, **plot_params)
def find_weight(k, e, sigma1 = 12, sigma2 = 1.1, norm_w = True, norm_direction = 1):
"""
Calculate the weight using a specified formula.
Parameters:
- k (float): Input parameter.
- e (float): Input parameter.
- sigma1 (float, optional): Standard deviation parameter for k. Default is 12.
- sigma2 (float, optional): Exponent parameter for (1 + |e|). Default is 1.1.
Returns:
float: Weight calculated based on the input parameters.
"""
w = np.exp(-k*sigma1)*(1+np.abs(e))**sigma2
w[np.isnan(w)] = 0
if (w == 0).all():
raise ValueError('all weights are 0!')
if norm_w:
if norm_direction == -1:
w /= w.sum()
elif norm_direction == 0:
w /= w.sum(0).reshape((1,-1))
elif norm_direction == 1:
w /= w.sum(1).reshape((-1,1))
else:
raise ValueError('Invalid direction to norm!!')
return w
def reevaluate_A_under_mask(y_plus, y_minus, A_mask, constraint_i = '', w_reg_i = ''):
"""
Reevaluate matrix A based on masks and input vectors.
Parameters:
- y_plus (numpy.ndarray): Vector with positive values.
- y_minus (numpy.ndarray): Vector with negative values.
- A_mask (numpy.ndarray): Mask specifying the structure of matrix A.
Returns:
numpy.ndarray: Reevaluated matrix A based on the provided masks and vectors.
"""
if 0 in A_mask:
A_mask = A_mask != 0
"""
if the maske covers all
"""
if np.sum(A_mask) == len(A_mask.flatten()):
if is_1d(y_plus) and is_1d(y_minus):
return y_plus.reshape((-1,1)) @ np.linalg.pinv(y_minus).reshape((1,-1))
return y_plus @ np.linalg.pinv(y_minus)
else:
A_new = np.zeros(A_mask.shape)
for row in range(A_mask.shape[0]) :
cols = np.where(A_mask[row])[0]
y_minus_row = y_minus[A_mask[row]]
if is_1d(y_plus) and is_1d(y_minus):
gram = np.outer(y_minus_row, y_minus_row)
A_row = y_plus[row]*y_minus_row.reshape((1,-1)) @ np.linalg.pinv(gram)
else:
A_row = y_plus[row] @ np.linalg.pinv(y_minus_row )
A_new[row, cols] = A_row
return A_new
def infer_A_under_constraint_under_period(data, K, As,
constraint = [],
w_reg = {}, params = {},
reeval = True, is1d_dir = 0,
given_periods = [], sigma1 = 0.8, sigma2 = 4, norm_w = True,
A_former = [], e_thres_for_mid_periods = 0.01, A_between_period_method = 'smooth'):
#A_between_period_method can be 'smooth' or 'decomposition'
"""
Infer the matrix A under specified constraints and within given periods.
Parameters:
- data (numpy.ndarray): Input data matrix.
- K (int): Lookahead parameter.
- As (numpy.ndarray): Matrix of As for prediction.
- constraint (list): List of constraints to apply during training.
- w_reg (dict): Dictionary of regularization weights.
- params (dict): Additional parameters for constraint inference.
- reeval (bool): Reevaluate constraints during training if True.
- is1d_dir (int): 1D direction parameter.
- given_periods (list): List of periods for linear dynamics.
- sigma1 (float): Sigma parameter for weight calculation.
- sigma2 (float): Sigma parameter for weight calculation.
- norm_w (bool): Normalize weights if True.
- A_former (numpy.ndarray): Former matrix A.
- e_thres_for_mid_periods (float): Error threshold for mid periods.
- A_between_period_method (str): Method for handling A between periods ('smooth' or 'decomposition').
Returns:
- As (numpy.ndarray): Updated matrix As.
"""
if given_periods[0][0] != 0:
raise ValueError('given periods must start at 0')
if checkEmptyList(given_periods):
raise ValueError('given_periods is empty')
if 'smooth' not in constraint:
print('smooth not in constraint although you asked for periods')
input('ok?!')
else:
data_in_periods = []
As_in_period = []
for period_num, period in enumerate(given_periods):
cur_data = data[:,period[0]:period[1]]
data_in_periods.append(cur_data)
cur_As = data[:,period[0]:period[1] - 1]
x, stores = k_step_prediction(cur_data, cur_As, K, store_mid = True, t = -1)
stores_3d = np.dstack(stores)
"""
error under each order
"""
es = np.vstack([np.sum((x_i - cur_data)**2, 0) for x_i in stores]) # for eachtime point
w = find_weight(np.arange(1,K+1), es.sum(1), sigma1 = sigma1, sigma2 = sigma2, norm_w = norm_w) # different orders
# RE-WEIGH EACH ORDER EST.
stored_3d_weighted = stores_3d * w.reshape((1,-1,1))
# FIND PROP FOR EVERY ORDER
A_hat = find_A_based_on_multiple_orders_for_period(stored_3d_weighted, cur_data,
constraint = constraint, w_reg = w_reg, params = params,
reeval = reeval , is1d_dir = is1d_dir, A_former = A_former, t = period_num)
# this is a vector of dim X num orders X 2. data plus is just the data. data minues is the estimation
#data_plus_data_minus_w = data_plus_data_minus * w_t.reshape((1,-1,1))
#constraint , w_reg,, params = {},
# reeval = True , is1d_dir = 0, A_former = [], t = 0
As_in_period.append(A_hat)
As[:,:, period[0]: period[1]] = A_hat.reshape((-1, A_hat.shape[1], 1))
"""
infer mid points
"""
xs, _ = [k_step_prediction(data_i, As_in_period[i], K, store_mid = False, t = -1) for i, data_i in enumerate(data_in_periods)]
e = np.mean([((xs[i] - data_i)**2).mean() for i, data_i in enumerate(data_in_periods)])
F = As_in_period.copy()
cs = np.zeros((len(F), As.shape[2]))
for period_num, period in periods:
cs[:, period[0]: period[1]] = create_sparse_lambda(len(F), period_num)
if e < e_thres_for_mid_periods:
between_periods = [[period[1], given_periods[i+1][0]] for i, period in enumerate(given_periods[:-1])]
if A_between_period_method == 'smooth':
for between_period in between_periods:
#period_0 =
#period_1 =
len_period = between_period[1] - between_period[0]
A_former = As[:,:, between_period[0] - 1]
data_between = data[:,between_period[0]-1:between_period[1]+1]
#data_between = data[:,between_period[0]:between_period[1]]
for t_relative, t_exact in enumerate(between_period[0]-1, between_period[1]+1):
K_i = np.min([K, t_relative])
#t_start = np.max([t_relative - 1,0])
#t_end = np.min([t_relative + K - 1, len_period ])
# PREDICT ONE STEP FROM X_T
#data_next = one_step_prediction(data_between[:,t_relative], A_former, t = -1, k = -1, t_start = -1, t_end = -1)
A_former = infer_A_under_constraint(data_between[:,t_relative+1],data_between[:,t_relative],
constraint = constraint,
w_reg = w_reg, params = params,
reeval = reeval, is1d_dir = is1d_dir, A_former = A_former, t = t-1,
given_periods = given_periods)
As[:,:,t_exact] = A_former
cs = find_c_from_operators(As[:,:,between_period[0]-1:between_period[1]+1], F)
elif 'deco' in A_between_period_method:
for between_period in between_periods:
data_between = data[:,between_period[0]-1:between_period[1]+1]
As_between, cs_between = find_A_decomposed_K_steps(data_between, F, K, sigma1, sigma2, A_former = A_former,
w_reg = w_reg, params = params,
reeval = reeval, reweigh_As_func = np.nanmedian, norm_w = True )
cs[:,between_period[0]-1:between_period[1]] = cs_between
As[:,:,between_period[0]-1:between_period[1]] = As_between
else:
raise ValueError('A_between_period_method is %s but must be "smooth" or "deco"'%A_between_period_method)
return As, cs
def find_A_decomposed_1_step_1_time(data_plus, data_minus, F, A_former = [], w_reg = {},
params = {}, reeval = True , smooth_w = 0, cur_reco_t = [], lasso_params = {}, l1_w = 0):
if not checkEmptyList( A_former) and 'smooth' in constraint:
raise ValueError('future extension! smoothness in decomposition')
if not is_1d(data_minus):
raise ValueError('data_minus is not 1d')
elif not is_1d(data_plus):
raise ValueError('data_plus is not 1d')
else:
#find_A_given_basis_operators(x, basis_Fs, A_former, = [],
# w_reg = w_reg, params = params, reeval = reeval )
Fx = np.hstack([(F_i @ data_minus.reshape((-1,1))).reshape((-1,1)) for F_i in F])
# find Cs
#print(Fx.shape)
"""
FIND C
"""
left_side = Fx
right_side = data_plus.reshape((-1,1))
if smooth_w > 0 and not checkEmptyList(cur_reco_t):
left_side = np.vstack([left_side, np.eye(left_side.shape[1])])
right_side = np.vstack([right_side, cur_reco_t.reshape((-1,1))])
if l1_w == 0:
cs_t = np.linalg.pinv(left_side) @ right_side
else:
cs_t = solve_Lasso_style(left_side, right_side, l1_w,
params = params, lasso_params = lasso_params, random_state = 0).reshape((1,-1))
cs_t = cs_t.reshape((-1,1))
A_t = np.sum(np.dstack([F_i*cs_t[i] for i,F_i in enumerate(F)]), 2)
cur_reco_t = A_t @ data_minus.reshape((-1,1))
return A_t, cs_t, cur_reco_t
def find_A_decomposed_1_step_period(data_plus, data_minus, F, A_former = [], w_reg = {}, params = {},
reeval = True, smooth_w = 0, lasso_params = {} , l1_w = 0, c_start = []):
if not checkEmptyList( A_former) and 'smooth' in constraint:
raise ValueError('future extension! smoothness in decomposition')
if data_plus.shape[1] != data_minus.shape[1]:
raise ValueError('data plus must have the same dim as data_minus, but data_plus.shape = %s, data_minus.shape = %s'%(str(data_plus.shape), str(data_minus.shape)))
if is_1d(data_minus):
return find_A_decomposed_1_step_1_time(data_plus, data_minus, F,A_former = A_former,
w_reg = w_reg, params = params, reeval = reeval , l1_w = l1_w)
# raise ValueError('data_minus is not 1d')
else:
# THIS IS A LIST OF RECOS. Each is 2d mat.
#print(data_minus.shape)
#print('!')
# Fx = [ [F_i @ data_minus[:,t].reshape((-1,1)) for F_i in F] for t in range(data_minus.shape[1])]
# #
# cs = np.hstack([(np.linalg.pinv(Fx[t]) @ data_plus[:,t].reshape((-1,1))).reshape((-1,1)) for t in range(data_minus.shape[1])])
# A = np.dstack([np.sum(np.dstack([F_i*cs[i,t] for i,F_i in enumerate(F)]), 2) for t in range(data_minus.shape[1])])
# cur_reco = np.hstack([(A[:,:,t] @ data_minus[:,t].reshape((-1,1))).reshape((-1,1)) for t in range(A.shape[2])])
A = []
cs = []
cur_reco = []
cs_t = c_start #[]
for t in range(data_minus.shape[1]):
A_t, cs_t, cur_reco_t = find_A_decomposed_1_step_1_time(data_plus[:,t], data_minus[:,t], F, A_former, w_reg,
params, reeval, smooth_w = smooth_w, cur_reco_t = cs_t,
lasso_params = lasso_params , l1_w = l1_w)
A.append(A_t)
# cs_t here isa vector of len M
cs.append(cs_t)
cur_reco.append(cur_reco_t)
A = np.dstack(A)
# cs is a matrix of M X T
cs = np.hstack(cs)
cur_reco = np.hstack(cur_reco)
return A, cs, cur_reco
def try_optimize(c_t, F, x_noisy_t, x_next, c_t_know, c_former, reco_so_far, t ):
Fx = np.hstack([(F[i]@x_noisy_t.reshape((-1,1))).reshape((-1,1)) for i in range(len(F))])
if len(reco_so_far) > 0:
F_so_far = np.hstack([(F[i]@reco_so_far.reshape((-1,1))).reshape((-1,1)) for i in range(len(F))])
addi2 = 0.01*(t**1.2)*(x_next - F_so_far @ c_t)**2
else:
addi2= 0
if not checkEmptyList(c_former):
addi = 0.5*(c_t - c_former)**2
else:
addi = 0
objective = 1.3*np.abs(c_t) + 1.5*np.abs(c_t - c_t_know) + addi+addi2 + (x_next - Fx @ c_t)**2 #c_t**2 +
return objective.sum()
def d3tod323(mat) :
mat_2d = np.vstack([
np.vstack([
mat[i,j,:]
for j in range(mat.shape[1])
]) for i in range(mat.shape[0])
] )
print(mat_2d.shape)
return mat_2d
def find_A_fractional_deptacated(k, B):
"""
Find the matrix A such that A^k = B.
Parameters:
- k (float): Power value.
- B (array-like): Target matrix.
Returns:
array-like: Matrix A satisfying A^k = B.
"""
A = fractional_matrix_power(B, 1/k)
return A
def infer_A_under_constraint(y_plus, y_minus, constraint = ['l0'], w_reg = 3, params = {},
reeval = True , is1d_dir = 0, A_former = [], t = 0):
#future not l0
#if type(constraint) != type(w_reg) and (isinstance(constraint, list) and len(constraint) != 1) :
# print('w_reg and cnostraing need to be of the same type. but %s, %s'%(str(constraint), str(w_reg)))
if checkEmptyList(A_former) and 'smooth' in constraint and t > 0:
raise ValueError('?!?!?!')
if is_1d(y_plus):
if is1d_dir == 0:
y_plus = y_plus.reshape((-1,1 ))
else:
y_plus = y_plus.reshape((1,-1 ))
if is_1d(y_minus):
if is1d_dir == 0:
y_minus = y_minus.reshape((-1,1 ))
shape_inv = (1,-1)
else:
y_minus = y_minus.reshape((1,-1 ))
shape_inv = (1,-1)
else:
shape_inv = y_minus.shape[::-1]
try:
A_hat = y_plus @ np.linalg.pinv(y_minus)
except:
print('y plus ?!')
print(y_plus)
A_hat = y_plus @ np.linalg.pinv(y_minus + np.random.rand(*y_minus.shape)*0.01)
for constraint_i in constraint:
w_reg_i = w_reg[constraint_i]
A_hat = apply_constraint_after_order(y_plus, y_minus, constraint_i, w_reg_i, A_former = A_former, t = t, A_hat = A_hat, reeval = True)
return A_hat
def find_Bs_for_dynamics(data, K, constraint = [], w_reg = [], params = {},
reeval = True , is1d_dir = 0, A_former = [], t = 0,
w_offset = True, addi = ''):
# Bs is a list of elements of B. Each B (element of Bs) is the operator y_t = B y_{t-k}.
Bs = []
for k_i in range(1, K+ 1):
y_plus = data[:, k_i:]
y_minus = data[:, :-k_i]
if w_offset:
y_minus_expanded = np.vstack([y_minus, np.ones((1, y_minus.shape[1] )) ])
else:
y_minus_expanded = y_minus
# Bs is a list of elements of B. Each B (element of Bs) is the operator y_t = B y_{t-k}.
B = infer_A_under_constraint(y_plus, y_minus_expanded, constraint, w_reg, params,
reeval , is1d_dir, A_former = A_former, t = 0)
Bs.append(B)
if w_offset:
Bs_main = [B[:,:-1] for B in Bs]
else:
Bs_main = Bs.copy()
return Bs, Bs_main
from scipy.optimize import minimize
def objective_function(A, Bs_main, weights = [], with_identity = False):
A = A.reshape(Bs_main[0].shape)
if checkEmptyList(weights):
weights = np.ones(len(Bs_main))
if not with_identity:
terms = [weights[k]*(np.linalg.matrix_power(A, k + 1) - B_i).T @ (np.linalg.matrix_power(A, k + 1) - B_i)
for k, B_i in enumerate(Bs_main)]
else:
dim = A.shape[0]
terms = [weights[k]*(np.linalg.matrix_power(A, k + 1) - B_i - np.eye(dim)).T @ (np.linalg.matrix_power(A, k + 1) - B_i - np.eye(dim)) for k, B_i in enumerate(Bs_main)]
#print(terms)
objective = np.sum(np.abs(np.dstack(terms)))
return objective
#term1 = A - A1
#term2 = A @ A - A2
#return np.sum(term1 + term2)
from distutils.version import LooseVersion
import scipy
def optimize_A_using_optimizer(Bs_main, A0 = [], weights = [], with_identity = False):
#
if checkEmptyList(A0):
# Initial guess for A
A0 = np.zeros_like(Bs_main[0])
#print(A0.shape)
# Minimize the objective function
#print(A0.shape)
# Get current scipy version
scipy_version = LooseVersion(scipy.__version__)
# Compare with 1.8.0
if scipy_version > LooseVersion("1.8.0"):
A0 = A0.flatten()
else:
pass
result = minimize(objective_function, A0, method='BFGS', args = (Bs_main, weights, with_identity))
# The optimized matrix A
optimized_A = result.x.reshape(Bs_main[0].shape)
#print("Optimized A:")
return optimized_A
#use scipy minimize!!
def poly_cost(lambda_i, lambda_powers, weights):
return np.sum([w*(lambda_i**(i+1) - lambda_powers[i])**2 for i, w in enumerate(weights)])
def lambda_powers2coeffs(lambda_powers = [], weights = []):
# lambda powers is a list of lambda1, lambda1**2, lambda1**3
# solves (lambda - lambda1)**2 + (lambda**2 - lambda2)**2 + ....
if checkEmptyList(weights):
weights = np.ones(len(lambda_powers))
if isinstance(lambda_powers,list ):
lambda_powers = np.array(lambda_powers)
# last coeffs
#free_el = np.sum((weights*lambda_powers)**2)
# power 2,4, 6, 8...
#lambda_coeffs = lists2list([[w] + [0] for w in weights])[::-1] + [0,0]
# powers 1,2,3,4....
#addi = [-2*weights[w_i]*lambda_p for w_i, lambda_p in enumerate(lambda_powers)][::-1] + [0]
#full_coeffs = np.array(lambda_coeffs).astype(complex)
#full_coeffs[-len(lambda_powers)-1:] += np.array(addi).astype(complex)
#full_coeffs[-1] = free_el
#roots = np.roots(full_coeffs)
initial_guess = lambda_powers[0]
roots = minimize(poly_cost, args = (lambda_powers, weights), x0 = initial_guess).x
# take sol closer to lmabda 0
if len(roots) > 1:
sol = roots[np.argmin(np.abs(roots - lambda_powers[0]))]
else:
sol = roots[0]
return sol, roots # free_el, lambda_coeffs, addi, full_coeffs,
def lambda_powers2coeffs_depracated(lambda_powers = [], weights = []):
# lambda powers is a list of lambda1, lambda1**2, lambda1**3
# solves (lambda - lambda1)**2 + (lambda**2 - lambda2)**2 + ....
if checkEmptyList(weights):
weights = np.ones(len(lambda_powers))
if isinstance(lambda_powers,list ):
lambda_powers = np.array(lambda_powers)
# last coeffs
free_el = np.sum((weights*lambda_powers)**2)
# power 2,4, 6, 8...
lambda_coeffs = lists2list([[w] + [0] for w in weights])[::-1] + [0,0]
# powers 1,2,3,4....
addi = [-2*weights[w_i]*lambda_p for w_i, lambda_p in enumerate(lambda_powers)][::-1] + [0]
full_coeffs = np.array(lambda_coeffs).astype(complex)
full_coeffs[-len(lambda_powers)-1:] += np.array(addi).astype(complex)
full_coeffs[-1] = free_el
roots = np.roots(full_coeffs)
print(roots)
print('val eq root')
k = len(full_coeffs)
#print([weights[k-i]*(root**(k-i-)-lambda_powers[k-i])**2 for i in range(len(weights))])
for j in range(len(roots)):
print(np.sum([full_coeffs[i]*roots[j]**(k-i-1) for i in range(k) ]))
print('???????????????')
print(roots)
print(len(roots))
print(len(np.unique(roots)))
print('coeffs')
print(full_coeffs)
input('?!')
# take sol closer to lmabda 0
if len(roots) > 1:
sol = roots[np.argmin(np.abs(roots - lambda_powers[0]))]
else:
sol = roots[0]
return sol, free_el, lambda_coeffs, addi, full_coeffs, roots
def find_best_lambdas(lambdas, weights = [], matched_evecs = [], roots_full = []):
# lambdas is a list of numpy arrays. Each array is all evals of that order (each array len p, ovearll K arrays). Fist list is order 1.
# vector with len K
if checkEmptyList(weights):
weights = np.ones(len(lambdas))
#weights *= np.exp(-0.1*np.arange(len(lambdas))[::-1])
weights = weights / np.max(weights)
K = len(weights)
p = len(lambdas[0])
lambdas_best = []
roots_full = []
#print('start reco')
for p_i in range(p):
lambda_powers = np.array([lambdas_i[p_i] for lambdas_i in lambdas])
#lambda_best, free_el, lambda_coeffs, addi, full_coeffs, roots = lambda_powers2coeffs(lambda_powers, weights)
lambda_best, roots = lambda_powers2coeffs(lambda_powers, weights)
lambdas_best.append(lambda_best)
roots_full.append(roots)
# eigen deco
if isinstance(matched_evecs, list):
matched_evecs = matched_evecs[0]
deco = eigen_dec(np.array(lambdas_best), matched_evecs)
# private decos
each_deco = [eigen_dec(np.array(lambdas_i), matched_evecs) for lambdas_i in lambdas]
"""
deco for each solution
"""
print('find decos')
combinations_r = list(itertools.product(*roots_full))
decos_all_roots = [eigen_dec(np.array(combination), matched_evecs) for combination in combinations_r]
return deco, lambdas_best, each_deco, decos_all_roots, roots_full
def reorg_evecs_all_orders(Bs, to_plot = True, to_save = True, save_path = '.',
save_formats = ['.png','.svg'], fig = [], axs = [], with_signs = False, to_abs = True):
addi = today + '_%s'%str(to_abs)
# Bs is a list of matrices A, A^2, A^3....
evecs = []
evals = []
"""
FIND EVECS AND EVALS
"""
for B in Bs:
w, v = np.linalg.eig(B)
evecs.append(v)
evals.append(w)
"""
REORDER EVECS AND EVALS BY FIRST COLUMN
"""
matches_and_signs = [find_matching_columns(evecs[0], evec, to_abs = to_abs,i= i) for i,evec in enumerate(evecs)]
matches = [np.vstack(el[0]) for el in matches_and_signs]
if with_signs:
signs = [el[1] for el in matches_and_signs]
else:
signs = [np.ones((1,Bs[0].shape[1])) for _ in matches_and_signs]
#matches = [np.vstack(find_matching_columns(evecs[0], evec)) for evec in evecs]
matched_evecs = []
matched_evals = []
dim = Bs[0].shape[0]
for count, evec in enumerate(evecs):
cur_match = matches[count]
eval_c = evals[count]
#cur_dict = {cur_match[0]:cur_match[1] for cur_match in matches}
# print('--------===============')
# print(evec.shape)
# print(cur_match)
"""
order_matches = indices of 2nd mat
"""
order_matches = np.array([cur_match[cur_match[:,0] == j, 1] for j in range(dim)]).flatten()
# print( order_matches)
# print('----------------------------')
signs[count] = signs[count][order_matches]
matched_eval = eval_c[order_matches]*signs[count]
#print(signs[count])
matched_eval = np.array([eval_c_i.conj() if signs[count][i] < 0 else eval_c_i for i,eval_c_i in enumerate(matched_eval) ])
matched_evec = evec[:, order_matches]*signs[count].reshape((1,-1))
for i in range(matched_evec.shape[1]):
#if count == 8:
#print(signs[count][i])
#print(evec[:, order_matches])
if signs[count][i] < 0:
matched_evec[:,i] = matched_evec[:,i].conj()
matched_evecs.append(matched_evec)
matched_evals.append(matched_eval)
if to_plot:
match_cols, disparities, match_cols_dict = eval_matches(matched_evecs, to_plot = True)
print('plot!!!!!!!!!!!!!!!!!!')
B_min = np.min([B.min() for B in Bs])
B_max = np.max([B.max() for B in Bs])
v_min = np.min([np.real(B.min()) for B in evecs])
v_max = np.max([np.real(B.max()) for B in evecs])
v_min_r = np.min([np.imag(B).min() for B in evecs])
v_max_r = np.max([np.imag(B).max() for B in evecs])
if checkEmptyList(axs):
fig, axs = plt.subplots(5, len(Bs), figsize = (len(Bs)*5, 15),sharey = True)
[sns.heatmap(B, ax = axs[0,i], vmin = B_min, vmax = B_max) for i,B in enumerate(Bs)]
[add_labels(ax, xlabel = 'x-y-z', ylabel = 'x-y-z', title = '$A^%d$'%(i+1), title_params = {'fontsize': 12}) for i, ax in enumerate(axs[0])]
[sns.heatmap(np.real(B), ax = axs[1,i], vmin = v_min, vmax = v_max) for i,B in enumerate(evecs)]
[add_labels(ax, xlabel = 'evec #', ylabel = 'evecs vals', title = 'Evecs Order k = %d'%i, title_params = {'fontsize': 12}) for i, ax in enumerate(axs[1])]
[sns.heatmap(np.real(B), ax = axs[3,i], vmin = v_min, vmax = v_max) for i,B in enumerate(matched_evecs)]
[add_labels(ax, xlabel = 'evec #', ylabel = 'evecs vals (match)', title = '(matched) Evecs Order k = %d'%i, title_params = {'fontsize': 12}) for i, ax in enumerate(axs[3])]
[sns.heatmap(np.imag(B), ax = axs[2,i], vmin = v_min_r, vmax = v_max_r) for i,B in enumerate(evecs)]
[add_labels(ax, xlabel = 'evec #', ylabel = 'evecs vals', title = 'IM Evecs Order k = %d'%i, title_params = {'fontsize': 12}) for i, ax in enumerate(axs[2])]
[sns.heatmap(np.imag(B), ax = axs[4,i], vmin = v_min_r, vmax = v_max_r) for i,B in enumerate(matched_evecs)]
[add_labels(ax, xlabel = 'evec #', ylabel = 'evecs vals (match)', title = 'IM (matched) Evecs Order k = %d'%i, title_params = {'fontsize': 12}) for i, ax in enumerate(axs[4])]
# """
# plot evals
# """
v_min = np.min([np.real(B.min()) for B in evecs])
v_max = np.max([np.real(B.max()) for B in evecs])
v_min_r = np.min([np.imag(B.min()) for B in evecs])
v_max_r = np.max([np.imag(B.max()) for B in evecs])
np.random.seed(0)
colors = np.random.rand(len(evals), 3)
colors = [tuple(colors[i]) for i in range(colors.shape[0])]
fig_eval, axs_eval = plt.subplots(2, len(Bs), figsize = (len(Bs)*5, 15),sharey = True, sharex = True)
[axs_eval[0,i].scatter(np.real(B), np.imag(B), color = colors) for i,B in enumerate(evals)]
#[axs[0,i].plot([0,np.real(B)], [0,np.imag(B)]) for i,B in enumerate(evals)]
[add_labels(ax, xlabel = 'evec #', ylabel = 'evecs vals', title = 'Evecs Order k = %d'%i, title_params = {'fontsize': 12}) for i, ax in enumerate(axs_eval[0])]
#print(matched_evals[0])
[axs_eval[1,i].scatter(np.real(B), np.imag(B), color = colors) for i,B in enumerate(matched_evals)]
#[axs[1,i].plot([0,np.real(B)], [0,np.imag(B)]) for i,B in enumerate(matched_evals)]
[add_labels(ax, xlabel = 'evec #', ylabel = 'evecs vals (match)', title = 'IM (matched) Evecs Order k = %d'%i, title_params = {'fontsize': 12}) for i, ax in enumerate(axs_eval[1])]
fig.tight_layout()
if to_save:
fig.suptitle(save_path + os.sep + 'evecs_%s'%addi + save_formats[0])
[fig.savefig(save_path + os.sep + 'evecs_%s'%addi + save_format) for save_format in save_formats]
fig_evals.suptitle(save_path + os.sep + 'evals_%s'%addi + save_formats[0])
[fig_evals.savefig(save_path + os.sep + 'evals_%s'%addi + save_format) for save_format in save_formats]
else:
match_cols, disparities = [],[]
return matched_evecs, matched_evals, match_cols, disparities, signs
def eval_matches(matched_Ps, to_plot = True, save_path = '.', save_formats = ['.png','.svg']):
addi = today
combs = list(itertools.combinations(range(len(matched_Ps)), 2))
#print(list(combs))
#[find_matching_columns(matched_Ps[comb[0]], matched_Ps[comb[1]] )[0] for comb in combs]
match_cols = [np.vstack(find_matching_columns(matched_Ps[comb[0]], matched_Ps[comb[1]] )[0]) for comb in combs.copy()]
#print(list(combs))
match_cols_dict = {tuple(comb):np.vstack(find_matching_columns(matched_Ps[comb[0]], matched_Ps[comb[1]] )[0]) for comb in list(combs)}
#print(match_cols_dict)
disparities = [(match_col[:,0] != match_col[:,1]).sum() for match_col in match_cols]
print('Columns do not match %d times'%np.mean(disparities))
if to_plot:
each = int(np.sqrt(len(match_cols))) + 1
fig, axs = plt.subplots(each-2,each+2, figsize = (each*2,each*7), sharey = True)
axs = axs.flatten()
[sns.heatmap(match_cols_i, vmin = 0, vmax = matched_Ps[0].shape[0], ax = axs[i], annot = True, square = True, cbar = False) for i, match_cols_i in enumerate( match_cols )]
fig.suptitle('Columns Matching')
fig.tight_layout()
[add_labels(ax, xlabel = 'Pair', ylabel = '') for ax in axs]
fig.tight_layout()
if to_save:
fig.suptitle(save_path + os.sep + 'pairs_%s'%addi + save_formats[0])
[fig.savefig(save_path + os.sep + 'pairs_%s'%addi + save_format) for save_format in save_formats]
fig, axs = plt.subplots()
sns.histplot(np.abs(disparities), ax = axs, bins = matched_Ps[0].shape[0] ,discrete = True)
add_labels(axs, xlabel = 'Disparities', ylabel = 'Count')
fig.tight_layout()
if to_save:
fig.suptitle(save_path + os.sep + 'Disparities_%s'%addi + save_formats[0])
[fig.savefig(save_path + os.sep + 'Disparities_%s'%addi + save_format) for save_format in save_formats]
fig, axs = plt.subplots()
[axs.scatter(match_cols_i[:,0], match_cols_i[:,1]) for i, match_cols_i in enumerate(match_cols)]
add_labels(axs, xlabel = 'pair 1', ylabel = 'Pair 2')
fig.suptitle('Columns Matching')
fig.tight_layout()
fig.tight_layout()
if to_save:
fig.suptitle(save_path + os.sep + 'match_%s'%addi + save_formats[0])
[fig.savefig(save_path + os.sep + 'match_%s'%addi + save_format) for save_format in save_formats]