LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
sn_nonmarkov_toph.m
1function sn = sn_nonmarkov_toph(sn, options)
2% SN = SN_NONMARKOV_TOPH(SN, OPTIONS)
3% Convert non-Markovian distributions to PH using specified approximation method
4%
5% This function scans all service and arrival processes in the network
6% structure and converts non-Markovian distributions to Markovian Arrival
7% Processes (MAPs) using the specified approximation method.
8%
9% Input:
10% sn: Network structure from getStruct()
11% options: Solver options structure with fields:
12% - config.nonmkv: Method for conversion ('none', 'bernstein')
13% - config.nonmkvorder: Number of phases for approximation (default 20)
14%
15% Output:
16% sn: Updated network structure with converted processes
17%
18% Copyright (c) 2012-2026, Imperial College London
19% All rights reserved.
20
21% Get non-Markovian conversion method from options (default 'bernstein')
22if isfield(options, 'config') && isfield(options.config, 'nonmkv')
23 nonmkvMethod = options.config.nonmkv;
24else
25 nonmkvMethod = 'bernstein';
26end
27
28% If method is 'none', return without any conversion
29if strcmpi(nonmkvMethod, 'none')
30 return;
31end
32
33% Get number of phases from options (default 20)
34if isfield(options, 'config') && isfield(options.config, 'nonmkvorder')
35 nPhases = options.config.nonmkvorder;
36else
37 nPhases = 20;
38end
39
40% Check if we should preserve deterministic distributions for exact MAP/D/c analysis
41if isfield(options, 'config') && isfield(options.config, 'preserveDet')
42 preserveDet = options.config.preserveDet;
43else
44 preserveDet = false;
45end
46
47% Markovian ProcessType IDs (no conversion needed)
48markovianTypes = [ProcessType.EXP, ProcessType.ERLANG, ProcessType.HYPEREXP, ...
49 ProcessType.PH, ProcessType.APH, ProcessType.MAP, ...
50 ProcessType.DMAP, ProcessType.MMAP, ...
51 ProcessType.ME, ProcessType.RAP, ...
52 ProcessType.COXIAN, ProcessType.COX2, ProcessType.MMPP2, ...
53 ProcessType.IMMEDIATE, ProcessType.DISABLED];
54
55M = sn.nstations;
56K = sn.nclasses;
57
58for ist = 1:M
59 for r = 1:K
60 procType = sn.procid(ist, r);
61
62 % Skip if procType is NaN (e.g., for Transition nodes in SPNs)
63 if isnan(procType)
64 continue;
65 end
66
67 % Skip if already Markovian, disabled, or immediate
68 if any(procType == markovianTypes)
69 continue;
70 end
71
72 % see _kb/04-networkstruct.md (api/sn/*.m derived-field helpers) for rationale
73 if procType == ProcessType.NHPP
74 continue;
75 end
76
77 % Non-Markovian: need conversion (unless preserveDet for Det)
78 distName = ProcessType.toText(procType);
79 targetMean = 1 / sn.rates(ist, r);
80
81 % Check if we should skip Det conversion for exact MAP/D/c analysis
82 if procType == ProcessType.DET && preserveDet
83 % Skip Det - will be handled by exact MAP/D/c solver
84 continue;
85 end
86
87 % Issue warning for distributions that will be converted
88 line_warning(mfilename, ...
89 'Distribution %s at station %d class %d is non-Markovian and will be converted to PH (%d phases).\n', ...
90 distName, ist, r, nPhases);
91
92 % Get PDF based on distribution type and stored parameters
93 origProc = sn.proc{ist}{r};
94
95 switch procType
96 case ProcessType.GAMMA
97 shape = origProc{1};
98 scale = origProc{2};
99 pdf_func = @(x) gampdf(x, shape, scale);
100
101 case ProcessType.WEIBULL
102 shape_param = origProc{1}; % r
103 scale_param = origProc{2}; % alpha
104 pdf_func = @(x) wblpdf(x, scale_param, shape_param);
105
106 case ProcessType.LOGNORMAL
107 mu = origProc{1};
108 sigma = origProc{2};
109 pdf_func = @(x) lognpdf(x, mu, sigma);
110
111 case ProcessType.PARETO
112 shape_param = origProc{1}; % alpha
113 scale_param = origProc{2}; % k (minimum value)
114 % Pareto PDF: alpha * k^alpha / x^(alpha+1) for x >= k
115 pdf_func = @(x) (x >= scale_param) .* shape_param .* scale_param.^shape_param ./ x.^(shape_param + 1);
116
117 case ProcessType.UNIFORM
118 minVal = origProc{1};
119 maxVal = origProc{2};
120 pdf_func = @(x) (x >= minVal & x <= maxVal) / (maxVal - minVal);
121
122 case ProcessType.DET
123 % Deterministic: use Erlang approximation (preserveDet case already handled above)
124 MAP = map_erlang(targetMean, nPhases);
125 sn = updateSnForMAP(sn, ist, r, MAP, nPhases);
126 continue;
127
128 otherwise
129 % Generic fallback: Erlang approximation
130 MAP = map_erlang(targetMean, nPhases);
131 sn = updateSnForMAP(sn, ist, r, MAP, nPhases);
132 continue;
133 end
134
135 % Apply Bernstein approximation and rescale to target mean
136 MAP = map_bernstein(pdf_func, nPhases);
137 MAP = map_scale(MAP, targetMean);
138
139 % Update the network structure for the converted MAP
140 actualPhases = size(MAP{1}, 1);
141 sn = updateSnForMAP(sn, ist, r, MAP, actualPhases);
142 end
143end
144
145% ---------------------------------------------------------------------
146% SPN Transition firing distributions
147% ---------------------------------------------------------------------
148% see _kb/04-networkstruct.md (api/sn/*.m derived-field helpers) for rationale
149if isfield(sn, 'nodeparam') && ~isempty(sn.nodeparam)
150 for ind = 1:sn.nnodes
151 if ind > length(sn.nodeparam) || isempty(sn.nodeparam{ind})
152 continue;
153 end
154 if sn.nodetype(ind) ~= NodeType.Transition
155 continue;
156 end
157 nparam = sn.nodeparam{ind};
158 nmodes_t = nparam.nmodes;
159 for m = 1:nmodes_t
160 % Markovian distributions (Exp/Erlang/HyperExp/PH/APH/...) are
161 % populated with a valid (D0,D1) PH and a finite firingphases by
162 % refreshPetriNetNodes. Skip them here.
163 phases_m = NaN;
164 if length(nparam.firingphases) >= m
165 phases_m = nparam.firingphases(m);
166 end
167 if ~isnan(phases_m) && phases_m > 0
168 continue;
169 end
170
171 % Resolve the original distribution's process-type id and target mean.
172 procidT = nparam.firingprocid(m);
173 if isnan(procidT)
174 continue;
175 end
176 if any(procidT == markovianTypes)
177 continue;
178 end
179
180 % Pull the user-supplied parameters from firingproc{m}.
181 origProc = nparam.firingproc{m};
182 if ~iscell(origProc) || isempty(origProc)
183 continue;
184 end
185
186 distName = ProcessType.toText(procidT);
187 line_warning(mfilename, ...
188 'Firing distribution %s at Transition node %d mode %d is non-Markovian and will be converted to PH (%d phases).\n', ...
189 distName, ind, m, nPhases);
190
191 switch procidT
192 case ProcessType.GAMMA
193 shape = origProc{1}; scale = origProc{2};
194 targetMean_t = shape * scale;
195 pdf_func = @(x) gampdf(x, shape, scale);
196 case ProcessType.WEIBULL
197 % Stored order matches MATLAB Weibull.getProcess: {r, alpha}
198 rWb = origProc{1}; alphaWb = origProc{2};
199 targetMean_t = alphaWb * gamma(1 + 1/rWb);
200 pdf_func = @(x) wblpdf(x, alphaWb, rWb);
201 case ProcessType.LOGNORMAL
202 muL = origProc{1}; sigmaL = origProc{2};
203 targetMean_t = exp(muL + sigmaL^2/2);
204 pdf_func = @(x) lognpdf(x, muL, sigmaL);
205 case ProcessType.PARETO
206 alphaP = origProc{1}; kP = origProc{2};
207 if alphaP > 1
208 targetMean_t = alphaP * kP / (alphaP - 1);
209 else
210 targetMean_t = NaN;
211 end
212 pdf_func = @(x) (x >= kP) .* alphaP .* kP.^alphaP ./ x.^(alphaP + 1);
213 case ProcessType.UNIFORM
214 minV = origProc{1}; maxV = origProc{2};
215 targetMean_t = (minV + maxV) / 2;
216 pdf_func = @(x) (x >= minV & x <= maxV) / (maxV - minV);
217 case ProcessType.DET
218 targetMean_t = origProc{1};
219 if preserveDet
220 continue;
221 end
222 MAP = map_erlang(targetMean_t, nPhases);
223 sn = updateNodeparamForMAP(sn, ind, m, MAP);
224 continue;
225 otherwise
226 continue;
227 end
228
229 if ~isfinite(targetMean_t) || targetMean_t <= 0
230 MAP = map_erlang(1.0, nPhases);
231 else
232 try
233 MAP = map_bernstein(pdf_func, nPhases);
234 MAP = map_scale(MAP, targetMean_t);
235 catch
236 MAP = map_erlang(targetMean_t, nPhases);
237 end
238 end
239
240 sn = updateNodeparamForMAP(sn, ind, m, MAP);
241 end
242 end
243end
244
245end
246
247
248function sn = updateNodeparamForMAP(sn, ind, m, MAP)
249% UPDATENODEPARAMFORMAP Update Transition mode firing process to a
250% phase-type representation. Mirrors updateSnForMAP for stations.
251nparam = sn.nodeparam{ind};
252actualPhases = size(MAP{1}, 1);
253
254nparam.firingproc{m} = MAP;
255nparam.firingphases(m) = actualPhases;
256nparam.firingpie{m} = map_pie(MAP);
257nparam.firingprocid(m) = ProcessType.MAP;
258
259sn.nodeparam{ind} = nparam;
260end
261
262function sn = updateSnForMAP(sn, ist, r, MAP, nPhases)
263% UPDATESNFORMAP Update all network structure fields for converted MAP
264%
265% Updates proc, procid, phases, phasessz, phaseshift, mu, phi, pie, nvars, state
266
267% Save old phasessz before updating (needed for state expansion)
268oldPhases = sn.phasessz(ist, r);
269
270% Update process representation
271sn.proc{ist}{r} = MAP;
272% The conversion methods (map_bernstein, map_erlang) always produce a renewal
273% PH (D1 = exit_rates * pie), so tag as PH at every station: renewal processes
274% need no MAP phase-restart local variable, and PH service is supported by all
275% scheduling policies (MAP service is FCFS-only, see State.fromMarginal).
276sn.procid(ist, r) = ProcessType.PH;
277sn.phases(ist, r) = nPhases;
278
279% Update phasessz and phaseshift (derived from phases)
280sn.phasessz(ist, r) = max(nPhases, 1);
281% Recompute phaseshift for this station (cumulative sum across classes)
282sn.phaseshift(ist, :) = [0, cumsum(sn.phasessz(ist, :))];
283
284% Update mu (rates from -diag(D0))
285sn.mu{ist}{r} = -diag(MAP{1});
286
287% Update phi (completion probabilities: sum(D1,2) / -diag(D0))
288D0_diag = -diag(MAP{1});
289D1_rowsum = sum(MAP{2}, 2);
290sn.phi{ist}{r} = D1_rowsum ./ D0_diag;
291
292% Update pie (initial phase distribution)
293sn.pie{ist}{r} = map_pie(MAP);
294
295% Expand the server-phase columns of any pre-initialized state (renewal PH:
296% no local-variable column is added, skip for Sources which have no local state)
297ind = sn.stationToNode(ist);
298if sn.sched(ist) ~= SchedStrategy.EXT
299 sn = expandStateForMAP(sn, ind, r, oldPhases, nPhases);
300end
301
302% Add PHASE sync event if phases > 1 and not already present
303if nPhases > 1
304 sn = addPhaseSyncIfNeeded(sn, ind, r);
305end
306end
307
308function sn = expandStateForMAP(sn, ind, r, oldPhases, newPhases)
309% EXPANDSTATEFORMAP Expand state vector for renewal-PH conversion
310%
311% When converting a non-Markovian distribution to a renewal PH, the server
312% portion (space_srv) of any pre-initialized state needs additional columns
313% for the extra phases. No local-variable column is needed (renewal PH has
314% no phase memory across jobs).
315%
316% State format: [space_buf | space_srv | space_var]
317% - space_srv has sum(phasessz) columns total
318% - space_var has sum(nvars) columns total
319
320isf = sn.nodeToStateful(ind);
321if isf <= 0 || isempty(sn.state) || isempty(sn.state{isf})
322 return;
323end
324
325ist = sn.nodeToStation(ind);
326nRows = size(sn.state{isf}, 1);
327
328% Calculate state vector structure (nvars is unchanged by the conversion)
329V_old = sum(sn.nvars(ind, :));
330
331% K = phases array for this station (already updated for this class)
332K = sn.phasessz(ist, :);
333sumK_new = sum(K);
334K_old = K;
335K_old(r) = oldPhases; % What it was before
336sumK_old = sum(K_old);
337
338% Phaseshift tells us where each class's phases start
339% For class r, server phases are at positions phaseshift(r)+1 to phaseshift(r)+K(r)
340% But phaseshift has already been updated, so compute old positions
341Ks_old = [0, cumsum(K_old)];
342
343% Current state dimensions
344currentCols = size(sn.state{isf}, 2);
345
346% Calculate buffer size (state columns before space_srv)
347% Expected: currentCols = bufSize + sumK_old + V_old
348bufSize = currentCols - sumK_old - V_old;
349if bufSize < 0
350 bufSize = 0;
351end
352
353% Extract state portions
354if bufSize > 0
355 space_buf = sn.state{isf}(:, 1:bufSize);
356else
357 space_buf = zeros(nRows, 0);
358end
359
360if sumK_old > 0
361 space_srv = sn.state{isf}(:, bufSize+1:bufSize+sumK_old);
362else
363 space_srv = zeros(nRows, 0);
364end
365
366if V_old > 0
367 space_var = sn.state{isf}(:, bufSize+sumK_old+1:end);
368else
369 space_var = zeros(nRows, 0);
370end
371
372% Expand space_srv: insert (newPhases - oldPhases) zeros after class r's position
373phasesToAdd = newPhases - oldPhases;
374if phasesToAdd > 0
375 % Position where class r's phases end (in space_srv)
376 insertPos = Ks_old(r) + oldPhases;
377
378 % Insert zeros for the new phases
379 space_srv_new = [space_srv(:, 1:insertPos), ...
380 zeros(nRows, phasesToAdd), ...
381 space_srv(:, insertPos+1:end)];
382else
383 space_srv_new = space_srv;
384end
385
386% Reconstruct state (space_var unchanged: renewal PH adds no local variable)
387sn.state{isf} = [space_buf, space_srv_new, space_var];
388
389% Also update space if it exists
390if isfield(sn, 'space') && ~isempty(sn.space) && ~isempty(sn.space{isf})
391 nRowsSpace = size(sn.space{isf}, 1);
392 currentColsSpace = size(sn.space{isf}, 2);
393
394 % Same calculation for space
395 bufSizeSpace = currentColsSpace - sumK_old - V_old;
396 if bufSizeSpace < 0
397 bufSizeSpace = 0;
398 end
399
400 if bufSizeSpace > 0
401 space_buf_s = sn.space{isf}(:, 1:bufSizeSpace);
402 else
403 space_buf_s = zeros(nRowsSpace, 0);
404 end
405
406 if sumK_old > 0
407 space_srv_s = sn.space{isf}(:, bufSizeSpace+1:bufSizeSpace+sumK_old);
408 else
409 space_srv_s = zeros(nRowsSpace, 0);
410 end
411
412 if V_old > 0
413 space_var_s = sn.space{isf}(:, bufSizeSpace+sumK_old+1:end);
414 else
415 space_var_s = zeros(nRowsSpace, 0);
416 end
417
418 if phasesToAdd > 0
419 space_srv_s_new = [space_srv_s(:, 1:insertPos), ...
420 zeros(nRowsSpace, phasesToAdd), ...
421 space_srv_s(:, insertPos+1:end)];
422 else
423 space_srv_s_new = space_srv_s;
424 end
425
426 sn.space{isf} = [space_buf_s, space_srv_s_new, space_var_s];
427end
428end
429
430function sn = addPhaseSyncIfNeeded(sn, ind, r)
431% ADDPHASESYNCIFNEEDED Add a PHASE sync event for converted MAP
432%
433% When a non-Markovian distribution is converted to a MAP with multiple phases,
434% we need to add a PHASE sync event so that phase transitions can occur
435% during simulation.
436
437% Check if PHASE sync already exists for this node/class
438phaseSyncExists = false;
439local = sn.nnodes + 1;
440
441if ~isempty(sn.sync)
442 for s = 1:length(sn.sync)
443 if ~isempty(sn.sync{s}) && ~isempty(sn.sync{s}.active) && ~isempty(sn.sync{s}.active{1})
444 activeEvent = sn.sync{s}.active{1};
445 if activeEvent.event == EventType.PHASE && activeEvent.node == ind && activeEvent.class == r
446 phaseSyncExists = true;
447 break;
448 end
449 end
450 end
451end
452
453% Add PHASE sync if not present
454if ~phaseSyncExists
455 newSync = struct('active', cell(1), 'passive', cell(1));
456 newSync.active{1} = Event(EventType.PHASE, ind, r);
457 newSync.passive{1} = Event(EventType.LOCAL, local, r, 1.0);
458 sn.sync{end+1, 1} = newSync;
459end
460end
Definition fjtag.m:161