-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbankProblem.py
1794 lines (1644 loc) · 73.7 KB
/
bankProblem.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
//
// Copyright (c) 2011 Ronaldo Carpio
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. The authors make no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//
from __future__ import print_function
import operator
import scipy, time, sys, itertools, scipy.stats
from collections import defaultdict
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cPickle as pickle
import gzip, os, glob, shutil
import markup
import table
import pyublas
import multiprocessing
# import c++ modules
import _debugMsg, _maximizer as mx, _myfuncs
import _bankProblem
import bellman
import lininterp2 as linterp
import plot3d
#import markovChain
# returns a dict that groups xlist by f(x) for each element x in xlist
def groupby(xlist, f):
result = defaultdict(list)
[result[f(x)].append(x) for x in xlist]
return result
# globals
class g:
Grid_M = None
Grid_S = None
Grid_P = None
IterList = []
Params = None
ParamSettings = {}
NIters = 0
IterResult = None
# grid size, boundaries
DEF_M_MAX = 4
DEF_S_MAX = 5
DEF_P_MAX = 2
DEF_M_GRID_SIZE = 50
DEF_S_GRID_SIZE = 40
DEF_P_GRID_SIZE = 30
DEF_D_GRID_SIZE = 40
DEF_SLOW_IN_GRID_SIZE = 40
DEF_SLOW_IN_FRAC_MAX = 4.0
# M_MAX = 4
# S_MAX = 5
# P_MAX = 2
# M_GRID_SIZE = 50
# S_GRID_SIZE = 40
# P_GRID_SIZE = 30
D_GRID_SIZE = DEF_D_GRID_SIZE
SLOW_IN_GRID_SIZE = DEF_SLOW_IN_GRID_SIZE
SLOW_IN_FRAC_MAX = DEF_SLOW_IN_FRAC_MAX
@staticmethod
def setGridSize(M=None, S=None, P=None, D=None, frac=None):
if M:
#(g.M_MAX, g.M_GRID_SIZE) = M
g.Grid_M = scipy.linspace(0, M[0], M[1])
if S:
#(g.S_MAX, g.S_GRID_SIZE) = S
g.Grid_S = scipy.linspace(0, S[0], S[1])
if P:
#(g.P_MAX, g.P_GRID_SIZE) = P
g.Grid_P = scipy.linspace(0, P[0], P[1])
if D: g.D_GRID_SIZE = D
if frac: (g.SLOW_IN_FRAC_MAX, g.SLOW_IN_GRID_SIZE) = frac
@staticmethod
def getGridSize():
#return {'M': (g.M_MAX, g.M_GRID_SIZE), 'S': (g.S_MAX, g.S_GRID_SIZE), 'P': (g.P_MAX, g.P_GRID_SIZE), 'D': g.D_GRID_SIZE, 'frac': (g.SLOW_IN_GRID_SIZE, g.SLOW_IN_FRAC_MAX)}
return {
'M': (g.Grid_M[-1], len(g.Grid_M)),
'S': (g.Grid_S[-1], len(g.Grid_S)),
'P': (g.Grid_P[-1], len(g.Grid_P)),
'D': g.D_GRID_SIZE,
'frac': (g.SLOW_IN_FRAC_MAX, g.SLOW_IN_GRID_SIZE)
}
@staticmethod
def setDefaultGridSize():
g.setGridSize(M=(g.DEF_M_MAX, g.DEF_M_GRID_SIZE), S=(g.DEF_S_MAX, g.DEF_S_GRID_SIZE), P=(g.DEF_P_MAX, g.DEF_P_GRID_SIZE), D=g.DEF_D_GRID_SIZE, frac=(g.DEF_SLOW_IN_FRAC_MAX, g.DEF_SLOW_IN_GRID_SIZE))
# colors of states
# 0 - bankrupt next period (M_t+1 is always <0)
# 1 - risky (M_t+1 is <0 in bad shock)
# 2 - safe (M_t+1 is always >0)
# 4 - bankrupt now
STATE_BANKRUPT = 0
STATE_RISKY = 1
STATE_SAFE = 2
STATE_ABSORBED = 4
StateToColor = {
STATE_BANKRUPT: 'r',
STATE_RISKY: 'b',
STATE_SAFE: 'g',
STATE_ABSORBED: 'k'
}
# max numbers of value function iterations to try before giving up
MAX_VITERS = 800
MAX_TIME = 1000
MAX_V = 10000
@staticmethod
def reset():
g.Grid_M = None
g.Grid_S = None
g.Grid_P = None
g.IterList = []
g.Params = None
g.ParamSettings = {}
g.NIters = 0
g.IterResult = None
@staticmethod
def to_dict():
dict = {
'Grid_M': g.Grid_M,
'Grid_S': g.Grid_S,
'Grid_P': g.Grid_P,
'IterList': g.IterList,
'ParamSettings': g.ParamSettings,
'NIters': g.NIters,
'IterResult': g.IterResult
}
return dict
@staticmethod
def from_dict(dict):
g.Grid_M = dict['Grid_M']
g.Grid_S = dict['Grid_S']
g.Grid_P = dict['Grid_P']
g.IterList = dict['IterList']
g.ParamSettings = dict['ParamSettings']
g.NIters = dict['NIters']
g.IterResult = dict['IterResult']
g.setDefaultGridSize()
######################################################################
# save/load optimization results
def saveRun(filename, allIters=False):
output = gzip.open(filename, 'wb')
dict = g.to_dict()
if (not allIters):
dict['IterList'] = g.IterList[-1:]
pickle.dump(dict, output)
output.close()
def loadRun(filename):
pk_file = gzip.open(filename, 'rb')
dict = pickle.load(pk_file)
pk_file.close()
g.from_dict(dict)
def loadRun_1(filename):
pk_file = gzip.open(filename, 'rb')
dict = pickle.load(pk_file)
pk_file.close()
# change ParamSettings from a list to a dict
[beta, grid_M, grid_S, grid_P, rFast, rSlow, slowOut, fastOut, fastIn, probSpace] = dict['ParamSettings']
dict['ParamSettings'] = {'beta':beta, 'grid_M':grid_M, 'grid_S':grid_S, 'grid_P':grid_P, 'rFast':rFast, 'rSlow':rSlow, 'slowOut':slowOut,
'fastOut':fastOut, 'fastIn':fastIn, 'probSpace':probSpace}
g.from_dict(dict)
def loadRun_2(filename):
pk_file = gzip.open(filename, 'rb')
dict = pickle.load(pk_file)
pk_file.close()
if (dict['NIters'] > 200):
dict['IterResult'] = bellman.ITER_RESULT_MAX_ITERS
else:
dict['IterResult'] = bellman.ITER_RESULT_CONVERGENCE
g.from_dict(dict)
g_LoadFns = {1: loadRun_1, 2: loadRun_2}
def convert_prev_version(filename, version):
print("loading v1 file: %s" % filename)
g_LoadFns[version](filename)
print("saving file: %s" % filename)
saveRun(filename)
def convert_prev_version_dir(dirname, version, filespec="*.out"):
pattern = os.path.join(dirname, filespec)
fileList = glob.glob(pattern)
for filename in fileList:
convert_prev_version(filename, version)
def resaveSmallFiles(dirname, dir2=None):
pattern = os.path.join(dirname, "*.out")
fileList = glob.glob(pattern)
for filename in fileList:
file = filename
outFile = file
if (dir2 != None):
base = os.path.basename(file)
outFile = os.path.join(dir2, base)
print("%s -> %s" % (file, outFile))
try:
loadRun(file)
saveRun(outFile)
#print(outFile)
except StandardError as err:
print("exception on %s: " % file, err)
class BankParams(_bankProblem.BankParams4):
def __init__(self, beta, rFast, rSlow, slowOut, fastOut, fastIn, probSpace, bankruptcyPenalty, popGrowth, **kwargs):
super(BankParams,self).__init__(beta, rFast, rSlow, slowOut, fastOut, fastIn, probSpace, bankruptcyPenalty, popGrowth)
def getControlGridList(self, stateVarList):
M = stateVarList[0]
S = stateVarList[1]
P = stateVarList[2]
dGrid = scipy.linspace(0, M, g.D_GRID_SIZE)
slowInFracGrid = scipy.linspace(0, g.SLOW_IN_FRAC_MAX, g.SLOW_IN_GRID_SIZE)
return [dGrid, slowInFracGrid]
def triangleDistribution(N):
if (N % 2 == 0):
# even
incrs = scipy.array(range(1, (N/2)+1) + range(N/2, 0, -1)) * 1.0
else:
# odd
incrs = scipy.array(range(1, (N/2)+1) + [N/2 + 1] + range(N/2, 0, -1)) * 1.0
dy = 1.0 / sum(incrs)
probSpace = incrs * dy
# ensure the sum adds up to 1.0
probSpace[-1] += (1.0 - sum(probSpace))
return probSpace
# class for generating test cases (varying the parameters)
class TestCaseGenerator:
def getDefaultParamsDict(self): raise NotImplementedError()
def getOverrideParamsList(self): raise NotImplementedError()
def getFilenamePrefix(self, testName, paramsDict): raise NotImplementedError()
# when we vary 2 parameters, get value1 and value 2
def getXYName(self): raise NotImplementedError()
def getXYGraphLabel(self): raise NotImplementedError()
def getXYShortLabel(self): raise NotImplementedError()
def getXY(self, paramsDict): raise NotImplementedError()
# class for varying interest rates
class VaryR_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, rFastRange=scipy.linspace(0, 0.08, 20), rSlowRange=scipy.linspace(0, 0.15, 20), slowOut=scipy.array([0.1, 0.1]), **kwargs):
(self.rFastRange, self.rSlowRange) = (rFastRange, rSlowRange)
self.defaultParams = {
'beta': beta,
'rSlow': 0.15,
'rFast': 0.02,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': slowOut,
'fastIn': scipy.array([0.8, 0.8]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
self.defaultParams.update(kwargs)
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
beta = self.defaultParams['beta']
# rFast from 0 to 1/beta + 1.0
# rSlow from 0 to 1/beta + 1.0
for rFast in self.rFastRange:
for rSlow in self.rSlowRange:
tests.append( ("test_r", {'rSlow':rSlow, 'rFast':rFast}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
filename = "%s_beta%.2f_rS%.3f_rF%.3f_pHigh%.2f_outHigh%.2f" % (testName, paramsDict['beta'], paramsDict['rSlow'], paramsDict['rFast'], paramsDict['probSpace'][1], paramsDict['fastOut'][1])
return filename
def getXYName(self): return ('rSlow', 'rFast')
def getXYGraphLabel(self): return ('interest rate on loans', 'interest rate on deposits')
def getXYShortLabel(self): return (r'$r^L$', r'$r^D$')
def getXY(self, paramsDict):
return (paramsDict['rSlow'], paramsDict['rFast'])
# use a different probability space.
class VaryR2_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, rFastRange=scipy.linspace(0, 0.08, 20), rSlowRange=scipy.linspace(0, 0.15, 20), slowOut=scipy.array([0.1, 0.1, 0.1, 0.1]), **kwargs):
(self.rFastRange, self.rSlowRange) = (rFastRange, rSlowRange)
self.defaultParams = {
'beta': beta,
'rSlow': 0.15,
'rFast': 0.02,
'probSpace': scipy.array([0.25, 0.25, 0.25, 0.25]),
'fastOut': scipy.array([0.7, 0.7, 0.9, 0.9]),
'slowOut': slowOut,
'fastIn': scipy.array([0.8, 0.8, 0.8, 0.8]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
self.defaultParams.update(kwargs)
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
beta = self.defaultParams['beta']
# rFast from 0 to 1/beta + 1.0
# rSlow from 0 to 1/beta + 1.0
for rFast in self.rFastRange:
for rSlow in self.rSlowRange:
tests.append( ("test_r", {'rSlow':rSlow, 'rFast':rFast}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
filename = "%s_beta%.2f_rS%.3f_rF%.3f_pHigh%.2f_outHigh%.2f" % (testName, paramsDict['beta'], paramsDict['rSlow'], paramsDict['rFast'], paramsDict['probSpace'][1], paramsDict['fastOut'][1])
return filename
def getXYName(self): return ('rSlow', 'rFast')
def getXYGraphLabel(self): return ('interest rate on loans', 'interest rate on deposits')
def getXYShortLabel(self): return (r'$r^L$', r'$r^D$')
def getXY(self, paramsDict):
return (paramsDict['rSlow'], paramsDict['rFast'])
# vary pHigh and out frac variance
class VaryOutFracPHigh_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, pHighRange=scipy.linspace(0., 1., 20), outFracLowRange=scipy.linspace(0.3, 0.9, 20)):
self.defaultParams = {
'beta': beta,
'rSlow': 0.15,
'rFast': 0.10,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': scipy.array([0.1, 0.1]),
'fastIn': scipy.array([0.8, 0.8]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
(self.pHighRange, self.outFracLowRange) = (pHighRange, outFracLowRange)
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
for pHigh in self.pHighRange:
for outFracLow in self.outFracLowRange:
probSpace = scipy.array([1.0-pHigh, pHigh])
fastOut = scipy.array([outFracLow, 0.9])
tests.append( ("test_var_pHigh", {'probSpace':probSpace, 'fastOut':fastOut}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
filename = "%s_pHigh%.2f_fastOut%.2f" % (testName, paramsDict['probSpace'][1], paramsDict['fastOut'][0])
return filename
def getXYName(self): return ('pHigh', 'fastOutFracLow')
def getXYGraphLabel(self): return (r'probability of high $\alpha^D_t$', r'low realization of $\alpha^D_t$')
def getXY(self, paramsDict):
return (paramsDict['probSpace'][1], paramsDict['fastOut'][0])
# mean_log_growth is the expected log growth of deposits _Without_ considering insurance (i.e. from new deposits and withdrawals only)
# we construct fastOut such that low log growth is (mean_log_growth-delta) in the low case, (mean_log_growth+delta) in the high case
def fastOutFrac(inFrac, mean_log_growth, delta):
alpha_high = 1.0 + inFrac - scipy.exp(mean_log_growth - delta)
alpha_low = 1.0 + inFrac - scipy.exp(mean_log_growth + delta)
g_low = 1.0 - alpha_high + inFrac
g_high = 1.0 - alpha_low + inFrac
#print(scipy.sqrt(g_low * g_high))
return [alpha_low, alpha_high]
class VaryDelta_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, rFastRange=scipy.linspace(0, 0.15, 16), mean_log_growth=0.0, delta_log_growth_gridsize=20, fastInFrac=0.8):
(self.beta, self.rFastRange, self.mean_log_growth, self.delta_log_growth_gridsize, self.fastInFrac) = (beta, rFastRange, mean_log_growth, delta_log_growth_gridsize, fastInFrac)
self.defaultParams = {
'beta': beta,
'rSlow': 0.15,
'rFast': 0.,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': scipy.array([0.1, 0.1]),
'fastIn': scipy.array([fastInFrac, fastInFrac]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
# lowest delta is 0
# highest delta is when alpha (out frac) = 0
self.delta_log_growth_max = mean_log_growth - scipy.log(1 - 1 + fastInFrac)
self.delta_log_growth_range = scipy.linspace(0, self.delta_log_growth_max, self.delta_log_growth_gridsize)
self.delta_log_growth_range[0] = 0.0001
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
fastInFrac = self.defaultParams['fastIn'][0]
for rFast in self.rFastRange:
for delta_log_growth in self.delta_log_growth_range:
fastOut = scipy.array(fastOutFrac(fastInFrac, self.mean_log_growth, delta_log_growth))
assert(fastOut[0] <= fastOut[1])
tests.append( ("test_delta", {'rFast':rFast, 'fastOut':fastOut, 'delta':delta_log_growth}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
rFast = paramsDict['rFast']
fastOut = paramsDict['fastOut']
delta = paramsDict['delta']
filename = "%s_rFast%.3f_delta%.3f_outFrac%.3f_%.3f" % (testName, rFast, delta, fastOut[0], fastOut[1])
return filename
def getXYName(self): return ('delta', 'rFast')
def getXYGraphLabel(self): return (r'$\delta$', 'interest rate on deposits')
def getXY(self, paramsDict):
rFast = paramsDict['rFast']
delta = paramsDict['delta']
return (delta, rFast)
# use a simple arithmetic mean. alpha_low = alpha_mean - delta, alpha_high = alpha_mean + delta
class VaryDelta2_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, rSlow=0.15, rFastRange=scipy.linspace(0, 0.15, 5), alphaMean=0.8, deltaRange=scipy.linspace(0, 0.2, 5), fastInFrac=0.8, slowOut=scipy.array([0.1, 0.1]), **kwargs):
(self.beta, self.rFastRange, self.alphaMean, self.deltaRange, self.fastInFrac) = (beta, rFastRange, alphaMean, deltaRange, fastInFrac)
self.defaultParams = {
'beta': beta,
'rSlow': rSlow,
'rFast': 0.,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': slowOut,
'fastIn': scipy.array([fastInFrac, fastInFrac]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
self.defaultParams.update(kwargs)
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
fastInFrac = self.defaultParams['fastIn'][0]
for rFast in self.rFastRange:
for delta in self.deltaRange:
fastOut = scipy.array([self.alphaMean - delta, self.alphaMean + delta])
assert(fastOut[0] <= fastOut[1])
tests.append( ("test_delta", {'rFast':rFast, 'fastOut':fastOut, 'delta':delta}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
rFast = paramsDict['rFast']
fastOut = paramsDict['fastOut']
delta = paramsDict['delta']
filename = "%s_rFast%.3f_delta%.3f_outFrac%.3f_%.3f" % (testName, rFast, delta, fastOut[0], fastOut[1])
return filename
def getXYName(self): return ('delta', 'rFast')
def getXYGraphLabel(self): return (r'$\delta$ ($\alpha^D_t = \bar{\alpha^D} \pm \delta$)', 'interest rate on deposits')
def getXYShortLabel(self): return (r'$\delta$', r'$r^D$')
def getXY(self, paramsDict):
rFast = paramsDict['rFast']
delta = paramsDict['delta']
return (delta, rFast)
class VaryDuration_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, delta=0.0, rSlow=0, rFast=0, inFracFastRange=scipy.linspace(0.1, 0.9, 20), outFracSlowRange=scipy.linspace(0.1, 0.8, 20)):
(self.beta, self.delta, self.inFracFastRange, self.outFracSlowRange) = (beta, delta, inFracFastRange, outFracSlowRange)
self.defaultParams = {
'beta': beta,
'rSlow': rSlow,
'rFast': rFast,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.8, 0.8]),
'slowOut': scipy.array([0.1, 0.1]),
'fastIn': scipy.array([0.7, 0.7]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
for inFracFast in self.inFracFastRange:
for outFracSlow in self.outFracSlowRange:
fastIn = scipy.array([inFracFast, inFracFast])
slowOut = scipy.array([outFracSlow, outFracSlow])
(alpha_low, alpha_high) = fastOutFrac(inFracFast, mean_log_growth=0.0, delta=self.delta)
fastOut = scipy.array([alpha_low, alpha_high])
tests.append( ("test_duration", {'fastIn': fastIn, 'slowOut': slowOut, 'fastOut': fastOut}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
fastIn = paramsDict['fastIn'][0]
slowOut = paramsDict['slowOut'][0]
filename = "%s_fastIn%0.3f_slowOut%0.3f" % (testName, fastIn, slowOut)
return filename
def getXYName(self): return ('fastIn', 'slowOut')
def getXYGraphLabel(self): return (r'$\gamma^L$ (new deposits)', r'$\alpha^D$ (fraction of loans repaid)')
def getXY(self, paramsDict):
fastIn = paramsDict['fastIn'][0]
slowOut = paramsDict['slowOut'][0]
return (fastIn, slowOut)
class VaryDuration2_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, slowOutRange=scipy.linspace(0.2, 0.6, 5), rFastRange=scipy.linspace(0.02, 0.15, 5)):
(self.beta, self.slowOutRange, self.rFastRange) = (beta, slowOutRange, rFastRange)
self.defaultParams = {
'beta': beta,
'rSlow': 0.13,
'rFast': 0.,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.8, 0.8]),
'slowOut': scipy.array([0.4, 0.4]),
'fastIn': scipy.array([0.7, 0.7]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
for rFast in self.rFastRange:
for slowOutFrac in self.slowOutRange:
slowOut = scipy.array([slowOutFrac, slowOutFrac])
tests.append( ("test_duration", {'slowOut': slowOut, 'rFast':rFast}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
rFast = paramsDict['rFast']
slowOut = paramsDict['slowOut'][0]
filename = "%s_rF%0.3f_slowOut%0.3f" % (testName, rFast, slowOut)
return filename
def getXYName(self): return ('slowOutFrac', 'rFast')
def getXYGraphLabel(self): return (r'$\alpha^L$ (expected duration=$\frac{1}{\alpha^L}$', 'interest on deposits')
def getXYShortLabel(self): return (r'$\alpha^L$', r'$r^D$')
def getXY(self, paramsDict):
rFast = paramsDict['rFast']
slowOut = paramsDict['slowOut'][0]
return (slowOut, rFast)
# duration vs. uncertainty
class VaryDuration3_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, slowOutRange=scipy.linspace(0.2, 0.6, 5), alphaMean=0.8, deltaRange=scipy.linspace(0, 0.2, 5), rFast=0.0):
(self.beta, self.slowOutRange, self.alphaMean, self.deltaRange) = (beta, slowOutRange, alphaMean, deltaRange)
self.defaultParams = {
'beta': beta,
'rSlow': 0.13,
'rFast': rFast,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.8, 0.8]),
'slowOut': scipy.array([0.4, 0.4]),
'fastIn': scipy.array([0.7, 0.7]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
for delta in self.deltaRange:
for slowOutFrac in self.slowOutRange:
fastOut = scipy.array([self.alphaMean - delta, self.alphaMean + delta])
slowOut = scipy.array([slowOutFrac, slowOutFrac])
tests.append( ("test_duration2", {'slowOut': slowOut, 'fastOut':fastOut, 'delta':delta}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
fastOut = paramsDict['fastOut']
delta = paramsDict['delta']
slowOut = paramsDict['slowOut'][0]
filename = "%s_delta%0.3f_slowOut%0.3f_fastOut%0.3f_%0.3f" % (testName, delta, slowOut, fastOut[0], fastOut[1])
return filename
def getXYName(self): return ('slowOutFrac', 'delta')
def getXYGraphLabel(self): return (r'$\alpha^L$ (expected duration=$\frac{1}{\alpha^L}$', r'$\delta$')
def getXYShortLabel(self): return (r'$\alpha^L$', r'$\delta$')
def getXY(self, paramsDict):
delta = paramsDict['delta']
slowOut = paramsDict['slowOut'][0]
return (slowOut, delta)
# vary pHigh and out frac variance
class VaryP_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, pHighRange=scipy.linspace(0.5, 1., 5), alphaMean=0.8, deltaRange=scipy.linspace(0, 0.2, 5), rFast=0.0, rSlow=0.13, slowOut=scipy.array([0.4, 0.4])):
(self.beta, self.pHighRange, self.alphaMean, self.deltaRange) = (beta, pHighRange, alphaMean, deltaRange)
self.defaultParams = {
'beta': beta,
'rSlow': rSlow,
'rFast': rFast,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': slowOut,
'fastIn': scipy.array([0.8, 0.8]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
for delta in self.deltaRange:
for pHigh in self.pHighRange:
fastOut = scipy.array([self.alphaMean - delta, self.alphaMean + delta])
probSpace = scipy.array([1.0-pHigh, pHigh])
tests.append( ("test_pHigh", {'probSpace':probSpace, 'fastOut':fastOut, 'delta':delta}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
delta = paramsDict['delta']
filename = "%s_pHigh%.3f_delta%0.3f_fastOut%.3f_%3f" % (testName, paramsDict['probSpace'][1], delta, paramsDict['fastOut'][0], paramsDict['fastOut'][1])
return filename
def getXYName(self): return ('pHigh', 'delta')
def getXYGraphLabel(self): return (r'$P(\alpha_{high})$', r'$\delta$')
def getXYShortLabel(self): return (r'$P(\alpha_{high})$', r'$\delta$')
def getXY(self, paramsDict):
delta = paramsDict['delta']
pHigh = paramsDict['probSpace'][1]
return (pHigh, delta)
# add uncertainty in loans
class VaryL_Generator(TestCaseGenerator):
def __init__(self, beta=0.9, L_alphaMean=0.4, L_deltaRange=scipy.linspace(0, 0.2, 5), D_alphaMean=0.8, D_deltaRange=scipy.linspace(0, 0.2, 5), rFast=0.0):
(self.beta, self.L_alphaMean, self.L_deltaRange, self.D_alphaMean, self.D_deltaRange) = (beta, L_alphaMean, L_deltaRange, D_alphaMean, D_deltaRange)
self.defaultParams = {
'beta': beta,
'rSlow': 0.13,
'rFast': rFast,
'probSpace': scipy.array([0.25, 0.25, 0.25, 0.25]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': scipy.array([0.1, 0.1]),
'fastIn': scipy.array([0.8, 0.8, 0.8, 0.8]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0])
}
def getDefaultParamsDict(self): return self.defaultParams
def getOverrideParamsList(self):
tests = []
for D_delta in self.D_deltaRange:
for L_delta in self.L_deltaRange:
fastOut = scipy.array([self.D_alphaMean - D_delta, self.D_alphaMean + D_delta, self.D_alphaMean - D_delta, self.D_alphaMean + D_delta])
slowOut = scipy.array([self.L_alphaMean - L_delta, self.L_alphaMean - L_delta, self.L_alphaMean + L_delta, self.L_alphaMean + L_delta])
tests.append( ("test_Ldelta", {'slowOut':slowOut, 'fastOut':fastOut, 'L_delta':L_delta, 'D_delta':D_delta}) )
return tests
def getFilenamePrefix(self, testName, paramsDict):
filename = "%s_Ldelta_%0.3f_Ddelta_%0.3f" % (testName, paramsDict['L_delta'], paramsDict['D_delta'])
return filename
def getXYName(self): return ('L_delta', 'D_delta')
r'$\delta^L$ ($\alpha^L_t = \bar{\alpha^L} \pm \delta^L$)'
r'$\delta^D$ ($\alpha^D_t = \bar{\alpha^D} \pm \delta^D$)'
def getXYGraphLabel(self): return (r'$\delta^L$ ($\alpha^L_t =\ \bar{\alpha}^L \pm\ \delta^L$)', r'$\delta^D$ ($\alpha^D_t =\ \bar{\alpha}^D \pm\ \delta^D$)')
def getXYShortLabel(self): return (r'$\delta^L$', r'$\delta^D$')
def getXY(self, paramsDict):
L_delta = paramsDict['L_delta']
D_delta = paramsDict['D_delta']
return (L_delta, D_delta)
g_TestR = VaryR_Generator(rFastRange=scipy.linspace(0, 0.15, 5), rSlowRange=scipy.linspace(0, 0.15, 5))
g_TestR2 = VaryR_Generator(rFastRange=scipy.linspace(0, 0.15, 5), rSlowRange=scipy.linspace(0, 0.15, 5), slowOut=scipy.array([0.4, 0.4]))
g_TestR3 = VaryR_Generator(rFastRange=scipy.linspace(0.09, 0.13, 5), rSlowRange=scipy.linspace(0.09, 0.13, 5), slowOut=scipy.array([0.4, 0.4]))
g_TestR4 = VaryR_Generator(rFastRange=scipy.linspace(0.1125, 0.15, 5), rSlowRange=scipy.linspace(0.1125, 0.15, 5), slowOut=scipy.array([0.4, 0.4]))
g_TestR5 = VaryR_Generator(rFastRange=scipy.array([0.03, 0.05, 0.1, 0.12]), rSlowRange=scipy.linspace(0.1, 0.16, 25), slowOut=scipy.array([0.4, 0.4]))
# R6 is same as R5 with a larger grid
g_TestR6 = VaryR_Generator(rFastRange=scipy.array([0.03, 0.05, 0.1, 0.12]), rSlowRange=scipy.linspace(0.1, 0.16, 25), slowOut=scipy.array([0.4, 0.4]), gridSizeDict={'S': (10, 80)})
# uses a different prob. distribution
g_Test2R = VaryR2_Generator(rFastRange=scipy.linspace(0.09, 0.13, 5), rSlowRange=scipy.linspace(0.09, 0.13, 5), slowOut=scipy.array([0.4, 0.4, 0.4, 0.4]))
g_TestDelta = VaryDelta2_Generator()
g_TestDelta2 = VaryDelta2_Generator(rSlow=0.12, rFastRange=scipy.linspace(0.02, 0.12, 11), deltaRange=scipy.linspace(0, 0.2, 11))
g_TestDelta3 = VaryDelta2_Generator(rSlow=0.12, rFastRange=scipy.linspace(0.02, 0.12, 6), deltaRange=scipy.linspace(0, 0.2, 6), slowOut=scipy.array([0.4, 0.4]))
g_TestDelta4 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.linspace(0.00, 0.08, 6), deltaRange=scipy.linspace(0, 0.12, 6), slowOut=scipy.array([0.4, 0.4]))
g_TestDelta5 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.linspace(0.048, 0.064, 5), deltaRange=scipy.linspace(0.04, 0.1, 5), slowOut=scipy.array([0.4, 0.4]))
g_TestDelta6 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.linspace(0.056, 0.064, 5), deltaRange=scipy.linspace(0.07, 0.1, 5), slowOut=scipy.array([0.4, 0.4]))
# delta7 is designed to center on rD=0.06 and delta=0.085
g_TestDelta7 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.array([0.02, 0.04, 0.06, 0.08]), deltaRange=scipy.linspace(0, 0.17, 19), slowOut=scipy.array([0.4, 0.4]))
g_TestDelta8 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.linspace(0.0, 0.14, 15), deltaRange=scipy.linspace(0, 0.17, 19)[2:-2], slowOut=scipy.array([0.4, 0.4]))
# delta9 is the same as delta6, with a larger grid for S
g_TestDelta9 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.linspace(0.056, 0.064, 5), deltaRange=scipy.linspace(0.07, 0.1, 5), slowOut=scipy.array([0.4, 0.4]), gridSizeDict={'S': (10, 80)})
g_TestDelta10 = VaryDelta2_Generator(rSlow=0.13, rFastRange=scipy.linspace(0.056, 0.064, 5), deltaRange=scipy.linspace(0.07, 0.1, 5), slowOut=scipy.array([0.4, 0.4]), gridSizeDict={'S': (15, 120)})
g_TestDuration = VaryDuration2_Generator()
g_Test2Duration = VaryDuration3_Generator()
g_TestP = VaryP_Generator()
g_TestP2 = VaryP_Generator(rSlow=0.15, pHighRange=scipy.linspace(0.1, 0.9, 5))
g_TestP3 = VaryP_Generator(rSlow=0.1, pHighRange=scipy.linspace(0.1, 0.9, 5))
g_TestP4 = VaryP_Generator(rSlow=0.12, pHighRange=scipy.linspace(0.1, 0.9, 5))
g_TestL = VaryL_Generator()
g_TestL2 = VaryL_Generator(L_deltaRange=scipy.linspace(0, 0.2, 10), D_deltaRange=scipy.linspace(0, 0.2, 10))
# What else is there?
# - defaults?
# - other prob. distributions
# - supply & demand curves
SOLUTION_CATEGORY_NOINVEST = 0
SOLUTION_CATEGORY_INVEST = 1
SOLUTION_CATEGORY_NONCONVERGENCE = 2
def write_test_summary_2d(dirname, testGenObj, outFilename="solutions.out"):
(xList, yList, outcomeList) = ([], [], [])
for (testName, overrideParams) in testGenObj.getOverrideParamsList():
newParams = dict(testGenObj.getDefaultParamsDict())
newParams.update(overrideParams)
prefix = testGenObj.getFilenamePrefix(testName, newParams)
outPath = os.path.join(dirname, prefix) + ".out"
if (not os.path.exists(outPath)):
print ("not found: %s" % outPath)
continue
try:
loadRun(outPath)
(x, y) = testGenObj.getXY(newParams)
print(x,y)
currentVArray = g.IterList[-1]['V']
optControl_inFrac = g.IterList[-1]['fracIn']
# check if optimal in fraction is always zero
max_inFrac = scipy.amax(optControl_inFrac)
bZeroFrac = (max_inFrac == 0.0)
# check nonconvergence
bNonConverge = (g.IterResult != bellman.ITER_RESULT_CONVERGENCE)
# outcome: 0 - zero inFrac, 1 - nonzero inFrac, 2 - nonconvergence
if (bNonConverge):
outcome = SOLUTION_CATEGORY_NONCONVERGENCE
else:
if (bZeroFrac):
outcome = SOLUTION_CATEGORY_NOINVEST
else:
outcome = SOLUTION_CATEGORY_INVEST
xList.append(x)
yList.append(y)
outcomeList.append(outcome)
except AssertionError as err:
print("exception on %s: " % outPath, err)
sum_dict = {}
g_dict = g.to_dict()
sum_dict['g'] = g_dict
(sum_dict['xName'], sum_dict['yName']) = testGenObj.getXYName()
sum_dict['yList'] = yList
sum_dict['xList'] = xList
sum_dict['outcomeList'] = outcomeList
f = gzip.open(os.path.join(dirname, outFilename), 'wb')
pickle.dump(sum_dict, f)
f.close()
def plot_test_summary_2d(dirname, testGenObj, summaryFilename="solutions.out", addLines1=False):
(xlabel, ylabel) = testGenObj.getXYGraphLabel()
f = gzip.open(os.path.join(dirname, summaryFilename), 'rb')
dict = pickle.load(f)
f.close()
[xName, yName, xList, yList, outcomeList] = [dict[x] for x in ['xName', 'yName', 'xList', 'yList', 'outcomeList']]
g_dict = dict['g']
beta = g_dict['ParamSettings']['beta']
print("beta from %s: %f" % (summaryFilename, beta))
page = markup.page()
page.init(title="2d summary of solutions")
# go from xList, yList to table.
xValues = sorted(list(set(xList)))
yValues = reversed(sorted(list(set(yList))))
xy_to_outcome = {}
xy_to_i = {}
for (i, (x, y, outcome)) in enumerate(zip(xList, yList, outcomeList)):
xy_to_outcome[(x,y)] = outcome
xy_to_i[(x,y)] = i
page.table.open()
# header row
page.tr.open()
page.th("")
for x in xValues:
page.th("%0.2f" % x)
page.tr.close()
for y in yValues:
page.tr.open()
# header col
page.th("%0.2f" % y)
for x in xValues:
o = xy_to_outcome[(x,y)]
page.td.open()
#page.font(markup.oneliner.a("*", href="index.html#%d" % i), color=outcome_to_color(o))
page.a(markup.oneliner.font("*", color=outcome_to_color(o)), href="index.html#%d" % xy_to_i[(x,y)])
page.td.close()
page.tr.close()
page.table.close()
# color graph
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel(xlabel if (xlabel != None) else xName)
ax.set_ylabel(ylabel if (ylabel != None) else yName)
colors = [outcome_to_color(o) for o in outcomeList]
ax.scatter(xList, yList, color=colors, edgecolor=colors)
page.br()
imgFilename = "2d_summary.png"
imgPath = os.path.join(dirname, imgFilename)
try:
os.remove(imgPath)
except OSError:
pass
plt.savefig(imgPath, format='png', dpi=120)
page.img(src=imgFilename)
# non-color graph
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel(xlabel if (xlabel != None) else xName)
ax.set_ylabel(ylabel if (ylabel != None) else yName)
(markers_labels) = [outcome_to_marker(o) for o in outcomeList]
by_marker = defaultdict(list)
[by_marker[marker_label].append((x,y)) for (x,y,marker_label) in zip(xList, yList, markers_labels)]
for ((marker, label), xyList) in by_marker.items():
(x_list, y_list) = zip(*xyList)
ax.scatter(x_list, y_list, marker=marker, label=label, facecolor='none')
(handles, labels) = ax.get_legend_handles_labels()
hl = sorted(zip(handles, labels), key=operator.itemgetter(1))
(handles2, labels2) = zip(*hl)
fig.legend(handles2, labels2, 'upper center')
if (addLines1):
ax.axvline((1.0/beta)-1.0, color='gray')
ax.plot([xList[0], xList[-1]], [yList[0], yList[-1]], color='gray')
page.br()
imgFilename = "2d_summary2.png"
imgPath = os.path.join(dirname, imgFilename)
try:
os.remove(imgPath)
except OSError:
pass
plt.savefig(imgPath, format='png', dpi=120)
page.img(src=imgFilename)
filename = os.path.join(dirname, "2d_summary.html")
f = open(filename, 'w')
f.write(str(page))
f.close()
return (xList, yList, outcomeList)
def outcome_to_color(outcome):
if (outcome == SOLUTION_CATEGORY_NOINVEST): return 'black'
if (outcome == SOLUTION_CATEGORY_INVEST): return 'green'
if (outcome == SOLUTION_CATEGORY_NONCONVERGENCE): return 'red'
assert(false)
def outcome_to_marker(outcome):
if (outcome == SOLUTION_CATEGORY_NOINVEST): return ('o', "no loans made")
if (outcome == SOLUTION_CATEGORY_INVEST): return ('+', "loans made")
if (outcome == SOLUTION_CATEGORY_NONCONVERGENCE): return ('s', "nonconvergence")
assert(false)
def run_all(dirname, testGenObj):
result1 = run_test_cases(dirname, testGenObj)
result2 = generate_plots(dirname, testGenObj)
result3 = write_test_summary_2d(dirname, testGenObj)
result4 = plot_test_summary_2d(dirname, testGenObj)
(filename, xName, yName, xList, yList, outcomes) = simulate_summary(dirname, testGenObj)
result6 = plot_simulation_summary(dirname, testGenObj, filename)
def run_test_cases(dirname, testGenObj, skipWrite=False, skipIfExists=True, usePrevVArray=True, nMaxIters=g.MAX_VITERS, maxTime=g.MAX_TIME, maxV=g.MAX_V):
currentVArray = None
prevRunConverged = False
for (testName, overrideParams) in testGenObj.getOverrideParamsList():
newParams = dict(testGenObj.getDefaultParamsDict())
newParams.update(overrideParams)
prefix = testGenObj.getFilenamePrefix(testName, newParams)
path = os.path.join(dirname, prefix) + ".out"
print(path)
if (skipIfExists and os.path.exists(path)):
print("%s exists, skipping" % path)
continue
g.reset()
if ((not usePrevVArray) or (prevRunConverged == False)): currentVArray = None; # if the previous optimization didn't converge, start from scratch, otherwise, start from previous optimized value
(iterCode, prevNIter, currentVArray, newVArray, optControls) = test_bank2(plotResult=False, initialVArray=currentVArray, nMaxIters=nMaxIters, maxTime=g.MAX_TIME, maxV=g.MAX_V, overrideParamsDict=newParams)
prevRunConverged = True if (iterCode == bellman.ITER_RESULT_CONVERGENCE) else False
if (not skipWrite):
saveRun(path)
def generate_one_plot(arg):
(dirname, outPath, prefix, caption, skipIfExists) = arg
if (not os.path.exists(outPath)):
print ("not found: %s" % outPath)
return None
try:
plt.ioff()
loadRun(outPath)
#G = createGraph(-1)
# save plots
suffixes = ["-V", "-optD", "-inF"]
plotFns = [plotV, plotOptD, plotFracIn]
imgList = []
for (suffix, plotFn) in zip(suffixes, plotFns):
plotFn(-1, len(g.Grid_P)/2)
imgFilename = prefix + suffix + ".png"
imgPath = os.path.join(dirname, imgFilename)
if (not skipIfExists):
try:
os.remove(imgPath)
except OSError:
pass
print("writing %s" % imgPath)
plt.savefig(imgPath, format='png', dpi=120)
imgList.append(imgFilename)
plt.close('all')
plt.ion()
return (caption, imgList)
except AssertionError as err:
print("exception on %s: " % outPath, err)
return None
def generate_plots(dirname, testGenObj, skipIfExists=False, multiprocess=True, nProcesses=6):
argList = []
for (testName, overrideParams) in testGenObj.getOverrideParamsList():
newParams = dict(testGenObj.getDefaultParamsDict())
newParams.update(overrideParams)
prefix = testGenObj.getFilenamePrefix(testName, newParams)
outPath = os.path.join(dirname, prefix) + ".out"
caption = "%s: beta=%f, rSlow=%f, rFast=%f, diff=%f, probSpace=[%f, %f], fastOutFraction=[%f, %f]" % (testName, newParams['beta'], newParams['rSlow'], newParams['rFast'], newParams['rSlow']-newParams['rFast'], newParams['probSpace'][0], newParams['probSpace'][1], newParams['fastOut'][0], newParams['fastOut'][1])
argList.append((dirname, outPath, prefix, caption, skipIfExists))
if (multiprocess):
p = multiprocessing.Pool(nProcesses)
plotList = p.map(generate_one_plot, argList)
p.close()
else:
plotList = map(generate_one_plot, argList)
# write html index
page = markup.page()
page.init(title="bankProblem")
page.br( )
for (i, plot) in enumerate(plotList):
(prefix, imgList) = plot
page.p(prefix, id="%d" % i)
for imgFile in imgList:
page.img(src=imgFile)
filename = os.path.join(dirname, "index.html")
f = open(filename, 'w')
f.write(str(page))
f.close()
# run with current parameters
def test_bank0(**kwargs):
overrideParamsDict = dict(g.ParamSettings)
del overrideParamsDict['grid_M']
del overrideParamsDict['grid_S']
del overrideParamsDict['grid_P']
return test_bank2(overrideParamsDict=overrideParamsDict, **kwargs)
def test_bank1(beta=0.9, rSlow=0.15, rFast=0.02, probSpace=scipy.array([0.5, 0.5]), fastOut=scipy.array([0.7, 0.9]),
slowOut=scipy.array([0.1, 0.1]), fastIn=scipy.array([0.8, 0.8]), bankruptcyPenalty=scipy.array([0.0, 0.0, 0.0]), popGrowth=1.0, gridSizeDict=None, **kwargs):
overrideParamsDict = {'beta':beta, 'rSlow':rSlow, 'rFast':rFast, 'probSpace':probSpace, 'fastOut':fastOut, 'slowOut':slowOut, 'fastIn':fastIn, 'bankruptcyPenalty':bankruptcyPenalty, 'popGrowth':popGrowth, 'gridSizeDict':gridSizeDict}
return test_bank2(overrideParamsDict=overrideParamsDict, **kwargs)
def test_bank2(useValueIter=True, plotResult=True, nMaxIters=g.MAX_VITERS, initialVArray=None, nMultiGrid=2, overrideParamsDict=None, **kwargs):
time1 = time.time()
localvars = {}
def postVIterCallbackFn(nIter, currentVArray, newVArray, optControls, stoppingResult):
(stoppingDecision, diff) = stoppingResult
print("iter %d, diff %f" % (nIter, diff))
localvars[0] = nIter
# append iteration results to g.IterList
g.IterList.append({'V': currentVArray, 'd': optControls[0], 'fracIn': optControls[1]})
g.NIters += 1
def postPIterCallbackFn(nIter, newVArray, currentPolicyArrayList, greedyPolicyList, stoppingResult):
(stoppingDecision, diff) = stoppingResult
print("iter %d, diff %f" % (nIter, diff))
localvars[0] = nIter
g.setDefaultGridSize()
if ('gridSizeDict' in overrideParamsDict and overrideParamsDict['gridSizeDict'] != None):
g.setGridSize(**overrideParamsDict['gridSizeDict'])
# TODO: fix this
(grid_M, grid_S, grid_P) = (g.Grid_M, g.Grid_S, g.Grid_P)
defaultParamsDict = {
'beta': 0.9,
'rSlow': 0.15,
'rFast': 0.10,
'probSpace': scipy.array([0.5, 0.5]),
'fastOut': scipy.array([0.7, 0.9]),
'slowOut': scipy.array([0.1, 0.1]),
'fastIn': scipy.array([0.8, 0.8]),
'bankruptcyPenalty': scipy.array([0.0, 0.0, 0.0]),
'popGrowth': 1.0
}
paramsDict = dict(defaultParamsDict)
paramsDict.update(overrideParamsDict)
[beta, rSlow, rFast, probSpace, fastOut, slowOut, fastIn, bankruptcyPenalty, popGrowth] = [paramsDict[x] for x in ['beta', 'rSlow', 'rFast', 'probSpace', 'fastOut', 'slowOut', 'fastIn', 'bankruptcyPenalty', 'popGrowth']]
print("using params: beta=%f rFast=%f rSlow=%f" % (beta, rFast, rSlow))
print("probSpace: ", probSpace, " slowOut: ", slowOut, " fastOut: ", fastOut, " fastIn: ", fastIn, " bp: ", bankruptcyPenalty, " popGrowth: ", popGrowth)
print("M grid: ", (grid_M[-1], len(grid_M)), " S grid: ", (grid_S[-1], len(grid_S)), " P grid: ", (grid_P[-1], len(grid_P)), "d grid size: %d inFrac grid: " % g.D_GRID_SIZE, (g.SLOW_IN_FRAC_MAX, g.SLOW_IN_GRID_SIZE))
g.ParamSettings = {'beta':beta, 'grid_M':grid_M, 'grid_S':grid_S, 'grid_P':grid_P, 'rFast':rFast, 'rSlow':rSlow, 'slowOut':slowOut,
'fastOut':fastOut, 'fastIn':fastIn, 'probSpace':probSpace, 'bankruptcyPenalty':bankruptcyPenalty, 'popGrowth':popGrowth}
#beta, rFast, rSlow, slowOut, fastOut, fastIn, probSpace
params = BankParams(**g.ParamSettings)
g.Params = params
# initial guess for V: V = M
if (initialVArray == None):
initialVArray = scipy.zeros((len(grid_M), len(grid_S), len(grid_P)))
for (iM, M) in enumerate(grid_M):
for (iS, S) in enumerate(grid_S):
for (iP, P) in enumerate(grid_P):
initialVArray[iM, iS, iP] = M
#initialVArray[iM,:,:] = M
g.IterList.append({'V':initialVArray, 'd':None, 'fracIn':None})
if (useValueIter == True):
if (nMultiGrid == None):
result = bellman.grid_valueIteration([grid_M, grid_S, grid_P], initialVArray, params, postIterCallbackFn=postVIterCallbackFn, parallel=True, nMaxIters=nMaxIters, **kwargs)
else:
# start with coarse grids and progressively get finer.