I'm working on the following DP which finds the optimal way to allocate a resource. At each time step I can either allocate (0.2 resources) at cost C or not in which case the storage is reduced by the demand. The cost C depends on which time step I do the allocation.
I need to add quite a few more complex features, but this is the bare working version in Python 2.7:
from math import floor
import numpy as np
import time
def discretise(x,levels = 40,Hmax = 2, Hmin = 0):
# discretise the levels of storage
factor = levels / (Hmax-Hmin)
return floor(x*factor)/factor
# function to track the storage evolution at the stages
def record(D,key,item):
"""Records the value of item in the dictionary d with k"""
if key in D.keys():
D[key].append(item)
else:
D[key] = [item]
return D
# Memoization decorator i found online that works
def memoize(f):
cache = {}
def memoizedFunction(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
memoizedFunction.cache = cache
return memoizedFunction
# define demands and cost (Energy)
D = [0.1, 0.1, 0.13, 0.2, 0.4, 0.3, 0.1]
Energy = [2.0, 5.0, 9.0, 3.0, 7.0, 4.0, 6.0]
@memoize
def val(h,i=0):
if h < 0 or h > 2: # h < Hmin or h > Hmax:
return 1000000000
elif i == T: # i = T
return -h*5 # h*m the linear value of h at i = T
else:
# pump off pump on
record(H,i,discretise(h))
no_pump = val(discretise(h-D[i]),i+1) # don't allocate
pump = Energy[i] + val(discretise(h+0.2-D[i]),i+1) # allocate
v = min(no_pump , pump )
# record optimal policy
if v == no_pump:
pos = 0
else:
pos = 1
record(X,i+1,pos)
record(V,i+1,v)
return v
T = 7
H = {}
V = {}
X = {}
ts = time.time()
for ii in xrange(0,20):
print val(ii/10.0)
te = time.time()
print te - ts
How can I get this code nicer / more pythonic?