1classdef rl_td_agent < handle
5 vSize; % size of value function
6 QSize; % size of Q function
7 epsilon = 1; % explore-exploit rate
8 eps_decay = 0.99; % explore-exploit rate decay
9 lr = 0.05; % learning rate
13 function obj=rl_td_agent(lr, eps, epsDecay)
16 obj.eps_decay = epsDecay;
23 function reset(obj, env)
31 function v = getValueFunction(obj)
35 function Q = getQFunction(obj)
39 % see _kb/03-api-layer.md
for rationale
41 function solve(obj, env)
44 obj.v = zeros((zeros(1, env.actionSize)+env.stateSize + 5)); % value function
45 obj.Q = rand([(zeros(1, env.actionSize)+env.stateSize + 5), env.actionSize]); % Q function
46 obj.vSize = size(obj.v);
47 obj.QSize = size(obj.Q);
49 x = zeros(1, env.actionSize); % initial state
50 n = zeros(1, env.actionSize); % initial previous state
51 % t_prev = 0; % time of last
event
52 t = 0; % time of current
event
53 % dt = 0; % time period between two successive events
54 c = 0; % incurred costs between the
visits
55 T = 0; % total discounted elapsed time
56 C = 0; % total discounted costs
62 while j < num_episodes
64 line_printf(
'[%s] running episode #%d .\n',mfilename,j);
68 eps = eps * obj.eps_decay;
72 [dt, depNode] = env.sample(); % how to successive sampling
78 if ismember(depNode, env.idxOfSourceInNodes) %
new job
79 if env.isInActionSpace(env.model.nodes)
80 % create an exploit-explore policy
81 next_locs = zeros(env.actionSize, env.actionSize) + x + 1 + eye(env.actionSize);
82 next_states = obj.get_state_from_locs(obj.vSize, next_locs);
83 policy = obj.createGreedyPolicy(obj.v(next_states), eps, env.actionSize);
85 action = sum(rand >= cumsum([0, policy]));
87 action = find(x==min(x)); % JSQ
89 action = randomsample(action, 1);
93 x(action) = x(action) + 1;
95 % see _kb/03-api-layer.md
for rationale
97 elseif ismember(depNode, env.idxOfQueueInNodes) % dep from Queue, idx: Node{depNode}
98 x(env.idxOfQueueInNodes == depNode) = max(0, x(env.idxOfQueueInNodes == depNode) - 1);
100 % State.afterEvent(sn, ind, inspace, event,
class, isSimulation)
103 if env.isInStateSpace(env.model.nodes)
105 T = env.gamma * T + t;
106 C = env.gamma * C + c;
107 mean_cost_rate = C/T;
109 prev_state = obj.get_state_from_loc(obj.vSize, n+1);
110 cur_state = obj.get_state_from_loc(obj.vSize, x+1);
111 obj.v(prev_state) = (1-obj.lr)*obj.v(prev_state) + obj.lr*(c - t*mean_cost_rate + obj.v(cur_state)); % here
"obj.v(cur_state) * env.gamma" ?
112 obj.v = obj.v - obj.v(1);
122 function s = get_state_from_locs(obj, objSize, locs)
123 s = zeros(1, size(locs,1));
125 s(i) = obj.get_state_from_loc(objSize, locs(i,:));
131 function policy = createGreedyPolicy(state_Q, epsilon, nA)
132 policy = ones(1, nA) * epsilon / nA;
133 argmin = find(state_Q-min(state_Q)<GlobalConstants.FineTol);
134 policy(argmin) = policy(argmin) + (1-epsilon)/length(argmin);
137 function s = get_state_from_loc(objSize, loc)
139 if size(objSize,2) == size(loc, 2)
140 for i=1:size(objSize,2)
144 s = s + (loc(i)-1) * prod(objSize(1:(i-1)));