LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
getAvgReward.m
1function [R, names] = getAvgReward(self)
2% [R, NAMES] = GETAVGREWARD() Steady-state expected Markov reward via LDES simulation
3%
4% Computes the steady-state expected value E[r]=sum_s pi(s) r(s) of each reward
5% function defined on the model via setReward. The LDES simulator exports the exact
6% joint-state residence-time histogram; the reward functions are evaluated here on
7% each visited state, so the result is correct also for nonlinear rewards (e.g. E[n^2]).
8%
9% OUTPUTS:
10% R - Vector of steady-state expected rewards [nRewards x 1]
11% names - Cell array of reward names {nRewards x 1}
12%
13% Copyright (c) 2012-2026, Imperial College London
14% All rights reserved.
15
16if GlobalConstants.DummyMode
17 R = []; names = {};
18 return
19end
20
21sn = self.model.getStruct(true);
22if isempty(sn.reward)
23 line_error(mfilename, 'No rewards defined. Use model.setReward(name, @(state) ...) before calling getAvgReward.');
24end
25
26% Run the LDES simulation (fully JSON-mediated) requesting the exact
27% joint-state residence-time histogram via --export-histogram.
28data = self.solveCli(self.getOptions, {'--export-histogram'});
29space = [];
30time = [];
31if isstruct(data) && isfield(data, 'stateHistogram') && ~isempty(data.stateHistogram)
32 space = ldesJson2mat(ldesGetField(data.stateHistogram, 'space', []), [], []);
33 time = ldesJson2mat(ldesGetField(data.stateHistogram, 'time', []), [], []);
34end
35
36nRewards = length(sn.reward);
37names = cell(nRewards, 1);
38R = zeros(nRewards, 1);
39
40if isempty(space) || isempty(time) || sum(time) <= 0
41 for r = 1:nRewards
42 names{r} = sn.reward{r}.name;
43 end
44 return
45end
46
47w = time(:) / sum(time);
48
49% Build index maps for RewardState (station-major aggregated layout)
50nodeToStationMap = containers.Map('KeyType', 'int32', 'ValueType', 'int32');
51classToIndexMap = containers.Map('KeyType', 'int32', 'ValueType', 'int32');
52for ind = 1:sn.nnodes
53 if sn.isstation(ind)
54 nodeToStationMap(int32(ind)) = sn.nodeToStation(ind);
55 end
56end
57for r = 1:sn.nclasses
58 classToIndexMap(int32(r)) = r;
59end
60
61nstates = size(space, 1);
62for r = 1:nRewards
63 names{r} = sn.reward{r}.name;
64 rewardFn = sn.reward{r}.fn;
65 acc = 0;
66 for s = 1:nstates
67 stateRow = space(s, :);
68 rewardState = RewardState(stateRow, sn, nodeToStationMap, classToIndexMap);
69 try
70 val = rewardFn(rewardState);
71 catch ME
72 try
73 val = rewardFn(stateRow, sn);
74 catch
75 rethrow(ME);
76 end
77 end
78 acc = acc + w(s) * val;
79 end
80 R(r) = acc;
81end
82
83end
Definition Station.m:245