1function self = link(self,
P)
4% Copyright (c) 2012-2026, Imperial College London
7if ~isempty(self.connections)
8 line_error(mfilename,'The Network.link method cannot be used after calling the addLink() method. Use Node.setProbRouting instead to configure routing probabilities.');
11if isa(
P,'RoutingMatrix')
19 self.resetNetwork; % remove artificial class switch
nodes
21K = self.getNumberOfClasses;
22I = self.getNumberOfNodes;
25 line_error(mfilename,'Multiclass model: the linked routing matrix
P must be a cell array, e.g.,
P = model.initRoutingMatrix;
P{1} = Pclass1;
P{2} = Pclass2.
');
29if size(P,1) == size(P,2)
38 % P may look linear only because state-dependent routing leaves some zero entries unspecified
39 %cacheNodes = find(cellfun(@(c) isa(c,'Cache
'), self.getStatefulNodes));
41 switch class(self.nodes{ind})
43 % A cache needs class-switch to distinguish hits/misses unless the model is degenerate
45 if self.nodes{ind}.server.hitClass == self.nodes{ind}.server.missClass
46 line_warning(mfilename,'Ambiguous use of hitClass and missClass at cache, it
is recommended to use different classes.\n
');
52% This block is to make sure that P = model.initRoutingMatrix; P{2} writes
53% into P{2,2} rather than being interpreted as P{2,1}.
71% assign routing for self-looping jobs
73 if isa(self.classes{r},'SelfLoopingClass
')
77 P{r,r}(self.classes{r}.refstat, self.classes{r}.refstat) = 1.0;
81% link virtual sinks automatically to sink
82ispool = cellisa(self.nodes,'Sink
');
84 line_error(mfilename,'The model can have at most one sink node.
');
87if sum(cellisa(self.nodes,'Source
')) > 1
88 line_error(mfilename,'The model can have at most one source node.
');
90ispool_nnz = find(ispool)';
103 P((ind-1)*K+1:ind*K,:)=0;
112 P{r,s}(ind,jnd) = Pmat((ind-1)*K+r,(jnd-1)*K+s);
124 P{r}((ind-1)*K+1:ind*K,:)=0;
137% Default per-item retrieval routing inherited from the read
class -- see _kb/09-ldes-and-cache.md
139 if isa(self.nodes{ind},
'Cache') && isprop(self.nodes{ind},
'retrievalSystemQueueIndices') ...
140 && ~isempty(keys(self.nodes{ind}.retrievalSystemQueueIndices))
141 cacheNode = self.
nodes{ind};
143 nItems = cacheNode.items.nitems;
144 rcMap = cacheNode.retrievalSystemQueueIndices;
147 r = double(ks{kk}) + 1; % read
class index (1-based; key
is index-1)
148 Q = rcMap(ks{kk}); % retrieval-system queue node indices
155 rClass = cacheNode.server.retrievalClasses(it, r);
159 if isempty(
P{rClass,rClass})
160 P{rClass,rClass} = zeros(I);
163 if Pr(c, Q(q)) > 0 % cache -> queue (entry)
164 P{rClass,rClass}(c, Q(q)) = Pr(c, Q(q));
166 if Pr(Q(q), c) > 0 % queue -> cache (exit)
167 P{rClass,rClass}(Q(q), c) = Pr(Q(q), c);
169 for dq=1:nQ % queue -> queue
170 if Pr(Q(q), Q(dq)) > 0
171 P{rClass,rClass}(Q(q), Q(dq)) = Pr(Q(q), Q(dq));
176 % consume the read
class's template edges over the queue set
181 P{r,r}(Q(q), Q(dq)) = 0;
188% Inject deferred retrieval-system routing entries from Cache.setRetrievalSystem -- see _kb/09-ldes-and-cache.md
190 if isa(self.nodes{ind}, 'Cache
') && isprop(self.nodes{ind}, 'retrievalRoutingEntries
') ...
191 && ~isempty(self.nodes{ind}.retrievalRoutingEntries)
192 rre = self.nodes{ind}.retrievalRoutingEntries;
194 ent = rre{e}; % [fromCls, toCls, srcNode, dstNode, prob]
195 if isempty(P{ent(1),ent(2)})
196 P{ent(1),ent(2)} = zeros(I);
198 P{ent(1),ent(2)}(ent(3),ent(4)) = ent(5);
203isemptyP = false(K,K);
217csnodematrix = cell(I,I);
220 csnodematrix{ind,jnd} = zeros(K,K);
227 [If,Jf] = find(P{r,s});
229 csnodematrix{If(k),Jf(k)}(r,s) = P{r,s}(If(k),Jf(k));
237% Psum=cellsum({P{r,:}})*ones(M,1);
238% if min(Psum)<1-GlobalConstants.CoarseTol
239% line_error(mfilename,'Invalid routing probabilities (Node %d departures, switching from
class %d).
',minpos(Psum),r);
241% if max(Psum)>1+GlobalConstants.CoarseTol
242% line_error(mfilename,sprintf('Invalid routing probabilities (Node %d departures, switching from
class %d).
',maxpos(Psum),r));
248% As we will now create a CS for each link i->j,
249% we now condition on the job going from node i to j
253 S = sum(csnodematrix{ind,jnd}(r,:));
255 csnodematrix{ind,jnd}(r,:)=csnodematrix{ind,jnd}(r,:)/S;
257 csnodematrix{ind,jnd}(r,r)=1.0;
264% eye(K): a job to an autoAdded class switch stays in the same class beforehand; csMatrix diagonal is irrelevant for chains
266nodeNames = self.getNodeNames;
269 csMatrix = csMatrix + csnodematrix{ind,jnd};
270 if ~isdiag(csnodematrix{ind,jnd})
271 self.nodes{end+1} = ClassSwitch(self, sprintf('CS_%s_to_%s
',nodeNames{ind},nodeNames{jnd}),csnodematrix{ind,jnd});
272 self.nodes{end}.autoAdded = true;
273 csid(ind,jnd) = length(self.nodes);
279 % this is to ensure that also stateful cs like caches
281 if isa(self.nodes{ind},'Cache
')
282 for r=find(self.nodes{ind}.server.hitClass)
283 csMatrix(r,self.nodes{ind}.server.hitClass(r)) = 1.0;
285 for r=find(self.nodes{ind}.server.missClass)
286 csMatrix(r,self.nodes{ind}.server.missClass(r)) = 1.0;
288 elseif isa(self.nodes{ind},'ClassSwitch
')
289 if isempty(self.nodes{ind}.server.csMatrix )
290 line_error(mfilename,'Uninitialized ClassSwitch node, use the setClassSwitchingMatrix method.
');
292 csMatrix = csMatrix | self.nodes{ind}.server.csMatrix > 0.0;
296self.csMatrix = csMatrix~=0;
298Ip = length(self.nodes); % number of nodes after addition of cs nodes
303 P{r,s}((I+1):Ip,(I+1):Ip)=0;
314 P{r,r}(ind,csid(ind,jnd)) = P{r,r}(ind,csid(ind,jnd)) + P{r,s}(ind,jnd);
316 P{s,s}(csid(ind,jnd),jnd) = 1;
324connected = zeros(Ip);
326% Clear non-station nodes' outputStrategy before setting
new routing (prevents accumulation across link() calls) -- see _kb/04-networkstruct.md
328 if ~isa(
nodes{ind},
'Station') && ismethod(
nodes{ind}.output,
'initDispatcherJobClasses')
329 if ismethod(
nodes{ind}.output,
'initDispatcherJobClassesPreservingRouted')
330 nodes{ind}.output.initDispatcherJobClassesPreservingRouted(self.classes);
332 nodes{ind}.output.initDispatcherJobClasses(self.classes);
334 % Sync sn.routing with the post-clear
outputStrategy so getRoutingMatrix won
't try PROB routing for cleared classes
335 if ~isempty(self.sn) && isfield(self.sn, 'routing
') && ind <= size(self.sn.routing, 1)
337 if k <= numel(nodes{ind}.output.outputStrategy) && ~isempty(nodes{ind}.output.outputStrategy{k})
338 entry = nodes{ind}.output.outputStrategy{k};
339 self.sn.routing(ind,k) = RoutingStrategy.fromText(entry{2});
341 self.sn.routing(ind,k) = RoutingStrategy.DISABLED;
348 [If,Jf,S] = find(P{r,r});
350 if connected(If(k),Jf(k)) == 0
351 self.addLink(nodes{If(k)}, nodes{Jf(k)});
352 connected(If(k),Jf(k)) = 1;
354 nodes{If(k)}.setProbRouting(self.classes{r}, nodes{Jf(k)}, S(k));
359% Refresh sn.routing from outputStrategy: initDispatcherJobClasses above set it DISABLED, setProbRouting has since repopulated it
360if ~isempty(self.sn) && isfield(self.sn, 'routing
')
362 if ~isa(nodes{ind}, 'Station') && ind <= size(self.sn.routing, 1)
364 if isempty(nodes{ind}.output.outputStrategy{k})
365 self.sn.routing(ind,k) = RoutingStrategy.DISABLED;
367 self.sn.routing(ind,k) = RoutingStrategy.fromText(nodes{ind}.output.outputStrategy{k}{2});
374% Validate the routing probabilities -- see _kb/04-networkstruct.md
375% Pcheck normalizes the two accepted shapes (plain matrix, or K x K class-pair cell) so both are checked the same way.
382% (1) Nonnegativity, checked separately from the row-sum test below -- see _kb/04-networkstruct.md
384 for r=1:size(Pcheck,1)
385 for s=1:size(Pcheck,2)
386 if ~isempty(Pcheck{r,s})
387 [Ineg,Jneg] = find(Pcheck{r,s} < -GlobalConstants.FineTol);
389 if size(Pcheck,1) > 1 || size(Pcheck,2) > 1
390 line_error(mfilename,sprintf('Negative routing probability %g from node %s to node %s (
class %s to
class %s). Routing probabilities must be nonnegative.
', full(Pcheck{r,s}(Ineg(1),Jneg(1))), self.nodes{Ineg(1)}.name, self.nodes{Jneg(1)}.name, self.classes{r}.name, self.classes{s}.name));
392 line_error(mfilename,sprintf('Negative routing probability %g from node %s to node %s. Routing probabilities must be nonnegative.
', full(Pcheck{r,s}(Ineg(1),Jneg(1))), self.nodes{Ineg(1)}.name, self.nodes{Jneg(1)}.name));
400% (2) Row-sum <= 1, summed over destination j AND arrival class s (class-switching correctness) -- see _kb/04-networkstruct.md
403 % Place/Transition (SPN incidence arcs) and Router (connectivity declared before setRouting) are exempt -- see _kb/04-networkstruct.md
404 if isa(self.nodes{ind},'Place
') || isa(self.nodes{ind},'Transition
') || isa(self.nodes{ind},'Router
')
407 % FORK legitimately emits on several output links at once; guarded since not every node carries schedStrategy (e.g. Join)
408 if isprop(self.nodes{ind},'schedStrategy
') && ~isempty(self.nodes{ind}.schedStrategy) && SchedStrategy.toId(self.nodes{ind}.schedStrategy) == SchedStrategy.FORK
411 for r=1:size(Pcheck,1)
413 for s=1:size(Pcheck,2)
414 if ~isempty(Pcheck{r,s})
415 pOut = pOut + sum(Pcheck{r,s}(ind,:));
418 if pOut > 1.0 + GlobalConstants.FineTol
419 if size(Pcheck,1) > 1
420 line_error(mfilename,sprintf('The total routing probability
for jobs leaving node %s in
class %s
is %g, which
is greater than 1.0.
',self.nodes{ind}.name,self.classes{r}.name,full(pOut)));
422 line_error(mfilename,sprintf('The total routing probability
for jobs leaving node %s
is %g, which
is greater than 1.0.
',self.nodes{ind}.name,full(pOut)));
426 % elseif pOut < 1.0 - GlobalConstants.FineTol % we cannot check this case as class r may not reach station i, in which case its outgoing routing prob is zero
427 % if self.nodes{i}.schedStrategy ~= SchedStrategy.EXT % if not a sink
428 % line_error(mfilename,'The total routing probability
for jobs leaving node %s in
class %s
is less than 1.0.
',self.nodes{i}.name,self.classes{r}.name);
434 if isa(self.nodes{ind},'Place
')
435 self.nodes{ind}.init;
439if isReset && ~isempty(self.sn) && isfield(self.sn,'rates
')
440 self.refreshChains; % without this exception with linkAndLog
443%% Check for reducible routing (absorbing states)
445 % Pass routing matrix directly to avoid getStruct() call during link()
446 [isErg, ergInfo] = self.isRoutingErgodic(self.sn.rtorig);
447 if ~isErg && ~isempty(ergInfo.absorbingStations)
448 % Build warning message
449 absNames = strjoin(ergInfo.absorbingStations, ',
');
450 line_warning(mfilename, 'Reducible network topology detected, results may be unreliable.\n
');
454%% Check that order-independent (OI) stations have a permutation-invariant rate
456 Nvec = zeros(1, self.getNumberOfClasses);
457 for r = 1:numel(Nvec)
458 if isa(self.classes{r}, 'ClosedClass
')
459 Nvec(r) = self.classes{r}.population;
461 Nvec(r) = Inf; % open classes have infinite population
465 nd = self.nodes{ind};
466 if isa(nd, 'Queue
') && SchedStrategy.toId(nd.schedStrategy) == SchedStrategy.OI ...
467 && ~isempty(nd.svcRateFun)
468 [ok, badc, partial] = nd.checkPermInvariance(Nvec, nd.cap);
470 line_error(mfilename, 'Order-independent (OI) station
''%s
'' has a service rate function that
is not permutation-invariant: mu(c) differs
for a reordering of the microstate %s. Use SchedStrategy.PAS
for order-dependent service, or disable
this check with model.setChecks(
false).
', nd.getName(), mat2str(badc));
472 line_warning(mfilename, 'Order-independent (OI) station
''%s
'': the permutation-invariance check was only partial because the reachable population
is large; a subset of microstates was verified. To skip
this check, call model.setChecks(
false) before link().\n
', nd.getName());
480 % create java version of the network
482 jnetwork = JLINE.from_line_network(self);
486 % compare sn data structures
487 jsn = JLINE.from_jline_struct(jnetwork);
488 fprintf(1,'* Comparison with Java NetworkStruct:
');
489 bool = testJavaStruct(self.getName(),self.getStruct(),jsn);