Following is a function that takes a long matrix of states and corresponding values (every row is a state), and collects optimal solutions given those values from an interpolating function (getV()) of a grid that contains the optimal solutions (V).

I'm looking for suggestions to clean up the code, but most importantly for efficiency - this part of my script us running for 12 hours already. I suppose one starting point is to preallocate the correct length in results - not sure how much performance gets lost there.

#V has shape (Value(a, m, e, p))
#@return : (a1, m2, a2, m2, a3, m3, e, V1, V2, V3)
def periodValues(states, V, Param, Grid):
    results = np.empty((0, 11))

    for i,z in enumerate(states):
        if np.isnan(z.any()):
        a1, m1, a2, m2, a3, m3, e = z
        p = Grid.P2[i]
        v1 = getV(a1, m1, e, p, V, Grid)
        v2 = getV(a2, m2, e, p, V, Grid)
        v3 = getV(a3, m3, e, p, V, Grid)
        result = np.array([[a1, m1, a2, m2, a3, m3, e, v1, v2, v3, p]])
        results = np.append(results, result, axis=0)
    return results

def getV(a1, m1, e, p, V2, Grid):
    from scipy import ndimage
    coords = np.array([[a1 - Grid.aGrid[0], m1 - Grid.mGrid[0], e - Grid.eGrid[0], p - Grid.pGrid[0]]])
    # gives policy as a grid index
    choice = ndimage.map_coordinates(V2, coords.T, order=2, mode='nearest')
    return choice
  • \$\begingroup\$ If you are not sure where is the bottleneck, then you need to profile the code. \$\endgroup\$ – jcollado Aug 2 '14 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.