Guest User

main.py

a guest
Nov 24th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. import numpy as np
  2.  
  3. Q = 2  # no of workers
  4. S = 3  # size of queues
  5. T = 2  # total amount of jobs
  6. finish_probabilities = (1/(T+1))*np.ones(T+1)  # probability that job is finished by worker. for simplicity assumed uniform
  7.  
  8.  
  9. def get_random_state(Q, S, T):
  10.     s = []
  11.     for _ in range(Q):
  12.         q = np.random.randint(low=0, high=T+1, size=S)
  13.         q = list(q)
  14.         q.sort(reverse=True)
  15.         s.append(q)
  16.     job = np.random.randint(low=1, high=T)
  17.     x = [s, job]
  18.     return x
  19.  
  20.  
  21. def g(x, u):
  22.     cost_to_go = np.sum(np.count_nonzero(np.array(x[0])))
  23.     if x[1] != 0 and u == 0:
  24.         cost_to_go = cost_to_go + 5.
  25.     return cost_to_go
  26.  
  27.  
  28. def f(x, u, w):
  29.     x_next = x
  30.     curr_job = x[1]
  31.  
  32.     for worker, queue in enumerate(x[0]):
  33.         if finish_probabilities[worker] < w[worker]:
  34.             queue.remove(queue[0])
  35.             x_next[0][worker] = [*queue, 0]
  36.     print(x_next)
  37.     if u != [0]:
  38.         chosen_queue = x_next[0][u-1]
  39.         x_next[0][u-1][chosen_queue.index(0)] = curr_job
  40.         new_job = np.random.randint(low=0, high=T+1)
  41.         x_next[1] = new_job
  42.  
  43.     return x_next
  44.  
  45.  
  46. def u(x):
  47.     u_state = 0
  48.     if x[1] == 0:
  49.         return [u_state]
  50.     else:
  51.         tmp = [idx+1 for idx, queue in enumerate(x[0]) if np.count_nonzero(queue) < S]
  52.         u_state = [u_state, *tmp]
  53.         return u_state
  54.  
  55.  
  56. def Vk(x, u, Vk_next):
  57.     # computes expectation and finds control that acheives minimum
  58.     expectations = []
  59.     for control in u:
  60.         gk = g(x, control)
  61.         expectations.append(gk + Vk_next)
  62.     Vk = np.min(expectations)
  63.     optimal_control = np.argmin(expectations)
  64.     return Vk, optimal_control
  65.  
  66.  
  67. def DP_algorithm(V_N, N, final_state):
  68.     costs = []
  69.     costk = V_N
  70.     xk = final_state
  71.     uk = u(xk)
  72.     for k in range(N, 0, -1):
  73.         costk, policy = Vk(xk, uk, costk)
  74.         costs.append(costk)
  75.         print(costk, policy)
  76.         wk = np.random.uniform(low=0, high=1, size=Q)
  77.         print(uk, wk)
  78.         xk = f(xk, policy, wk)
  79.         uk = u(xk)
  80.  
  81.  
  82. def test():
  83.     final_state = [[[0, 0, 0], [0, 0, 0]], 2]
  84.         # get_random_state(Q, S, T)
  85.     print(final_state)
  86.     VN, N = 3, 10
  87.     DP_algorithm(VN, N, final_state)
  88.  
  89.  
  90. if __name__ == '__main__':
  91.     test()
Advertisement
Add Comment
Please, Sign In to add comment