-
Notifications
You must be signed in to change notification settings - Fork 0
/
conf_ope_rl.py
2298 lines (2032 loc) · 94.5 KB
/
conf_ope_rl.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
import numpy as np
import pandas as pd
from random import seed
from random import random
import matplotlib.pyplot as plt
import gurobipy as gp
from joblib import Parallel, delayed
from copy import deepcopy
import cvxpy as cvx
from scipy.sparse import lil_matrix
import mosek
from datetime import datetime
import pickle
reshape_byxrow = lambda a,nU: a.reshape(-1,nU,a.shape[-1]).sum(1)
def log_progress(sequence, every=None, size=None, name='Items'):
from ipywidgets import IntProgress, HTML, VBox
from IPython.display import display
is_iterator = False
if size is None:
try:
size = len(sequence)
except TypeError:
is_iterator = True
if size is not None:
if every is None:
if size <= 200:
every = 1
else:
every = int(size / 200) # every 0.5%
else:
assert every is not None, 'sequence is iterator, set every'
if is_iterator:
progress = IntProgress(min=0, max=1, value=1)
progress.bar_style = 'info'
else:
progress = IntProgress(min=0, max=size, value=0)
label = HTML()
box = VBox(children=[label, progress])
display(box)
index = 0
try:
for index, record in enumerate(sequence, 1):
if index == 1 or index % every == 0:
if is_iterator:
label.value = '{name}: {index} / ?'.format(
name=name,
index=index
)
else:
progress.value = index
label.value = u'{name}: {index} / {size}'.format(
name=name,
index=index,
size=size
)
yield record
except:
progress.bar_style = 'danger'
raise
else:
progress.bar_style = 'success'
progress.value = index
label.value = "{name}: {index}".format(
name=name,
index=str(index or '?')
)
# Simulate from multinomial distribution
def simulate_multinomial(vmultinomial):
r=np.random.uniform(0.0, 1.0)
CS=np.cumsum(vmultinomial)
CS=np.insert(CS,0,0)
m=(np.where(CS<r))[0]
nextState=m[len(m)-1]
return nextState
def get_pib(nA,nS, a_s, stateHist):
'''
# estimate p(a \mid s)
'''
p_a1_su = np.zeros([nA, nS])
for a in range(nA):
p_a1_su[a,:] = [sum( (a_s==a) & (stateHist[:-1,s]==1) ) / sum(stateHist[:-1,s]) for s in range(nS)]
return p_a1_su
def get_pib_counts(nA,nS, a_s, stateHist):
'''
# estimate counts of p(a \mid s)
'''
p_a1_su_counts = np.zeros([nA, nS])
for a in range(nA):
p_a1_su_counts[a,:] = [sum( (a_s==a) & (stateHist[:-1,s]==1) ) for s in range(nS)]
return p_a1_su_counts
def get_cndl_s_a_sprime(s_a_sprime, distrib):
assert np.isclose(distrib.sum(), 1)
joint_s_a_sprime = s_a_sprime / np.sum(s_a_sprime)
s_a_giv_sprime = joint_s_a_sprime / distrib
for k in range(s_a_giv_sprime.shape[2]):
if not np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01):
print 'conditional not well behaved for s='+str(k)
return [joint_s_a_sprime, s_a_giv_sprime]
# take in transition matrix, policy, initial state s0
def simulate_rollouts( nS, nA, P, Pi, state_dist, n ):
stateChangeHist = np.zeros([nS,nS])
s_a_sprime = np.zeros([nS,nA,nS])
currentState=0;
s0 = np.zeros([1,nS])
print state_dist
s0_ = np.random.choice(range(nS), p = state_dist)
s0[0,s0_] = 1
stateHist=s0
dfStateHist=pd.DataFrame(s0)
distr_hist = [ [0] * nS]
a_s = np.zeros(n)
for x in range(n):
a = np.random.choice(np.arange(0, nA), p=Pi[:,currentState])
a_s[x] = a
currentRow=np.ma.masked_values(( P[currentState, a, :] ) , 0.0)
nextState=np.random.choice(np.arange(0, nS), p=currentRow)
# Keep track of state changes
stateChangeHist[currentState,nextState]+=1
# Keep track of the state vector itself
state=np.zeros([1,nS]) #np.array([[0,0,0,0]])
state[0,nextState]=1.0
# Keep track of state history
stateHist=np.append(stateHist,state,axis=0)
# get s,a,s' distribution
s_a_sprime[currentState, a, nextState] += 1
currentState=nextState
# calculate the actual distribution over the 3 states so far
totals=np.sum(stateHist,axis=0)
gt=np.sum(totals)
distrib=totals*1.0/gt
distrib=np.reshape(distrib,(1,nS))
distr_hist=np.append(distr_hist,distrib,axis=0)
return [ stateChangeHist, stateHist, a_s, s_a_sprime, distrib, distr_hist ]
def agg_state(nS,nSmarg,nU,nA,s_a_sprime):
''' Aggregate every nSmarg states
'''
agger = np.zeros([nS, nSmarg])
eye_nSmarg = np.eye(nSmarg)
agger = np.repeat(eye_nSmarg, nU,axis = 0).reshape([nS, nSmarg])
agg_s_a_sprime = np.zeros([nSmarg, nA, nSmarg])
for a in range(nA):
agg_s_a_sprime[:,a,:] = agger.T.dot(s_a_sprime[:,a,:].dot(agger))
return agg_s_a_sprime
def get_bnds(est_Q,LogGamma):
''' Odds ratio with respect to 1-a
'''
n = len(est_Q)
p_hi = np.multiply(np.exp(LogGamma), est_Q ) / (np.ones(n) - est_Q + np.multiply(np.exp(LogGamma), est_Q ))
p_lo = np.multiply(np.exp(-LogGamma), est_Q ) / (np.ones(n) - est_Q + np.multiply(np.exp(-LogGamma), est_Q ))
assert (p_lo < p_hi).all()
a_bnd = 1/p_hi;
b_bnd = 1/p_lo
return [ a_bnd, b_bnd ]
def get_bnds_as( p_a1_s, LogGamma ):
a_bnd = np.zeros(p_a1_s.shape); b_bnd = np.zeros(p_a1_s.shape)
for a in range(p_a1_s.shape[0]):
[a_bnd_, b_bnd_] = get_bnds(p_a1_s[a,:],LogGamma)
a_bnd[a,:] = a_bnd_; b_bnd[a,:] = b_bnd_
return [a_bnd, b_bnd]
def get_auxiliary_info_from_traj(stateChangeHist, stateHist, a_s, s_a_sprime, distrib, distr_hist, nA,nS):
'''
get empirical joint distribution
'''
p_a1_su = get_pib(nA,nS, a_s, stateHist);
[joint_s_a_sprime, s_a_giv_sprime] = get_cndl_s_a_sprime(s_a_sprime, distrib)
return [ p_a1_su, joint_s_a_sprime, s_a_giv_sprime ]
def get_agg_auxiliary_info_from_all_trajectories(res, nA,nS, nSmarg, nU):
# s_a_sprime_cum = np.zeros([nS,nA,nS])
# assume all trajectories of same length
# better to compute running averages rather than
[ stateChangeHist, stateHist, a_s, s_a_sprime, distrib, distr_hist ] = res[0]
N = len(res);
s_a_sprime_cum = s_a_sprime
p_a1_su = get_pib_counts(nA,nS, a_s, stateHist);
aggStateHist = reshape_byxrow(stateHist.T, nU).T;
agg_s_a_sprime_cum = agg_state(nS,nSmarg,nU,nA,s_a_sprime)
p_a1_s = get_pib_counts(nA,nSmarg, a_s, aggStateHist);
i = 0
# totals=np.sum(stateHist,axis=0); gt=np.sum(totals); distrib=totals/gt; distrib=np.reshape(distrib,(1,nS))
for traj in res[1:]:
if i%100==0:
print i
i+=1;
[ stateChangeHist_, stateHist_, a_s_, s_a_sprime_, distrib_, distr_hist ] = traj
p_a1_su_ = get_pib_counts(nA,nS, a_s_, stateHist_) # takes too much memory to store history # stateHist = np.vstack([stateHist, stateHist_]) # a_s = np.vstack([a_s, a_s_.reshape([len(a_s_),1]) ])
# append
s_a_sprime_cum = s_a_sprime_cum + s_a_sprime_; p_a1_su += p_a1_su_; distrib += distrib_
# aggregate history online
aggStateHist_ = reshape_byxrow(stateHist_.T, nU).T
agg_s_a_sprime_ = agg_state(nS,nSmarg,nU,nA,s_a_sprime_)
p_a1_s_ = get_pib_counts(nA,nSmarg, a_s, aggStateHist_)
agg_s_a_sprime_cum = agg_s_a_sprime_cum + agg_s_a_sprime_; p_a1_s += p_a1_s_
# take average over trajectories
distrib = (distrib / distrib.sum()) ; # p_infty_b_su
# print distrib
p_a1_su = p_a1_su / N; p_a1_su = p_a1_su/ p_a1_su.sum(axis=0) # return probabilities
p_a1_s = p_a1_s / N; p_a1_s = p_a1_s/ p_a1_s.sum(axis=0)
# print ((s_a_sprime_cum/s_a_sprime_cum.sum())/distrib)[:,:,0]
[joint_s_a_sprime, s_a_giv_sprime] = get_cndl_s_a_sprime(s_a_sprime_cum, distrib.flatten())
p_infty_b_s = (reshape_byxrow(distrib.T,nU).T ).flatten()
[joint_s_a_sprime_agg, s_a_giv_sprime_agg] = get_cndl_s_a_sprime(agg_s_a_sprime_cum, p_infty_b_s)
# return [aggStateHist, p_a1_s, p_e_s, agg_s_a_sprime, joint_s_a_sprime_agg, s_a_giv_sprime_agg]
return [ p_a1_su, joint_s_a_sprime, s_a_giv_sprime, s_a_sprime_cum, p_a1_s, joint_s_a_sprime_agg, s_a_giv_sprime_agg, agg_s_a_sprime_cum, distrib]
## deprecated version that keeps things in memory
# def get_auxiliary_info_from_all_trajectories(res, nA,nS):
# # s_a_sprime_cum = np.zeros([nS,nA,nS])
# # assume all trajectories of same length
# [ stateChangeHist, stateHist, a_s, s_a_sprime, distrib, distr_hist ] = res[0]
# N = len(res)
# a_s = a_s.reshape([len(a_s),1])
# s_a_sprime_cum = s_a_sprime
# totals=np.sum(stateHist,axis=0); gt=np.sum(totals); distrib=totals/gt; distrib=np.reshape(distrib,(1,nS))
# for traj in res[1:]:
# [ stateChangeHist_, stateHist_, a_s_, s_a_sprime_, distrib, distr_hist ] = traj
# stateHist = np.vstack([stateHist, stateHist_])
# a_s = np.vstack([a_s, a_s_.reshape([len(a_s_),1]) ])
# s_a_sprime_cum = s_a_sprime_cum + s_a_sprime_
# totals=np.sum(stateHist_,axis=0); gt=np.sum(totals); distrib_=totals/gt; distrib_=np.reshape(distrib,(1,nS))
# distrib += distrib_
# print 'a_s shape', a_s.shape
# print 'statehist shape', stateHist.shape
# distrib = distrib / N # take average over trajectories
# print 'stat dist p_b(s)', distrib
# # totals=np.sum(stateHist,axis=0); gt=np.sum(totals); distrib=totals/gt; distrib=np.reshape(distrib,(1,nS))
# p_a1_su = get_pib(nA,nS, a_s, stateHist);
# print ((s_a_sprime_cum/s_a_sprime_cum.sum())/distrib)[:,:,0]
# [joint_s_a_sprime, s_a_giv_sprime] = get_cndl_s_a_sprime(s_a_sprime_cum, distrib.flatten())
# return [ p_a1_su, joint_s_a_sprime, s_a_giv_sprime, s_a_sprime, stateHist, a_s, distrib]
def agg_history(stateHist, s_a_sprime, p_infty_b_s, a_s, p_e_su, nA, nS, nSmarg, nU):
'''
# agg history and process
'''
# assert np.isclose(sum(p_infty_b_s), 1)
aggStateHist = reshape_byxrow(stateHist.T, nU).T
p_a1_s = get_pib(nA,nSmarg, a_s, aggStateHist);
p_e_s = reshape_byxrow(p_e_su.T,nU).T / nU #get_agg(p_e_su, nU)/2
agg_s_a_sprime = agg_state(nS,nSmarg,nU,nA,s_a_sprime)
[joint_s_a_sprime_agg, s_a_giv_sprime_agg] = get_cndl_s_a_sprime(agg_s_a_sprime, p_infty_b_s)
return [aggStateHist, p_a1_s, p_e_s, agg_s_a_sprime, joint_s_a_sprime_agg, s_a_giv_sprime_agg]
def rollout_parallel(i, nS, nA, P, Pi, state, n ):
res = simulate_rollouts( nS, nA, P, Pi, state, n )
return res
def get_w_lp(gamma, s_a_giv_sprime, p_infty_b_su, pe_su, p_a1_su, nA, nS, tight= True, quiet = True):
m = gp.Model()
w = m.addVars(nS)
if quiet: m.setParam("OutputFlag", 0)
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b_su), 1)
assert len(p_infty_b_su) == nS
epsilon = 0.2
p_infty_b_su=p_infty_b_su.flatten()
for k in range(nS):
m.addConstr( 0 == (-1*w[k] + gp.quicksum(w[j]* gp.quicksum([s_a_giv_sprime[j,a,k]*(pe_su[a,j] / p_a1_su[a,j]) for a in range(nA)]) for j in range(nS) ) ) )
# m.addConstr( 0 == (-1*w[k] + gp.quicksum( [w[j]*s_a_giv_sprime[j,a,k]*(pe_su[a,j] / p_a1_su[a,j]) for a in range(nA)]) for j in range(nS) ))
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w[k] * p_infty_b[k] for k in range(nS)))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_su[a,j] / p_a1_su[a,j]) for a in range(nA)]) for j in range(nS) )) )
if tight:
m.addConstr(gp.quicksum([ w[k]*p_infty_b_su[k] for k in range(nS)]) - 1 <= epsilon)
else:
m.addConstr(gp.quicksum([ w[k]*p_infty_b_su[k] for k in range(nS)]) >= 0.1)
m.update()
m.optimize()
w_ = np.asarray([w[i].X for i in range(nS)])
return w_
def get_w_lp_testfunction(gamma, s_a_giv_sprime, p_infty_b_su, pe_su, p_a1_su, nA, nS, tight= True, quiet = True):
m = gp.Model()
w = m.addVars(nS)
if quiet: m.setParam("OutputFlag", 0)
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b_su), 1)
assert len(p_infty_b_su) == nS
epsilon = 0.2
p_infty_b_su=p_infty_b_su.flatten()
for k in range(nS):
m.addConstr( 0 == (-1*w[k] + gp.quicksum(w[j]* gp.quicksum([s_a_giv_sprime[j,a,k]* p_infty_b_su[k]*(pe_su[a,j] / p_a1_su[a,j]) for a in range(nA)]) for j in range(nS) ) ) )
# m.addConstr( 0 == (-1*w[k] + gp.quicksum( [w[j]*s_a_giv_sprime[j,a,k]*(pe_su[a,j] / p_a1_su[a,j]) for a in range(nA)]) for j in range(nS) ))
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w[k] * p_infty_b[k] for k in range(nS)))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_su[a,j] / p_a1_su[a,j]) for a in range(nA)]) for j in range(nS) )) )
if tight:
m.addConstr(gp.quicksum([ w[k]*p_infty_b_su[k] for k in range(nS)]) - 1 <= epsilon)
else:
m.addConstr(gp.quicksum([ w[k]*p_infty_b_su[k] for k in range(nS)]) >= 0.1)
m.update()
m.optimize()
w_ = np.asarray([w[i].X for i in range(nS)])
return w_
""" subgrad descent template algo
automatically augments data !
take in theta_0, # rounds
LOSS: loss function
GRAD_: fn to obtain parametric subgradient
POL_GRAD: gradient of parametrized policy wrt parameters
PI_1: return prob of pi(x) = 1
data: dictionary, e.g. of x, t01, y, a_, b_
Projected onto bounds
"""
def proj_grad_descent(g, N_RNDS, data, eta_0=1, step_schedule=0.5, sense_min = True):
risks = np.zeros(N_RNDS)
THTS = [None] * N_RNDS; PARAMS = [None] * N_RNDS; losses = [None] * N_RNDS
gs_proj = [None] * N_RNDS;
gs_init = [None] * N_RNDS;
# initialize randomly in [a_, b_]
for k in range(N_RNDS):
eta_t = eta_0 * 1.0 / np.power((k + 1) * 1.0, step_schedule)
# [loss, param] = LOSS_(th, data)
# subgrad = GRAD_(th, data)
[obj, th, A] = obj_eval(g, *[data])
data['A']=A; data['theta'] = th
g_grad = grad_H_wrt_g(g, *[data])
if sense_min == True:
g = -1*g
g_grad = -1*g_grad
g_step = g + eta_t * g_grad; gs_init[k] = g_step
[g_proj, proj_val] = proj_g_(g_step, *[data])
gs_proj[k] = g_proj
g = g_proj
THTS[k] = th; losses[k] = obj
return [losses, gs_init, gs_proj, THTS]
def random_g(a_bnd,b_bnd):
[nA,nS] = a_bnd.shape
g = np.zeros([nS,nA,nS])
draw = np.random.uniform(size = a_bnd.shape) * (b_bnd - a_bnd)
for k in range(nS):
g[k,:,:] = a_bnd + draw
return g
def obj_eval(g, *args):
''' Evaluate objective
Assume g is [k,a,j]
'''
data = args[0]
Phi = data['Phi'] # state
p_infty_b_s = data['pbs']
nSmarg = len(p_infty_b_s)
s_a_giv_sprime = data['s_a_giv_sprime']
p_e_s = data['p_e_s']; nA = len(p_e_s); check_grad = data['check_grad']
A = np.zeros([nSmarg,nSmarg])
for k in range(nSmarg):
for j in range(nSmarg):
A[k,j] += sum( [ s_a_giv_sprime[j,a,k]*p_infty_b_s[k] * (p_e_s[a,j] *g[k,a,j] ) for a in range(nA)] )
A[k,k] -= p_infty_b_s[k]
tildeA = A
# Make regular and add normalization
tildeA[-1,:] = p_infty_b_s
v = np.zeros([nSmarg]); v[-1] = 1
theta = np.linalg.inv(tildeA).dot(v)
if check_grad:
return Phi.dot(theta)
return [Phi.dot(theta), theta, tildeA]
def grad_H_wrt_g(g, *args):
''' Evaluate gradient
Assume g is [k,a,j]
-({I}[j /= |S|] pi^e_a,j Pb_{j,a,k}) (\E[A']^{-\top } \Phi \theta^\top)_{i,j}
Build A matrix explicitly
'''
data = args[0]
A = data['A']
theta = data['theta']
Phi = data['Phi']
outer_ = np.outer(Phi, theta)
M = np.linalg.inv(A).dot(outer_)
g_grad = np.zeros(g.shape)
s_a_giv_sprime = data['s_a_giv_sprime'] ;p_e_s = data['p_e_s']; p_infty_b_s = data['pbs']
for k in range(g_grad.shape[0]):
for a in range(g_grad.shape[1]):
for j in range(g_grad.shape[2])[:-1]: # omit last row of J
g_grad[k,a,j] = M[j,k]*s_a_giv_sprime[j,a,k]*p_infty_b_s[k]*p_e_s[a,j]
return g_grad
def proj_g_(g_tilde, *args):
''' Project a given g vector onto feasible vector
'''
data = args[0]
a_bnd = data['a_bnd']; b_bnd = data['b_bnd']
p_infty_b_s = data['pbs'] ; p_e_s = data['p_e_s']
nS = len(p_infty_b_s)
nA = len(p_e_s)
s_a_giv_sprime = data['s_a_giv_sprime']
tight = data['tight']
m = gp.Model()
g = m.addVars(nS,nA,nS)
quiet = True
if quiet: m.setParam("OutputFlag", 0)
for k in range(nS):
for a in range(nA):
for j in range(nS):
m.addConstr(g[k,a,j] <= b_bnd[a,j])
m.addConstr(g[k,a,j] >= a_bnd[a,j])
for a in range(nA):
if tight:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b_s[k] for k in range(nS) for j in range(nS) ] ) == 1)
else:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b_s[k] for k in range(nS) for j in range(nS)] ) - 1 <= epsilon)
m.addConstr(1 - gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b_s[k] for k in range(nS) for j in range(nS)] ) <= epsilon)
m.update()
obj = gp.quicksum( (g[k,a,j]*g[k,a,j] - 2*g[k,a,j]*g_tilde[k,a,j] + g_tilde[k,a,j]*g_tilde[k,a,j] for k in range(nS)for a in range(nA) for j in range(nS)))
m.setObjective(obj)
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
g_ = np.asarray([g[k,a,j].x for k in range(nS) for a in range(nA) for j in range(nS) ]).reshape([nS,nA,nS])
return [g_,m.objVal]
else:
return [None, None]
def optw_ls(th, *args):
data = dict(args[0])
X = data['x']
t01 = data['t01']
Y = data['y']
a_ = data['a_']
b_ = data['b_']
x0 = data['x0']
sign = data['sign']
n = X.shape[0]
W = np.diag(th.flatten())
beta = np.linalg.inv(X.T * W * X) * X.T * W * Y
loss = np.asscalar((np.dot(x0, beta)))*sign
return loss
def primal_scalarized_L1_feasibility_for_saddle(gamma, w, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, pe_s, p_a1_s,
nS, nA, tight= True, quiet = True):
# Minimize L1 residuals over g
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
m = gp.Model()
p_infty_b = p_infty_b.flatten()
# w = m.addVars(nS)
g = m.addVars(nS,nA,nS) #\beta_k(a\mid j)
z = m.addVars(nS)
if quiet: m.setParam("OutputFlag", 0)
epsilon = 0.5
for k in range(nS):
m.addConstr( z[k] >= (-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( z[k] >= -1*(-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
for k in range(nS):
for a in range(nA):
for j in range(nS):
m.addConstr(g[k,a,j] <= b_bnd[a,j])
m.addConstr(g[k,a,j] >= a_bnd[a,j])
for a in range(nA):
if tight:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS) ] ) == 1)
else:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) - 1 <= epsilon)
m.addConstr(1 - gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) <= epsilon)
m.update()
expr = gp.quicksum(z)
m.setObjective(expr, gp.GRB.MINIMIZE)
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
g_ = np.asarray([g[k,a,j].x for k in range(nS) for a in range(nA) for j in range(nS) ]).reshape([nS,nA,nS])
return [m.objVal, g_]
else:
g = None
return [None, g]
# g_ = m.getAttr('x', g)
def saddle_outer_min_w(gamma, g, Phi, eta, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, pe_s, p_a1_s,nS, nA, sense_min = True):
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b), 1)
m = gp.Model()
p_infty_b = p_infty_b.flatten()
w = m.addVars(nS)
z = m.addVars(nS)
quiet = True
if quiet: m.setParam("OutputFlag", 0)
for k in range(nS):
m.addConstr( z[k] >= (-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( z[k] >= -1*(-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( gp.quicksum(w ) == 1)
m.update()
sense_min01 = 1 if sense_min else -1
expr = eta * gp.quicksum(z) + sense_min01 * gp.quicksum( w[k] *Phi[k]*p_infty_b[k] for k in range(nS))
m.setObjective(expr, gp.GRB.MINIMIZE)
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
w_ = np.asarray([w[k].x for k in range(nS) ])
z_ = np.asarray([z[k].x for k in range(nS) ])
wphi_obj = np.dot(w_,Phi)
print m.objVal
return [wphi_obj, z_.sum() , w_]
else:
return None
def get_w_withAmatrix(s_a_giv_sprime,p_infty_b_s, p_e_s,p_a1_s, nSmarg):
'''
with indic[s=k] test function
'''
nA = len(p_e_s)
A = np.zeros([nSmarg,nSmarg]) # - np.eye(nSmarg)
for k in range(nSmarg):
for j in range(nSmarg):
A[k,j] += sum( [ s_a_giv_sprime[j,a,k]*p_infty_b_s[k] * (p_e_s[a,j] / p_a1_s[a,j]) for a in range(nA)] )
A[k,k] -= p_infty_b_s[k]
tildeA = A
tildeA[-1,:] = p_infty_b_s
v = np.zeros(nSmarg); v[-1] = 1
w = np.linalg.solve(tildeA, v)
return w
def get_w_withAmatrix_cond(s_a_giv_sprime,p_infty_b_s, p_e_s,p_a1_s, nSmarg):
'''
conditional on s = k
'''
nA = len(p_e_s)
A = np.zeros([nSmarg,nSmarg]) # - np.eye(nSmarg)
for k in range(nSmarg):
for j in range(nSmarg):
A[k,j] += sum( [ s_a_giv_sprime[j,a,k]* (p_e_s[a,j] / p_a1_s[a,j]) for a in range(nA)] )
A[k,k] -= 1
tildeA = A
tildeA[-1,:] = np.ones(nSmarg)
v = np.zeros(nSmarg); v[-1] = 1
w = np.linalg.solve(tildeA, v)
return w
def get_w_withAmatrix_cond_from_g(g,s_a_giv_sprime,p_infty_b_s, p_e_s, nSmarg):
'''
conditional on s = k
'''
nA = len(p_e_s)
A = np.zeros([nSmarg,nSmarg]) # - np.eye(nSmarg)
for k in range(nSmarg):
for j in range(nSmarg):
A[k,j] += sum( [ s_a_giv_sprime[j,a,k] * (p_e_s[a,j] / g[k,a,j]) for a in range(nA)] )
A[k,k] -= 1
tildeA = A
tildeA[-1,:] = np.ones(nSmarg)
v = np.zeros(nSmarg); v[-1] = 1
w = np.linalg.solve(tildeA, v)
return w
def primal_feasibility(gamma, w, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, pe_s, p_a1_s,
nS, nA, tight= True, quiet = True):
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b), 1)
m = gp.Model()
p_infty_b = p_infty_b.flatten()
# w = m.addVars(nS)
g = m.addVars(nS,nA,nS) #\beta_k(a\mid j)
if quiet: m.setParam("OutputFlag", 0)
epsilon = 0.5
for k in range(nS):
m.addConstr( 0 == (-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w))+ gamma*(-1*w[k] + gp.quicksum( sum([w[j]*s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
for k in range(nS):
for a in range(nA):
for j in range(nS):
m.addConstr(g[k,a,j] <= b_bnd[a,j])
m.addConstr(g[k,a,j] >= a_bnd[a,j])
for a in range(nA):
if tight:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS) ] ) == 1)
else:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) - 1 <= epsilon)
m.addConstr(1 - gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) <= epsilon)
m.update()
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
feasibility = True
g = np.asarray([g[k,a,j].x for k in range(nS) for a in range(nA) for j in range(nS) ]).reshape([nS,nA,nS])
else:
feasibility = False
g = None
# g_ = m.getAttr('x', g)
return [feasibility, g]
def primal_scalarized_L1_feasibility(gamma, w, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, pe_s, p_a1_s,
nS, nA, tight= True, quiet = True):
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b), 1)
m = gp.Model()
p_infty_b = p_infty_b.flatten()
# w = m.addVars(nS)
g = m.addVars(nS,nA,nS) #\beta_k(a\mid j)
z = m.addVars(nS)
if quiet: m.setParam("OutputFlag", 0)
epsilon = 0.5
for k in range(nS):
m.addConstr( z[k] >= (-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( z[k] >= -1*(-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
for k in range(nS):
for a in range(nA):
for j in range(nS):
m.addConstr(g[k,a,j] <= b_bnd[a,j])
m.addConstr(g[k,a,j] >= a_bnd[a,j])
for a in range(nA):
if tight:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS) ] ) == 1)
else:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) - 1 <= epsilon)
m.addConstr(1 - gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) <= epsilon)
m.update()
expr = gp.quicksum(z)
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
g = np.asarray([g[k,a,j].x for k in range(nS) for a in range(nA) for j in range(nS) ]).reshape([nS,nA,nS])
return [m.objVal, g]
else:
g = None
return [None, g]
# g_ = m.getAttr('x', g)
def dual_feasibility(gamma, w, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b_s, pe_s, p_a1_s,
nS, nA, tight= True, quiet = True):
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b_s), 1)
m = gp.Model()
p_infty_b_s = p_infty_b_s.flatten()
c = m.addVars(nS,nA,nS, lb = 0)
d = m.addVars(nS,nA,nS, lb = 0)
lmbda01 = m.addVars(nS, vtype=gp.GRB.BINARY);
# lmbda = m.addVars(nS, lb = -1*gp.GRB.INFINITY)
if tight:
mu = m.addVars(nA, lb = -1*gp.GRB.INFINITY)
m.update()
if quiet: m.setParam("OutputFlag", 0)
for j in range(nS):
for a in range(nA):
for k in range(nS):
if tight:
m.addConstr(c[j,a,k] - d[j,a,k] +
- w[j]*pe_s[a,j]*(2*lmbda01[k]-1)*s_a_giv_sprime[j,a,k]# gp.quicksum(lmbda[ind]*s_a_giv_sprime[j,a,ind]*w[j]*pe_s[a,j] for ind in range(nS))
+ mu[a]*s_a_giv_sprime[j,a,k]*p_infty_b_s[k]
<= 0 )
else:
m.addConstr(c[j,a,k] - d[j,a,k]
- w[j]*pe_s[a,j]*(2*lmbda01[k]-1)*s_a_giv_sprime[j,a,k] <= 0 )
# m.addConstr(lmbda[j] <= 1)
# m.addConstr(lmbda[j] >= -1)
m.update()
expr = gp.LinExpr()
expr += gp.quicksum( c[j,a,k]*a_bnd[a,j] for k in range(nS) for a in range(nA) for j in range(nS) )
expr += gp.quicksum( -1*d[j,a,k]*b_bnd[a,j] for k in range(nS) for a in range(nA) for j in range(nS) )
expr += gp.quicksum( -1*(2*lmbda01[k]-1) * w[k] for k in range(nS) )
if tight:
expr += gp.quicksum( mu )
# need to change for discounted case
m.setObjective(expr, gp.GRB.MAXIMIZE); m.optimize()
if (m.status == gp.GRB.OPTIMAL):
print 'c, ', [c[j,a,k].x for j in range(nS) for a in range(nA) for k in range(nS)]
print 'd, ', [d[j,a,k].x for j in range(nS) for a in range(nA) for k in range(nS)]
lmbda_ = [(2*lmbda01[k].x-1) for k in range(nS)]
return [m.objVal, lmbda_]
else:
return [None, None]
def proj_w_(w_tilde, *args):
''' Project a given w vector onto feasible vector
'''
data = args[0]
a_bnd = data['a_bnd']; b_bnd = data['b_bnd']
p_infty_b_s = data['pbs'] ; p_e_s = data['p_e_s']
nS = len(p_infty_b_s)
nA = len(p_e_s)
s_a_giv_sprime = data['s_a_giv_sprime']
m = gp.Model()
w = m.addVars(nS)
quiet = True
if quiet: m.setParam("OutputFlag", 0)
m.addConstr( gp.quicksum(w[k] for k in range(nS)) == 1 )
m.update()
obj = gp.quicksum( (w_tilde[k]*w_tilde[k] - 2*w_tilde[k]*w[k] + w[k]*w[k] for k in range(nS) ))
m.setObjective(obj, gp.GRB.MINIMIZE)
m.optimize()
w_ = np.asarray([w[k].x for k in range(nS) ])
return [w_,m.objVal]
def subgrad_H_wrt_w(w,*args):
'''
Gradient of:
\max_{g \in \Wset} \{ \sum_k
\abs{w_k \Pstat_b(k) - \sum_j w_j \Pstatcompactb_{j,a,k} \pi^e_{a,j} g_k(a\mid j)) } $$
and let $m_k = {w_k \Pstat_b(k) - \sum_j w_j \Pstatcompactb_{j,a,k} \pi^e_{a,j} g_k(a\mid j)) }
with respect to w
Requires optimal g for computation
'''
data = args[0]
a_bnd = data['a_bnd']; b_bnd = data['b_bnd']
p_infty_b_s = data['pbs'] ; p_e_s = data['p_e_s']
s_a_giv_sprime = data['s_a_giv_sprime']
g = data['g']
nSmarg = len(p_infty_b_s)
nA = len(p_e_s)
A = np.zeros([nSmarg,nSmarg]) # - np.eye(nSmarg)
for k in range(nSmarg):
for j in range(nSmarg):
A[k,j] += sum( [ s_a_giv_sprime[j,a,k]*p_infty_b_s[k] * (p_e_s[a,j] *g[k,a,j]) for a in range(nA)] )
A[k,k] -= p_infty_b_s[k]
m = np.dot(A, w)
subgrad_wrt_w = np.zeros(nSmarg)
# \partial_{w_j} H = \sum_k \op{sgn}(m_k) ( \Pstatcompactb_k \mathbb{I}[k=j] - \sum_a \Pstatcompactb_{j,a,k} \pi^e_{a,j} g_{k,a,j} )
for k in range(nSmarg):
subgrad_wrt_w[k] = sum([np.sign(m[kprime]) * (p_infty_b_s[kprime]*(kprime== k)
- sum([s_a_giv_sprime[j,a,k]*p_infty_b_s[k]*p_e_s[a,j]*g[k,a,j] for a in range(nA)]) ) for kprime in range(nSmarg)])
return subgrad_wrt_w
def max_G_primal_scalarized_L1_for_saddle(gamma, w, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, pe_s,nS, nA, tight= True, quiet = True):
# maximize KKT residuals over g
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
m = gp.Model()
p_infty_b = p_infty_b.flatten()
# w = m.addVars(nS)
g = m.addVars(nS,nA,nS) #\beta_k(a\mid j)
z = m.addVars(nS)
if quiet: m.setParam("OutputFlag", 0)
tight = True
epsilon = 0.5
for k in range(nS):
m.addConstr( z[k] >= (-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( z[k] >= -1*(-1*w[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
for k in range(nS):
for a in range(nA):
for j in range(nS):
m.addConstr(g[k,a,j] <= b_bnd[a,j])
m.addConstr(g[k,a,j] >= a_bnd[a,j])
for a in range(nA):
if tight:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS) ] ) == 1)
else:
m.addConstr(gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) - 1 <= epsilon)
m.addConstr(1 - gp.quicksum([g[k,a,j] *s_a_giv_sprime[j,a,k]*p_infty_b[k] for k in range(nS) for j in range(nS)] ) <= epsilon)
m.update()
expr = 0
# gp.quicksum(z)
m.setObjective(expr,gp.GRB.MAXIMIZE)
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
g_ = np.asarray([g[k,a,j].x for k in range(nS) for a in range(nA) for j in range(nS) ]).reshape([nS,nA,nS])
return [m.objVal, g_]
else:
g = None
return [None, g]
def alternating(Phi, g, w, N_RNDS, data, eta_0=1, eta_step_schedule=1.4, sigma_step_schedule = 0.6, gamma = 1):
# min w on the inside
# max g on the outside
[a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, p_e_s, p_a1_s] = data
nS = len(p_infty_b); nA = len(p_e_s)
risks = np.zeros(N_RNDS)
THTS = [None] * N_RNDS; PARAMS = [None] * N_RNDS; losses = [None] * N_RNDS
gs = [None] * N_RNDS;
quiet = True
# initialize randomly in [a_, b_]
for k in range(N_RNDS):
eta_t = eta_0 * np.power((k + 1) * 1.0, eta_step_schedule)
print eta_t
# Minimize residuals wrt g over w
[obj_phival, residuals, w] = saddle_outer_min_w(gamma, g, Phi, eta_t, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, p_e_s, p_a1_s,nS, nA)
print 'obj phi', obj_phival, ', residuals: ', residuals
# Maximize over g
print w
[objVal, g] = max_G_primal_scalarized_L1_for_saddle(gamma, w, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b, p_e_s, nS, nA, quiet = quiet)
gs[k] = g
print g
THTS[k] = w; losses[k] = obj_phival
return [losses, gs, THTS]
def saddle_inner_min_w(gamma, g, eta, *args):
data = args[0]
a_bnd = data['a_bnd']; b_bnd = data['b_bnd']
Phi = data['Phi']
p_infty_b = data['pbs'] ; p_e_s = data['p_e_s']
nS = len(p_infty_b)
nA = len(p_e_s)
s_a_giv_sprime = data['s_a_giv_sprime']
sense_min = data['sense_min']
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b), 1)
m = gp.Model()
p_infty_b = p_infty_b.flatten()
w = m.addVars(nS)
z = m.addVars(nS)
quiet = True
if quiet: m.setParam("OutputFlag", 0)
for k in range(nS):
m.addConstr( z[k] >= (-1*w[k]*p_infty_b[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k]*p_infty_b[k] * (p_e_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( z[k] >= -1*(-1*w[k]*p_infty_b[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k]*p_infty_b[k] * (p_e_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
# m.addConstr( 0 == (1-gamma)*(1-gp.quicksum(w))+ gamma*(-1*w[k] + gp.quicksum( sum([s_a_giv_sprime[j,a,k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )
m.addConstr( gp.quicksum(w[k] *p_infty_b[k] for k in range(nS) ) == 1)
m.update()
sense_min01 = 1 if sense_min else -1
expr_proj = gp.quicksum(z) #+ sense_min01 * gp.quicksum( w[k] *Phi[k]*p_infty_b[k] for k in range(nS))
m.setObjective(expr_proj, gp.GRB.MINIMIZE)
# expr = eta * gp.quicksum(z) + sense_min01 * gp.quicksum( w[k] *Phi[k]*p_infty_b[k] for k in range(nS))
# m.setObjective(expr, gp.GRB.MINIMIZE)
m.optimize()
if (m.status == gp.GRB.OPTIMAL):
w_ = np.asarray([w[k].x for k in range(nS) ])
z_ = np.asarray([z[k].x for k in range(nS) ])
wphi_obj = np.dot(w_,Phi)
return [wphi_obj, z_.sum() , w_]
else:
return None
def proj_grad_descent_smoothed(g, N_RNDS, data,
eta_0=1, step_schedule=0.5, sigma_0 = 0.5, sigma_step_schedule = 0.5, sense_min = True, gamma = 1,
quiet = True):
# solve penalized inner minimization over w
risks = np.zeros(N_RNDS)
THTS = [None] * N_RNDS; PARAMS = [None] * N_RNDS; losses = [None] * N_RNDS
gs_proj = [None] * N_RNDS;
gs_init = [None] * N_RNDS; residuals_ = [None] * N_RNDS
a_bnd = data['a_bnd']; b_bnd = data['b_bnd']
p_infty_b_s = data['pbs'] ; p_e_s = data['p_e_s']
nS = len(p_infty_b_s)
nA = len(p_e_s)
Phi = data['Phi']
s_a_giv_sprime = data['s_a_giv_sprime']
# initialize randomly in [a_, b_]
for k in range(N_RNDS):
eta_t = eta_0 * 1.0 / np.power((k + 1) * 1.0, step_schedule)
sigma_t = sigma_0 * 1.0 / np.power((k + 1) * 1.0, step_schedule)
# Project before taking gradient steps
[obj_phival, residuals, w] = saddle_inner_min_w(gamma, g, eta_t, *[data])
[feas, g_] = primal_feasibility_testg(gamma, w,g , a_bnd, b_bnd, s_a_giv_sprime, p_infty_b_s, p_e_s,nS, nA)
if g_ is not None:
# if feasibility oracle
[g_grad,theta] = grad_H_wrt_g_explicit(g_, *[data])
else:
[g_grad,theta] = grad_H_wrt_g_explicit(g, *[data])
if not quiet:
print 'eta', eta_t
print 'w', w, 'w-norm, ', w/w.sum()
print 'residuals, ', residuals
print feas
print g_
print 'th,', theta / theta.sum()
# default to max behavior
if sense_min == True: # maximize the negative of
g = -g
g_grad = -1*g_grad
losses[k] = -1*np.dot(theta,Phi)
losses[k] = np.dot(theta,Phi)
if g_ is not None:
g_step = g_ + sigma_t * g_grad;
else:
g_step = g + sigma_t * g_grad;
# check if this step introduces cycling
gs_init[k] = g_step
[g_proj, proj_val] = proj_g_(g_step, *[data])
gs_proj[k] = g_proj; residuals_[k] = residuals
g = g_proj
THTS[k] = w;
return [losses, gs_init, gs_proj, THTS, residuals_]
def grad_H_wrt_g_explicit(g, *args):
''' Evaluate gradient
Assume g is [k,a,j]
-({I}[j /= |S|] pi^e_a,j Pb_{j,a,k}) (\E[A']^{-\top } \Phi \theta^\top)_{i,j}
'''
data = args[0]
Phi = data['Phi'] # state
p_infty_b_s = data['pbs']
nSmarg = len(p_infty_b_s)
s_a_giv_sprime = data['s_a_giv_sprime']
p_e_s = data['p_e_s']; nA = len(p_e_s); check_grad = data['check_grad']
A = np.zeros([nSmarg,nSmarg])
for k in range(nSmarg):
for j in range(nSmarg):
A[k,j] += sum( [ s_a_giv_sprime[j,a,k]*p_infty_b_s[k] * (p_e_s[a,j] *g[k,a,j] ) for a in range(nA)] )
A[k,k] -= p_infty_b_s[k]
tildeA = A
# Make regular and add normalization
tildeA[-1,:] = p_infty_b_s
v = np.zeros([nSmarg]); v[-1] = 1
theta = np.linalg.inv(tildeA).dot(v)
# print 'theta from grad comp,', theta
# gradient specific operations
outer_ = np.outer(Phi, theta)
M = np.linalg.inv(tildeA).dot(outer_)
g_grad = np.zeros(g.shape)
s_a_giv_sprime = data['s_a_giv_sprime'] ;p_e_s = data['p_e_s']; p_infty_b_s = data['pbs']
for k in range(g_grad.shape[0]):
for a in range(g_grad.shape[1]):
for j in range(g_grad.shape[2])[:-1]: # omit last row of J
g_grad[k,a,j] = -1*M[j,k]*s_a_giv_sprime[j,a,k]*p_infty_b_s[k]*p_e_s[a,j]
# j,k or k,j ?
return [g_grad,theta]
def primal_feasibility_testg(gamma, w, g_tilde, a_bnd,b_bnd, s_a_giv_sprime, p_infty_b_s, pe_s,
nS, nA, tight= True, quiet = True):
# use test function I[ s=k ] (aka solve with tthe unconditional expectation )
# project in L2 norm of g
for k in range(nS):
assert np.isclose((s_a_giv_sprime[:,:,k].sum()), 1,atol = 0.01)
assert np.isclose(sum(p_infty_b_s), 1)
m = gp.Model()
p_infty_b_s = p_infty_b_s.flatten()
# w = m.addVars(nS)
g = m.addVars(nS,nA,nS) #\beta_k(a\mid j)
if quiet: m.setParam("OutputFlag", 0)
epsilon = 0.5
for k in range(nS):
m.addConstr( 0 == (-1*w[k]*p_infty_b_s[k] + gp.quicksum( w[j]*gp.quicksum([s_a_giv_sprime[j,a,k]*p_infty_b_s[k] * (pe_s[a,j] * g[k,a,j]) for a in range(nA)]) for j in range(nS) )) )