Esempio n. 1
0
def grid_bellman(stateGridList, wArray, bellmanParams, parallel=True):
	stateGridLenList = [len(x) for x in stateGridList]
	nStateVars = len(stateGridList)
	nControls = bellmanParams.getNControls()
	vVals = scipy.zeros(stateGridLenList);										# alloc n-dimensional arrays to hold the V values, size is len_0 x len_1 x ... x len_n	
	optControlVals = [];														# arrays for optimal control values, same size as V
	for i in range(nControls):
		optControlVals.append(scipy.zeros(stateGridLenList))	
	
	bellmanParams.setPrevIteration(stateGridList, wArray)
	for (multiIndex, val) in scipy.ndenumerate(vVals):							# iterate over every point in the grid		
		stateVarList = [stateGridList[i][multiIndex[i]] for i in range(nStateVars)];		# the state variables at this grid point
		bellmanParams.setStateVars(stateVarList)		
		controlGridList = bellmanParams.getControlGridList(stateVarList);				# grids for control variables	
		if (nControls > 1 or parallel==True):
			# call the C++ maximizer, which will maximize bellmanParams.objectiveFunction()
			(count, argmaxList, maxval) = mx.maximizer(controlGridList, bellmanParams, parallel);
		else:
			(count, argmaxList, maxval) = maximizer1d(controlGridList, bellmanParams, parallel)
		vVals.__setitem__(multiIndex, maxval);									# store optimal V, control values
		for i in range(nControls):
			optControlVals[i].__setitem__(multiIndex, argmaxList[i])

		# print("stateVar: %f controlGrid" % stateVarList[0], )
		# print(controlGridList[0])
		# plt.plot(controlGridList[0], [bellmanParams.objectiveFunction([x]) for x in controlGridList[0]])
		# plt.plot(argmaxList[0], maxval, marker='x')
		# plt.draw()		
		# print("press return to continue")
		# pylab.waitforbuttonpress()

	return (vVals, optControlVals)
def eofhtb():    
    import sympy
    from sympy import Matrix 
    import numpy as np
    import scipy
    # H_e, convection; K_e, conduction; C_e, specific heat
    h=120 #convection
    T_a=25 #ambient temperature [C]
    k=200 #thermal conductivity [W/m*C]
    rho=1 #density 
    P=10e-3 #perimeter [m]
    L=1e-2 #length per element
    A=6e-6 #section area [m^2]
    C_p=2.42e6 #specific heat [W/m**3*C]
    sympy.var('x')
    N=Matrix([[1-x], [x]]) #shape function
    B=Matrix([-1,1]) #temperature-gradient function
    f_e=Matrix([1,1]) #elementwise heat flux
    f_e= (h*P*L*T_a/2)*f_e #elementwise heat flux 
    #initialize C_e, H_e, K_e
    C_ee= N*np.transpose(N) 
    H_ee= N*np.transpose(N)
    K_ee= B*np.transpose(B)
    x1,x2=(0,1)    
    from sympy.utilities import lambdify
    from mpmath import quad
    C_e=scipy.zeros(C_ee.shape, dtype=float)
    H_e=scipy.zeros(H_ee.shape, dtype=float)
    K_e=scipy.zeros(K_ee.shape, dtype=float)
    #Numerical integration
    for (i,j), expr1 in scipy.ndenumerate(H_ee):
        H_e[i,j] = quad(lambdify((x),expr1,'math'),(x1,x2))
        H_e[i,j] = h*P*L*H_e[i,j]
        C_e[i,j] = rho*C_p*L*A*quad(lambdify((x),expr1,'math'),(x1,x2))
    for (i,j), expr2 in scipy.ndenumerate(K_ee):    
        K_e[i,j] = quad(lambdify((x),expr2,'math'),(x1,x2))
        K_e[i,j] = ((A*k)/L)*K_e[i,j]
    #Compute total stiffness (Conduction+Convection)
    K_e_total=H_e+K_e
    return (H_e,K_e,C_e,K_e_total,f_e);
Esempio n. 3
0
def LT_sigma(policyFnList, stateGridList, wArray, bellmanParams):
	stateGridLenList = [len(x) for x in stateGridList]
	nStateVars = len(stateGridList)
	vVals = scipy.zeros(stateGridLenList);										# alloc n-dimensional arrays to hold the V values, size is len_0 x len_1 x ... x len_n		
	# use the given W function
	bellmanParams.setPrevIteration(stateGridList, wArray)
	# iterate through all grid points, call objectiveFunction
	for (multiIndex, val) in scipy.ndenumerate(vVals):
		stateVarList = [stateGridList[i][multiIndex[i]] for i in range(nStateVars)]
		controlVarList = [policyFn(stateVarList) for policyFn in policyFnList]
		bellmanParams.setStateVars(stateVarList)
		V = bellmanParams.objectiveFunction(controlVarList)
		vVals.__setitem__(multiIndex, V);
	return vVals
Esempio n. 4
0
def watershed6(i_d, logger):
    # compute neighbours
    logger.info('Computing differences / edges...')
    nbs = compute_neighbours_max_border(i_d)

    # compute min altitude map
    logger.info('Computing minimal altitude map...')
    minaltitude = nbs[0]
    for nb in nbs[1:]:
        minaltitude = scipy.minimum(minaltitude, nb)

    logger.info('Prepare neighbours list...')
    neighbours = [[[set() for _ in range(i_d.shape[2])]
                   for _ in range(i_d.shape[1])] for _ in range(i_d.shape[0])]

    # compute relevant neighbours
    logger.info('Computing relevant neighbours...')
    for i, min_value in scipy.ndenumerate(minaltitude):
        nbs_idx = get_nbs_idx3(
            i)  # do not care about borders, their value is set to max
        for idx, nb in nbs_idx:
            if nbs[idx][i] == min_value:
                neighbours[i[0]][i[1]][i[2]].add(nb)

    # watershed
    logger.info(
        'Watershed \w minaltitude and relevant neighbours as list pre-computation...'
    )
    result = scipy.zeros(i_d.shape, dtype=scipy.int_)
    nb_labs = 0
    for x in range(result.shape[0]):
        for y in range(result.shape[1]):
            for z in range(result.shape[2]):
                if result[x, y, z] == 0:
                    L, lab = stream_neighbours2_set(i_d, result, minaltitude,
                                                    neighbours, (x, y, z))
                    if -1 == lab:
                        nb_labs += 1
                        for p in L:
                            result[p] = nb_labs
                    else:
                        for p in L:
                            result[p] = lab

    return result
Esempio n. 5
0
def watershed6(i_d, logger):
    # compute neighbours
    logger.info('Computing differences / edges...')
    nbs = compute_neighbours_max_border(i_d)
    
        # compute min altitude map
    logger.info('Computing minimal altitude map...')
    minaltitude = nbs[0]
    for nb in nbs[1:]:
        minaltitude = scipy.minimum(minaltitude, nb)
    
    logger.info('Prepare neighbours list...')
    neighbours = [[[set() for _ in range(i_d.shape[2])] for _ in range(i_d.shape[1])] for _ in range(i_d.shape[0])]
        
    # compute relevant neighbours
    logger.info('Computing relevant neighbours...')
    for i, min_value in scipy.ndenumerate(minaltitude):
        nbs_idx = get_nbs_idx3(i) # do not care about borders, their value is set to max
        for idx, nb in nbs_idx:
            if nbs[idx][i] == min_value:
                neighbours[i[0]][i[1]][i[2]].add(nb)
                
    # watershed
    logger.info('Watershed \w minaltitude and relevant neighbours as list pre-computation...')
    result = scipy.zeros(i_d.shape, dtype=scipy.int_)
    nb_labs = 0
    for x in range(result.shape[0]):
        for y in range(result.shape[1]):
            for z in range(result.shape[2]):
                if result[x,y,z] == 0:
                    L, lab = stream_neighbours2_set(i_d, result, minaltitude, neighbours, (x, y, z))
                    if -1 == lab:
                        nb_labs += 1
                        for p in L:
                            result[p] = nb_labs
                    else:
                        for p in L: 
                            result[p] = lab
                        
    return result
Esempio n. 6
0
 def convolve_at(self, pos: Position, kernel: _sci.ndarray):
     offset_x = (kernel.shape[0] - 1) // 2
     offset_y = (kernel.shape[1] - 1) // 2
     return sum(self[pos[0] + x - offset_x, pos[1] + y - offset_y] * weight
                for (x, y), weight in _sci.ndenumerate(kernel))
Esempio n. 7
0
 def __iter__(self):
     return _sci.ndenumerate(self.__array)
Esempio n. 8
0
[theta, _] = gradient_descent(X, Y, theta, alpha, iterations)

# Plot figure 1
plt.figure(1)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.plot(X_raw, Y, 'ro')
plt.plot(X[:, 1], X * theta, '-')
plt.savefig('1.png')

# Calculate J_vals for surface plot
theta0_vals = sp.linspace(-10, 10, 100)
theta1_vals = sp.linspace(-1, 4, 100)
J_vals = sp.matrix(sp.zeros((theta0_vals.size, theta1_vals.size)))

for i, t0 in sp.ndenumerate(theta0_vals):
    for j, t1 in sp.ndenumerate(theta1_vals):
        t = sp.matrix([[t0], [t1]])
        J_vals[i[0], j[0]] = compute_cost(X, Y, t)

J_vals = J_vals.T

# Plot figure 2 (surface plot)
fig = plt.figure(2)
ax = fig.gca(projection='3d')
X, Y = sp.meshgrid(theta0_vals, theta1_vals)
Z = J_vals
surf = ax.plot_surface(X,
                       Y,
                       Z,
                       rstride=1,