LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
linemodel_load.m
1function model = linemodel_load(filename)
2% LINEMODEL_LOAD Load a LINE model from JSON.
3%
4% MODEL = LINEMODEL_LOAD(FILENAME) loads a model from the specified JSON
5% file (conforming to line-model.schema.json) and returns a Network,
6% LayeredNetwork, Workflow, or Environment object.
7%
8% Parameters:
9% filename - path to a .json file
10%
11% Returns:
12% model - Network, LayeredNetwork, Workflow, or Environment object
13%
14% Example:
15% model = linemodel_load('mm1.json');
16% solver = SolverMVA(model);
17% AvgTable = solver.getAvgTable();
18%
19% Copyright (c) 2012-2026, Imperial College London
20% All rights reserved.
21
22jsonText = fileread(filename);
23doc = jsondecode(jsonText);
24
25if ~isfield(doc, 'model')
26 error('linemodel_load:noModel', 'JSON file does not contain a "model" field.');
27end
28
29data = doc.model;
30mtype = data.type;
31
32switch mtype
33 case 'Network'
34 model = json2network(data, jsonText);
35 case 'LayeredNetwork'
36 model = json2layered(data);
37 case 'Workflow'
38 model = json2workflow(data);
39 case 'Environment'
40 model = json2environment(data, jsonText);
41 otherwise
42 error('linemodel_load:unknownType', 'Unsupported model type: %s', mtype);
43end
44end
45
46
47% =========================================================================
48% Network deserialization
49% =========================================================================
50
51function model = json2network(data, rawJson)
52% Reconstruct a Network from decoded JSON struct.
53% rawJson is the original text, used for parsing routing keys with commas.
54
55modelName = 'model';
56if isfield(data, 'name')
57 modelName = data.name;
58end
59model = Network(modelName);
60
61% --- Create nodes (before classes, since ClosedClass needs refstat) ---
62nodeList = {};
63if isfield(data, 'nodes')
64 nds = data.nodes;
65 if isstruct(nds)
66 nds = num2cell(nds);
67 end
68 for i = 1:length(nds)
69 nd = nds{i};
70 if isstruct(nd)
71 nd_name = nd.name;
72 nd_type = nd.type;
73 else
74 nd_name = nd('name');
75 nd_type = nd('type');
76 end
77 node = create_node(model, nd, nd_name, nd_type);
78 nodeList{end+1} = node; %#ok<AGROW>
79 end
80end
81node_map = containers.Map();
82for i = 1:length(nodeList)
83 node_map(nodeList{i}.name) = nodeList{i};
84end
85
86% --- Deferred node linking (Fork/Join, Fork tasksPerLink) ---
87if isfield(data, 'nodes')
88 nds2 = data.nodes;
89 if isstruct(nds2)
90 nds2 = num2cell(nds2);
91 end
92 for i = 1:length(nds2)
93 nd2 = nds2{i};
94 nd_name2 = nd2.name;
95 node2 = node_map(nd_name2);
96 % Join: link to paired Fork
97 if isfield(nd2, 'forkNode') && isa(node2, 'Join')
98 if node_map.isKey(nd2.forkNode)
99 node2.joinOf = node_map(nd2.forkNode);
100 end
101 end
102 % Fork: set tasksPerLink
103 if isfield(nd2, 'tasksPerLink') && isa(node2, 'Fork')
104 node2.setTasksPerLink(nd2.tasksPerLink);
105 end
106 end
107end
108
109% --- Create classes ---
110classesList = {};
111if isfield(data, 'classes')
112 cls = data.classes;
113 if isstruct(cls)
114 cls = num2cell(cls);
115 end
116 for i = 1:length(cls)
117 cd = cls{i};
118 cname = cd.name;
119 ctype = cd.type;
120 switch ctype
121 case 'Open'
122 prio = 0;
123 if isfield(cd, 'priority'), prio = cd.priority; end
124 jc = OpenClass(model, cname, prio);
125 case 'Closed'
126 pop = cd.population;
127 refNode = [];
128 if isfield(cd, 'refNode') && node_map.isKey(cd.refNode)
129 refNode = node_map(cd.refNode);
130 end
131 prio = 0;
132 if isfield(cd, 'priority'), prio = cd.priority; end
133 if isempty(refNode)
134 error('linemodel_load:noRefNode', ...
135 'ClosedClass "%s" has no valid refNode.', cname);
136 end
137 jc = ClosedClass(model, cname, pop, refNode, prio);
138 case 'Signal'
139 prio = 0;
140 if isfield(cd, 'priority'), prio = cd.priority; end
141 sigType = SignalType.NEGATIVE;
142 if isfield(cd, 'signalType')
143 sigType = SignalType.fromText(cd.signalType);
144 end
145 openOrClosed = 'Open';
146 if isfield(cd, 'openOrClosed')
147 openOrClosed = cd.openOrClosed;
148 end
149 if strcmp(openOrClosed, 'Closed')
150 refNode = [];
151 if isfield(cd, 'refNode') && node_map.isKey(cd.refNode)
152 refNode = node_map(cd.refNode);
153 end
154 if isempty(refNode)
155 error('linemodel_load:noRefNode', ...
156 'ClosedSignal "%s" has no valid refNode.', cname);
157 end
158 jc = ClosedSignal(model, cname, sigType, refNode, prio);
159 else
160 jc = OpenSignal(model, cname, sigType, prio);
161 end
162 % Removal distribution
163 if isfield(cd, 'removalDistribution')
164 remDist = json2dist(cd.removalDistribution);
165 if ~isempty(remDist)
166 jc.setRemovalDistribution(remDist);
167 end
168 end
169 % Removal policy
170 if isfield(cd, 'removalPolicy')
171 jc.setRemovalPolicy(RemovalPolicy.fromText(cd.removalPolicy));
172 end
173 otherwise
174 jc = OpenClass(model, cname);
175 end
176 if isfield(cd, 'deadline') && isfinite(cd.deadline)
177 jc.deadline = cd.deadline;
178 end
179 classesList{end+1} = jc; %#ok<AGROW>
180 end
181end
182class_map = containers.Map();
183for i = 1:length(classesList)
184 class_map(classesList{i}.name) = classesList{i};
185end
186
187% --- Resolve signal targetClass associations ---
188if isfield(data, 'classes')
189 cls2 = data.classes;
190 if isstruct(cls2), cls2 = num2cell(cls2); end
191 for i = 1:length(cls2)
192 cd2 = cls2{i};
193 if isfield(cd2, 'type') && strcmp(cd2.type, 'Signal') && isfield(cd2, 'targetClass')
194 if class_map.isKey(cd2.name) && class_map.isKey(cd2.targetClass)
195 sigCls = class_map(cd2.name);
196 sigCls.forJobClass(class_map(cd2.targetClass));
197 end
198 end
199 end
200end
201
202% --- Set service/arrival distributions ---
203if isfield(data, 'nodes')
204 nds = data.nodes;
205 if isstruct(nds)
206 nds = num2cell(nds);
207 end
208 for i = 1:length(nds)
209 nd = nds{i};
210 nd_name = nd.name;
211 node = node_map(nd_name);
212
213 if isfield(nd, 'service') && ~isempty(nd.service)
214 svc = nd.service;
215 svcFields = fieldnames(svc);
216 for f = 1:length(svcFields)
217 cname = svcFields{f};
218 distJson = svc.(cname);
219 if ~class_map.isKey(cname)
220 continue;
221 end
222 jc = class_map(cname);
223 dist = json2dist(distJson);
224 if ~isempty(dist)
225 if isa(node, 'Source')
226 node.setArrival(jc, dist);
227 elseif isa(node, 'Queue') || isa(node, 'Delay')
228 % Pass DPS/GPS weight if available
229 weight = 1;
230 if isfield(nd, 'schedParams')
231 sp_tmp = nd.schedParams;
232 if isfield(sp_tmp, cname)
233 weight = sp_tmp.(cname);
234 end
235 end
236 node.setService(jc, dist, weight);
237 end
238 end
239 end
240 end
241
242 % ClassSwitch matrix (dict format: classSwitchMatrix)
243 if isfield(nd, 'classSwitchMatrix') && isa(node, 'ClassSwitch')
244 csm_data = nd.classSwitchMatrix;
245 classes = model.getClasses();
246 K = length(classes);
247 mat = zeros(K);
248 class_idx = containers.Map();
249 for ci = 1:K
250 class_idx(classes{ci}.name) = ci;
251 end
252 fromFields = fieldnames(csm_data);
253 for fi = 1:length(fromFields)
254 fromName = fromFields{fi};
255 if ~class_idx.isKey(fromName), continue; end
256 ri = class_idx(fromName);
257 toStruct = csm_data.(fromName);
258 toFields = fieldnames(toStruct);
259 for ti = 1:length(toFields)
260 toName = toFields{ti};
261 if ~class_idx.isKey(toName), continue; end
262 ci = class_idx(toName);
263 mat(ri, ci) = toStruct.(toName);
264 end
265 end
266 node.server = node.server.updateClassSwitch(mat);
267 % Legacy 2D array format: csMatrix (from older JAR saves)
268 elseif isfield(nd, 'csMatrix') && isa(node, 'ClassSwitch')
269 mat = nd.csMatrix;
270 if iscell(mat)
271 mat = cell2mat(mat);
272 end
273 node.server = node.server.updateClassSwitch(mat);
274 end
275
276 % DPS scheduling parameters (weights already passed via setService above)
277
278 % Per-class buffer capacity
279 if isfield(nd, 'classCap') && isa(node, 'Queue')
280 ccData = nd.classCap;
281 ccFields = fieldnames(ccData);
282 for cci = 1:length(ccFields)
283 cname = ccFields{cci};
284 if class_map.isKey(cname)
285 jc = class_map(cname);
286 % Find class index
287 cls = model.getClasses();
288 for ci = 1:length(cls)
289 if strcmp(cls{ci}.name, cname)
290 node.classCap(ci) = ccData.(cname);
291 break;
292 end
293 end
294 end
295 end
296 end
297
298 % Drop rules
299 if isfield(nd, 'dropRule') && isa(node, 'Queue')
300 drData = nd.dropRule;
301 drFields = fieldnames(drData);
302 for dri = 1:length(drFields)
303 cname = drFields{dri};
304 if class_map.isKey(cname)
305 cls = model.getClasses();
306 for ci = 1:length(cls)
307 if strcmp(cls{ci}.name, cname)
308 node.dropRule(ci) = str_to_droprule(drData.(cname));
309 break;
310 end
311 end
312 end
313 end
314 end
315
316 % Load-dependent scaling
317 if isfield(nd, 'loadDependence') && isa(node, 'Queue')
318 ld = nd.loadDependence;
319 if isfield(ld, 'type') && strcmp(ld.type, 'loadDependent') && isfield(ld, 'scaling')
320 scaling = ld.scaling(:)';
321 node.setLoadDependence(scaling);
322 end
323 end
324
325 % Join strategy and quorum
326 if isa(node, 'Join')
327 if isfield(nd, 'joinStrategy')
328 jsStr = nd.joinStrategy;
329 classes = model.getClasses();
330 for ci = 1:length(classes)
331 switch jsStr
332 case 'STD'
333 node.input.setStrategy(classes{ci}, JoinStrategy.STD);
334 case {'PARTIAL', 'QUORUM', 'Quorum'}
335 node.input.setStrategy(classes{ci}, JoinStrategy.PARTIAL);
336 end
337 end
338 end
339 if isfield(nd, 'joinQuorum')
340 jq = nd.joinQuorum;
341 classes = model.getClasses();
342 for ci = 1:length(classes)
343 node.input.setRequired(classes{ci}, jq);
344 end
345 end
346 end
347
348 % Cache hit/miss class mappings and popularity distributions
349 if isa(node, 'Cache') && isfield(nd, 'cache')
350 cc = nd.cache;
351 % Hit class mapping
352 if isfield(cc, 'hitClass')
353 hcData = cc.hitClass;
354 hcFields = fieldnames(hcData);
355 for hci = 1:length(hcFields)
356 inName = hcFields{hci};
357 outName = hcData.(inName);
358 if class_map.isKey(inName) && class_map.isKey(outName)
359 node.setHitClass(class_map(inName), class_map(outName));
360 end
361 end
362 end
363 % Miss class mapping
364 if isfield(cc, 'missClass')
365 mcData = cc.missClass;
366 mcFields = fieldnames(mcData);
367 for mci = 1:length(mcFields)
368 inName = mcFields{mci};
369 outName = mcData.(inName);
370 if class_map.isKey(inName) && class_map.isKey(outName)
371 node.setMissClass(class_map(inName), class_map(outName));
372 end
373 end
374 end
375 % Popularity distributions (setRead)
376 if isfield(cc, 'popularity')
377 popData = cc.popularity;
378 popFields = fieldnames(popData);
379 for pfi = 1:length(popFields)
380 cname = popFields{pfi};
381 if class_map.isKey(cname)
382 popDist = json2dist(popData.(cname));
383 if ~isempty(popDist) && ~isa(popDist, 'Disabled')
384 node.setRead(class_map(cname), popDist);
385 end
386 end
387 end
388 end
389 end
390 % Heterogeneous server types
391 if isa(node, 'Queue') && isfield(nd, 'serverTypes')
392 stArr = nd.serverTypes;
393 if isstruct(stArr), stArr = num2cell(stArr); end
394 for si = 1:length(stArr)
395 stData = stArr{si};
396 stName = stData.name;
397 stCount = stData.count;
398 st = ServerType(stName, stCount);
399 % Compatible classes
400 if isfield(stData, 'compatibleClasses')
401 ccList = stData.compatibleClasses;
402 if ~iscell(ccList), ccList = {ccList}; end
403 for cci = 1:length(ccList)
404 if class_map.isKey(ccList{cci})
405 st.addCompatible(class_map(ccList{cci}));
406 end
407 end
408 end
409 node.addServerType(st);
410 % Per-class service distributions
411 if isfield(stData, 'service')
412 svcData = stData.service;
413 svcFields = fieldnames(svcData);
414 for fi = 1:length(svcFields)
415 cname = svcFields{fi};
416 if class_map.isKey(cname)
417 jc = class_map(cname);
418 dist = json2dist(svcData.(cname));
419 if ~isempty(dist)
420 node.setHeteroService(jc, st, dist);
421 end
422 end
423 end
424 end
425 end
426 % Scheduling policy
427 if isfield(nd, 'heteroSchedPolicy')
428 policy = HeteroSchedPolicy.fromText(nd.heteroSchedPolicy);
429 node.setHeteroSchedPolicy(policy);
430 end
431 end
432 end
433end
434
435% --- Restore Balking, Retrial, Patience ---
436if isfield(data, 'nodes')
437 ndsImp = data.nodes;
438 if isstruct(ndsImp), ndsImp = num2cell(ndsImp); end
439 for i = 1:length(ndsImp)
440 ndImp = ndsImp{i};
441 if ~node_map.isKey(ndImp.name), continue; end
442 node = node_map(ndImp.name);
443 if ~isa(node, 'Queue'), continue; end
444 % Balking
445 if isfield(ndImp, 'balking') && ~isempty(ndImp.balking)
446 balkData = ndImp.balking;
447 fnames = fieldnames(balkData);
448 for fi = 1:length(fnames)
449 className = fnames{fi};
450 if ~class_map.isKey(className), continue; end
451 jc = class_map(className);
452 bjc = balkData.(className);
453 % Parse strategy
454 switch bjc.strategy
455 case 'QUEUE_LENGTH', strategy = BalkingStrategy.QUEUE_LENGTH;
456 case 'EXPECTED_WAIT', strategy = BalkingStrategy.EXPECTED_WAIT;
457 case 'COMBINED', strategy = BalkingStrategy.COMBINED;
458 otherwise, continue;
459 end
460 % Parse thresholds
461 thData = bjc.thresholds;
462 if isstruct(thData), thData = num2cell(thData); end
463 thresholds = {};
464 for ti = 1:length(thData)
465 td = thData{ti};
466 maxJobs = td.maxJobs;
467 if maxJobs < 0, maxJobs = Inf; end
468 thresholds{end+1} = {td.minJobs, maxJobs, td.probability};
469 end
470 node.setBalking(jc, strategy, thresholds);
471 end
472 end
473 % Retrial
474 if isfield(ndImp, 'retrial') && ~isempty(ndImp.retrial)
475 retData = ndImp.retrial;
476 fnames = fieldnames(retData);
477 for fi = 1:length(fnames)
478 className = fnames{fi};
479 if ~class_map.isKey(className), continue; end
480 jc = class_map(className);
481 rjc = retData.(className);
482 delayDist = json2dist(rjc.delay);
483 maxAttempts = -1;
484 if isfield(rjc, 'maxAttempts')
485 maxAttempts = rjc.maxAttempts;
486 end
487 node.setRetrial(jc, delayDist, maxAttempts);
488 end
489 end
490 % Patience
491 if isfield(ndImp, 'patience') && ~isempty(ndImp.patience)
492 patData = ndImp.patience;
493 fnames = fieldnames(patData);
494 for fi = 1:length(fnames)
495 className = fnames{fi};
496 if ~class_map.isKey(className), continue; end
497 jc = class_map(className);
498 pjc = patData.(className);
499 patDist = json2dist(pjc.distribution);
500 if isfield(pjc, 'impatienceType')
501 switch pjc.impatienceType
502 case 'reneging', impType = ImpatienceType.RENEGING;
503 case 'balking', impType = ImpatienceType.BALKING;
504 case 'retrial', impType = ImpatienceType.RETRIAL;
505 otherwise, impType = ImpatienceType.RENEGING;
506 end
507 else
508 impType = ImpatienceType.RENEGING;
509 end
510 node.setPatience(jc, impType, patDist);
511 end
512 end
513 end
514end
515
516% --- Configure Transition modes ---
517if isfield(data, 'nodes')
518 nds3 = data.nodes;
519 if isstruct(nds3)
520 nds3 = num2cell(nds3);
521 end
522 for i = 1:length(nds3)
523 nd3 = nds3{i};
524 if ~isfield(nd3, 'modes'), continue; end
525 if ~strcmp(nd3.type, 'Transition'), continue; end
526 tnode = node_map(nd3.name);
527 modesData = nd3.modes;
528 if isstruct(modesData)
529 modesData = num2cell(modesData);
530 end
531 for mi = 1:length(modesData)
532 md = modesData{mi};
533 modeName = 'Mode';
534 if isfield(md, 'name'), modeName = md.name; end
535 mode = tnode.addMode(modeName);
536 % Distribution
537 if isfield(md, 'distribution') && ~isempty(md.distribution)
538 dist = json2dist(md.distribution);
539 if ~isempty(dist)
540 tnode.setDistribution(mode, dist);
541 end
542 end
543 % Timing strategy
544 if isfield(md, 'timingStrategy')
545 if strcmp(md.timingStrategy, 'IMMEDIATE')
546 tnode.setTimingStrategy(mode, TimingStrategy.IMMEDIATE);
547 else
548 tnode.setTimingStrategy(mode, TimingStrategy.TIMED);
549 end
550 end
551 % Number of servers
552 if isfield(md, 'numServers')
553 nsVal = md.numServers;
554 if ischar(nsVal) || isstring(nsVal)
555 if strcmpi(nsVal, 'Infinity'), nsVal = Inf; else, nsVal = str2double(nsVal); end
556 end
557 if nsVal > 1
558 tnode.setNumberOfServers(mode, nsVal);
559 end
560 end
561 % Firing priority
562 if isfield(md, 'firingPriority')
563 tnode.setFiringPriorities(mode, md.firingPriority);
564 end
565 % Firing weight
566 if isfield(md, 'firingWeight')
567 tnode.setFiringWeights(mode, md.firingWeight);
568 end
569 % Enabling conditions
570 if isfield(md, 'enablingConditions')
571 ecList = md.enablingConditions;
572 if isstruct(ecList), ecList = num2cell(ecList); end
573 for ei = 1:length(ecList)
574 ec = ecList{ei};
575 if node_map.isKey(ec.node) && class_map.isKey(ec.class)
576 tnode.setEnablingConditions(mode, class_map(ec.class), node_map(ec.node), ec.count);
577 end
578 end
579 end
580 % Inhibiting conditions
581 if isfield(md, 'inhibitingConditions')
582 icList = md.inhibitingConditions;
583 if isstruct(icList), icList = num2cell(icList); end
584 for ii = 1:length(icList)
585 ic = icList{ii};
586 if node_map.isKey(ic.node) && class_map.isKey(ic.class)
587 tnode.setInhibitingConditions(mode, class_map(ic.class), node_map(ic.node), ic.count);
588 end
589 end
590 end
591 % Firing outcomes
592 if isfield(md, 'firingOutcomes')
593 foList = md.firingOutcomes;
594 if isstruct(foList), foList = num2cell(foList); end
595 for fi = 1:length(foList)
596 fo = foList{fi};
597 if node_map.isKey(fo.node) && class_map.isKey(fo.class)
598 tnode.setFiringOutcome(mode, class_map(fo.class), node_map(fo.node), fo.count);
599 end
600 end
601 end
602 end
603 end
604end
605
606% --- Restore initial state for Place nodes ---
607if isfield(data, 'nodes')
608 nds4 = data.nodes;
609 if isstruct(nds4), nds4 = num2cell(nds4); end
610 for i = 1:length(nds4)
611 nd4 = nds4{i};
612 if isfield(nd4, 'initialState') && node_map.isKey(nd4.name)
613 nodeObj = node_map(nd4.name);
614 if isa(nodeObj, 'Place')
615 stVal = nd4.initialState;
616 stVal = stVal(:)'; % Ensure row vector (jsondecode returns column vectors)
617 nodeObj.setState(stVal);
618 end
619 end
620 end
621end
622
623% --- Build routing ---
624if isfield(data, 'routing') && isfield(data.routing, 'type') && strcmp(data.routing.type, 'matrix')
625 P = model.initRoutingMatrix();
626 K = length(classesList);
627 M = length(nodeList);
628
629 % Build node/class index maps
630 nodeIdx = containers.Map();
631 for i = 1:M
632 nodeIdx(nodeList{i}.name) = i;
633 end
634 classIdx = containers.Map();
635 for i = 1:K
636 classIdx(classesList{i}.name) = i;
637 end
638
639 % Parse routing keys from raw JSON to preserve commas
640 routingEntries = parse_routing_keys(rawJson, class_map, node_map);
641
642 for e = 1:length(routingEntries)
643 re = routingEntries{e};
644 r = classIdx(re.className1);
645 s = classIdx(re.className2);
646 ii = nodeIdx(re.fromNode);
647 jj = nodeIdx(re.toNode);
648 P{r,s}(ii, jj) = re.prob;
649 end
650
651 model.link(P);
652end
653
654% --- Restore routing strategies ---
655if isfield(data, 'routingStrategies')
656 stratMap = containers.Map();
657 stratMap('RAND') = RoutingStrategy.RAND;
658 stratMap('RROBIN') = RoutingStrategy.RROBIN;
659 stratMap('WRROBIN') = RoutingStrategy.WRROBIN;
660 stratMap('JSQ') = RoutingStrategy.JSQ;
661 stratMap('KCHOICES') = RoutingStrategy.KCHOICES;
662 stratMap('FIRING') = RoutingStrategy.FIRING;
663 stratMap('RL') = RoutingStrategy.RL;
664 stratMap('DISABLED') = RoutingStrategy.DISABLED;
665
666 rsFields = fieldnames(data.routingStrategies);
667 for fi = 1:length(rsFields)
668 nodeName = rsFields{fi};
669 if node_map.isKey(nodeName)
670 nodeObj = node_map(nodeName);
671 classStrats = data.routingStrategies.(nodeName);
672 csFields = fieldnames(classStrats);
673 for ci = 1:length(csFields)
674 className = csFields{ci};
675 stratName = classStrats.(className);
676 if class_map.isKey(className) && stratMap.isKey(stratName)
677 % Skip RAND, PROB: already handled by routing matrix
678 % Skip WRROBIN: handled separately in routingWeights section
679 rs = stratMap(stratName);
680 if rs ~= RoutingStrategy.RAND && rs ~= RoutingStrategy.PROB && rs ~= RoutingStrategy.WRROBIN
681 nodeObj.setRouting(class_map(className), rs);
682 end
683 end
684 end
685 end
686 end
687end
688
689% --- Restore routing weights (WRROBIN) ---
690if isfield(data, 'routingWeights')
691 rwFields = fieldnames(data.routingWeights);
692 for fi = 1:length(rwFields)
693 nodeName = rwFields{fi};
694 if node_map.isKey(nodeName)
695 nodeObj = node_map(nodeName);
696 classWeights = data.routingWeights.(nodeName);
697 cwFields = fieldnames(classWeights);
698 for ci = 1:length(cwFields)
699 className = cwFields{ci};
700 destWeights = classWeights.(className);
701 if class_map.isKey(className)
702 % Clear existing routing entries for this class
703 % (link() may have set PROB entries that would accumulate)
704 classIdx = class_map(className).index;
705 if length(nodeObj.output.outputStrategy) >= classIdx && ...
706 length(nodeObj.output.outputStrategy{1, classIdx}) >= 3
707 nodeObj.output.outputStrategy{1, classIdx}{3} = {};
708 end
709 dwFields = fieldnames(destWeights);
710 for di = 1:length(dwFields)
711 destName = dwFields{di};
712 weight = destWeights.(destName);
713 if node_map.isKey(destName)
714 nodeObj.setRouting(class_map(className), RoutingStrategy.WRROBIN, node_map(destName), weight);
715 end
716 end
717 end
718 end
719 end
720 end
721end
722
723% --- Restore switchover times ---
724for ni = 1:length(data.nodes)
725 nd = data.nodes(ni);
726 if isfield(nd, 'switchoverTimes') && ~isempty(nd.switchoverTimes)
727 nodeObj = node_map(nd.name);
728 soArr = nd.switchoverTimes;
729 if ~iscell(soArr)
730 soArr = {soArr};
731 end
732 for si = 1:length(soArr)
733 so = soArr{si};
734 fromCls = class_map(so.from);
735 toCls = class_map(so.to);
736 dist = json2dist(so.distribution);
737 if ~isempty(dist)
738 nodeObj.setSwitchover(fromCls, toCls, dist);
739 end
740 end
741 end
742end
743
744% --- Restore finite capacity regions ---
745if isfield(data, 'finiteCapacityRegions')
746 fcrArr = data.finiteCapacityRegions;
747 if ~iscell(fcrArr)
748 fcrArr = {fcrArr};
749 end
750 classes = model.getClasses();
751 for ri = 1:length(fcrArr)
752 rj = fcrArr{ri};
753 regNodes = {};
754 % Support both old format ("nodes" list) and new format ("stations" array)
755 if isfield(rj, 'stations')
756 stArr = rj.stations;
757 if ~iscell(stArr), stArr = {stArr}; end
758 for si = 1:length(stArr)
759 sj = stArr{si};
760 nodeName = sj.node;
761 if node_map.isKey(nodeName)
762 regNodes{end+1} = node_map(nodeName); %#ok<AGROW>
763 end
764 end
765 elseif isfield(rj, 'nodes')
766 nodeNames = rj.nodes;
767 if ~iscell(nodeNames), nodeNames = {nodeNames}; end
768 for ni = 1:length(nodeNames)
769 if node_map.isKey(nodeNames{ni})
770 regNodes{end+1} = node_map(nodeNames{ni}); %#ok<AGROW>
771 end
772 end
773 end
774 maxJobs = FiniteCapacityRegion.UNBOUNDED;
775 if isfield(rj, 'globalMaxJobs')
776 maxJobs = rj.globalMaxJobs;
777 end
778 if ~isempty(regNodes)
779 try
780 region = model.addRegion(rj.name, regNodes, maxJobs);
781 % globalMaxMemory
782 if isfield(rj, 'globalMaxMemory')
783 region.globalMaxMemory = rj.globalMaxMemory;
784 end
785 % classMaxJobs
786 if isfield(rj, 'classMaxJobs')
787 cmj = rj.classMaxJobs;
788 cmjFields = fieldnames(cmj);
789 for ci = 1:length(cmjFields)
790 cname = cmjFields{ci};
791 if class_map.isKey(cname)
792 jc = class_map(cname);
793 region.classMaxJobs(jc.index) = cmj.(cname);
794 end
795 end
796 end
797 % dropRule
798 if isfield(rj, 'dropRule')
799 drData = rj.dropRule;
800 drFields = fieldnames(drData);
801 for di = 1:length(drFields)
802 cname = drFields{di};
803 if class_map.isKey(cname)
804 jc = class_map(cname);
805 region.dropRule(jc.index) = str_to_droprule(drData.(cname));
806 end
807 end
808 end
809 % Per-station classWeight and classSize from stations array
810 if isfield(rj, 'stations')
811 stArr2 = rj.stations;
812 if ~iscell(stArr2), stArr2 = {stArr2}; end
813 for si = 1:length(stArr2)
814 sj2 = stArr2{si};
815 if isfield(sj2, 'classWeight')
816 cwData = sj2.classWeight;
817 cwFields = fieldnames(cwData);
818 for ci = 1:length(cwFields)
819 cname = cwFields{ci};
820 if class_map.isKey(cname)
821 jc = class_map(cname);
822 region.classWeight(jc.index) = cwData.(cname);
823 end
824 end
825 end
826 if isfield(sj2, 'classSize')
827 csData = sj2.classSize;
828 csFields = fieldnames(csData);
829 for ci = 1:length(csFields)
830 cname = csFields{ci};
831 if class_map.isKey(cname)
832 jc = class_map(cname);
833 region.classSize(jc.index) = csData.(cname);
834 end
835 end
836 end
837 end
838 end
839 catch
840 end
841 end
842 end
843end
844end
845
846
847function node = create_node(model, nd, name, ntype)
848% Create a node from JSON data.
849switch ntype
850 case 'Source'
851 node = Source(model, name);
852 case 'Sink'
853 node = Sink(model, name);
854 case 'Delay'
855 node = Delay(model, name);
856 case 'Queue'
857 schedStr = 'FCFS';
858 if isfield(nd, 'scheduling')
859 schedStr = nd.scheduling;
860 end
861 schedId = str_to_sched_id(schedStr);
862 node = Queue(model, name, schedId);
863 if isfield(nd, 'servers') && nd.servers > 1
864 node.setNumberOfServers(nd.servers);
865 end
866 if isfield(nd, 'buffer') && isfinite(nd.buffer)
867 node.cap = nd.buffer;
868 end
869 case 'Fork'
870 node = Fork(model, name);
871 case 'Join'
872 node = Join(model, name);
873 case 'Router'
874 node = Router(model, name);
875 case 'ClassSwitch'
876 node = ClassSwitch(model, name);
877 case 'Cache'
878 cc = struct();
879 if isfield(nd, 'cache')
880 cc = nd.cache;
881 end
882 nitems = 10;
883 if isfield(cc, 'items'), nitems = cc.items; end
884 cap = 1;
885 if isfield(cc, 'capacity'), cap = cc.capacity; end
886 replStr = 'LRU';
887 if isfield(cc, 'replacement'), replStr = cc.replacement; end
888 replId = str_to_repl_id(replStr);
889 node = Cache(model, name, nitems, cap, replId);
890 case 'Place'
891 node = Place(model, name);
892 case 'Transition'
893 node = Transition(model, name);
894 otherwise
895 node = Queue(model, name, SchedStrategy.FCFS);
896end
897end
898
899
900% =========================================================================
901% LayeredNetwork deserialization
902% =========================================================================
903
904function model = json2layered(data)
905% Reconstruct a LayeredNetwork from decoded JSON struct.
906
907modelName = 'model';
908if isfield(data, 'name')
909 modelName = data.name;
910end
911model = LayeredNetwork(modelName);
912
913% --- Processors (Python schema: "processors", JAR schema: "hosts") ---
914proc_map = containers.Map();
915if isfield(data, 'processors')
916 procs = data.processors;
917elseif isfield(data, 'hosts')
918 procs = data.hosts;
919else
920 procs = [];
921end
922if ~isempty(procs)
923 if isstruct(procs), procs = num2cell(procs); end
924 for i = 1:length(procs)
925 pd = procs{i};
926 pname = pd.name;
927 mult = 1;
928 if isfield(pd, 'multiplicity'), mult = pd.multiplicity; end
929 schedStr = 'INF';
930 if isfield(pd, 'scheduling'), schedStr = pd.scheduling; end
931 schedId = str_to_sched_id(schedStr);
932 quantum = 0.001;
933 if isfield(pd, 'quantum'), quantum = pd.quantum; end
934 sf = 1.0;
935 if isfield(pd, 'speedFactor'), sf = pd.speedFactor; end
936 proc = Host(model, pname, mult, schedId, quantum, sf);
937 if isfield(pd, 'replication') && pd.replication > 1
938 proc.setReplication(pd.replication);
939 end
940 proc_map(pname) = proc;
941 end
942end
943
944% --- Tasks ---
945task_map = containers.Map();
946if isfield(data, 'tasks')
947 tsks = data.tasks;
948 if isstruct(tsks), tsks = num2cell(tsks); end
949 for i = 1:length(tsks)
950 td = tsks{i};
951 tname = td.name;
952 mult = 1;
953 if isfield(td, 'multiplicity'), mult = td.multiplicity; end
954 schedStr = 'INF';
955 if isfield(td, 'scheduling'), schedStr = td.scheduling; end
956 schedId = str_to_sched_id(schedStr);
957 taskType = 'Task';
958 if isfield(td, 'taskType'), taskType = td.taskType; end
959 if strcmp(taskType, 'FunctionTask')
960 task = FunctionTask(model, tname, mult, schedId);
961 elseif strcmp(taskType, 'CacheTask')
962 totalItems = 1;
963 if isfield(td, 'totalItems'), totalItems = td.totalItems; end
964 cacheCap = 1;
965 if isfield(td, 'cacheCapacity'), cacheCap = td.cacheCapacity; end
966 rsStr = 'FIFO';
967 if isfield(td, 'replacementStrategy'), rsStr = td.replacementStrategy; end
968 rsMap = containers.Map({'RR','FIFO','SFIFO','LRU'}, ...
969 {ReplacementStrategy.RR, ReplacementStrategy.FIFO, ...
970 ReplacementStrategy.SFIFO, ReplacementStrategy.LRU});
971 if rsMap.isKey(upper(rsStr))
972 rs = rsMap(upper(rsStr));
973 else
974 rs = ReplacementStrategy.FIFO;
975 end
976 task = CacheTask(model, tname, totalItems, cacheCap, rs, mult, schedId);
977 else
978 task = Task(model, tname, mult, schedId);
979 end
980 % Assign to processor (Python schema: "processor", JAR schema: "host")
981 procRef = '';
982 if isfield(td, 'processor'), procRef = td.processor;
983 elseif isfield(td, 'host'), procRef = td.host;
984 end
985 if ~isempty(procRef) && proc_map.isKey(procRef)
986 task.on(proc_map(procRef));
987 end
988 % Think time (Python schema: "thinkTime" as dist, JAR schema: "thinkTimeMean"/"thinkTimeSCV")
989 if isfield(td, 'thinkTime')
990 dist = json2dist(td.thinkTime);
991 if ~isempty(dist)
992 task.setThinkTime(dist);
993 end
994 elseif isfield(td, 'thinkTimeMean') && td.thinkTimeMean > 0
995 task.setThinkTime(Exp(1.0 / td.thinkTimeMean));
996 end
997 % Setup time
998 if isfield(td, 'setupTime')
999 dist = json2dist(td.setupTime);
1000 if ~isempty(dist)
1001 task.setSetupTime(dist);
1002 end
1003 elseif isfield(td, 'setupTimeMean') && td.setupTimeMean > 1e-8
1004 task.setSetupTime(Exp(1.0 / td.setupTimeMean));
1005 end
1006 % Delay-off time
1007 if isfield(td, 'delayOffTime')
1008 dist = json2dist(td.delayOffTime);
1009 if ~isempty(dist)
1010 task.setDelayOffTime(dist);
1011 end
1012 elseif isfield(td, 'delayOffTimeMean') && td.delayOffTimeMean > 1e-8
1013 task.setDelayOffTime(Exp(1.0 / td.delayOffTimeMean));
1014 end
1015 % Fan in
1016 if isfield(td, 'fanIn') && isstruct(td.fanIn)
1017 fnames = fieldnames(td.fanIn);
1018 for fi = 1:length(fnames)
1019 task.setFanIn(fnames{fi}, td.fanIn.(fnames{fi}));
1020 end
1021 end
1022 % Fan out
1023 if isfield(td, 'fanOut') && isstruct(td.fanOut)
1024 fnames = fieldnames(td.fanOut);
1025 for fi = 1:length(fnames)
1026 task.setFanOut(fnames{fi}, td.fanOut.(fnames{fi}));
1027 end
1028 end
1029 % Replication
1030 if isfield(td, 'replication') && td.replication > 1
1031 task.setReplication(td.replication);
1032 end
1033 task_map(tname) = task;
1034 end
1035end
1036
1037% --- Entries ---
1038entry_map = containers.Map();
1039if isfield(data, 'entries')
1040 ents = data.entries;
1041 if isstruct(ents), ents = num2cell(ents); end
1042 for i = 1:length(ents)
1043 ed = ents{i};
1044 ename = ed.name;
1045 entryType = 'Entry';
1046 if isfield(ed, 'entryType'), entryType = ed.entryType; end
1047 if strcmp(entryType, 'ItemEntry')
1048 totalItems = 1;
1049 if isfield(ed, 'totalItems'), totalItems = ed.totalItems; end
1050 accessProb = [];
1051 if isfield(ed, 'accessProb')
1052 ap = ed.accessProb;
1053 if isstruct(ap)
1054 accessProb = json2dist(ap);
1055 elseif isnumeric(ap)
1056 accessProb = DiscreteSampler(ap);
1057 end
1058 end
1059 if isempty(accessProb)
1060 % Default uniform distribution
1061 accessProb = DiscreteSampler(ones(1, totalItems) / totalItems);
1062 end
1063 entry = ItemEntry(model, ename, totalItems, accessProb);
1064 else
1065 entry = Entry(model, ename);
1066 end
1067 if isfield(ed, 'task') && task_map.isKey(ed.task)
1068 entry.on(task_map(ed.task));
1069 end
1070 % Entry arrival distribution
1071 if isfield(ed, 'arrival')
1072 dist = json2dist(ed.arrival);
1073 if ~isempty(dist)
1074 entry.setArrival(dist);
1075 end
1076 end
1077 entry_map(ename) = entry;
1078 end
1079end
1080
1081% --- Activities ---
1082act_map = containers.Map();
1083if isfield(data, 'activities')
1084 acts = data.activities;
1085 if isstruct(acts), acts = num2cell(acts); end
1086 for i = 1:length(acts)
1087 ad = acts{i};
1088 aname = ad.name;
1089
1090 % Host demand
1091 hd = GlobalConstants.FineTol;
1092 if isfield(ad, 'hostDemand')
1093 hdDist = json2dist(ad.hostDemand);
1094 if ~isempty(hdDist)
1095 hd = hdDist;
1096 end
1097 end
1098
1099 % Bound to entry (Python schema: "boundTo", JAR schema: "boundToEntry")
1100 bte = '';
1101 if isfield(ad, 'boundTo')
1102 bte = ad.boundTo;
1103 elseif isfield(ad, 'boundToEntry')
1104 bte = ad.boundToEntry;
1105 end
1106
1107 act = Activity(model, aname, hd, bte);
1108
1109 % Assign to task
1110 if isfield(ad, 'task') && task_map.isKey(ad.task)
1111 act.on(task_map(ad.task));
1112 end
1113
1114 % Replies to entry
1115 if isfield(ad, 'repliesTo') && entry_map.isKey(ad.repliesTo)
1116 act.repliesTo(entry_map(ad.repliesTo));
1117 end
1118
1119 % Synch calls (Python schema: "entry", JAR schema: "dest")
1120 if isfield(ad, 'synchCalls')
1121 scs = ad.synchCalls;
1122 if isstruct(scs), scs = num2cell(scs); end
1123 for j = 1:length(scs)
1124 sc = scs{j};
1125 if isfield(sc, 'entry'), ename = sc.entry;
1126 elseif isfield(sc, 'dest'), ename = sc.dest;
1127 else, continue;
1128 end
1129 meanCalls = 1.0;
1130 if isfield(sc, 'mean'), meanCalls = sc.mean; end
1131 if entry_map.isKey(ename)
1132 act.synchCall(entry_map(ename), meanCalls);
1133 end
1134 end
1135 end
1136
1137 % Asynch calls (Python schema: "entry", JAR schema: "dest")
1138 if isfield(ad, 'asynchCalls')
1139 acs = ad.asynchCalls;
1140 if isstruct(acs), acs = num2cell(acs); end
1141 for j = 1:length(acs)
1142 ac = acs{j};
1143 if isfield(ac, 'entry'), ename = ac.entry;
1144 elseif isfield(ac, 'dest'), ename = ac.dest;
1145 else, continue;
1146 end
1147 meanCalls = 1.0;
1148 if isfield(ac, 'mean'), meanCalls = ac.mean; end
1149 if entry_map.isKey(ename)
1150 act.asynchCall(entry_map(ename), meanCalls);
1151 end
1152 end
1153 end
1154
1155 act_map(aname) = act;
1156 end
1157end
1158
1159% --- Precedences (Python schema: "type"/"activities", JAR schema: "preActs"/"postActs"/"preType"/"postType") ---
1160if isfield(data, 'precedences')
1161 precs = data.precedences;
1162 if isstruct(precs), precs = num2cell(precs); end
1163 for i = 1:length(precs)
1164 pd = precs{i};
1165 if ~isfield(pd, 'task') || ~task_map.isKey(pd.task)
1166 continue;
1167 end
1168 task = task_map(pd.task);
1169
1170 if isfield(pd, 'preActs') || isfield(pd, 'postActs')
1171 % JAR schema
1172 preNames = {};
1173 postNames = {};
1174 if isfield(pd, 'preActs')
1175 preNames = pd.preActs;
1176 if ischar(preNames), preNames = {preNames}; end
1177 end
1178 if isfield(pd, 'postActs')
1179 postNames = pd.postActs;
1180 if ischar(postNames), postNames = {postNames}; end
1181 end
1182 preType = 'pre';
1183 postType = 'post';
1184 if isfield(pd, 'preType'), preType = pd.preType; end
1185 if isfield(pd, 'postType'), postType = pd.postType; end
1186
1187 % Normalize JAR naming convention to Python convention
1188 switch postType
1189 case 'post-AND', postType = 'and-fork';
1190 case 'post-OR', postType = 'or-fork';
1191 case 'post-LOOP', postType = 'loop';
1192 end
1193 switch preType
1194 case 'pre-AND', preType = 'and-join';
1195 case 'pre-OR', preType = 'or-join';
1196 end
1197
1198 % Extract postParams (JAR schema: probabilities/loopCount)
1199 postParams = [];
1200 if isfield(pd, 'postParams')
1201 postParams = pd.postParams;
1202 if iscell(postParams), postParams = cell2mat(postParams); end
1203 end
1204
1205 preActs = {};
1206 for ai = 1:length(preNames)
1207 if act_map.isKey(preNames{ai})
1208 preActs{end+1} = act_map(preNames{ai}); %#ok<AGROW>
1209 end
1210 end
1211 postActs = {};
1212 for ai = 1:length(postNames)
1213 if act_map.isKey(postNames{ai})
1214 postActs{end+1} = act_map(postNames{ai}); %#ok<AGROW>
1215 end
1216 end
1217
1218 if strcmp(preType, 'pre') && strcmp(postType, 'post')
1219 if length(preActs) == 1 && length(postActs) == 1
1220 ap = ActivityPrecedence.Serial(preActs{1}, postActs{1});
1221 task.addPrecedence(ap);
1222 end
1223 elseif strcmp(preType, 'pre') && strcmp(postType, 'and-fork')
1224 if ~isempty(preActs) && ~isempty(postActs)
1225 ap = ActivityPrecedence.AndFork(preActs{1}, postActs);
1226 task.addPrecedence(ap);
1227 end
1228 elseif strcmp(preType, 'and-join') && strcmp(postType, 'post')
1229 if ~isempty(preActs) && ~isempty(postActs)
1230 ap = ActivityPrecedence.AndJoin(preActs, postActs{1});
1231 task.addPrecedence(ap);
1232 end
1233 elseif strcmp(preType, 'pre') && strcmp(postType, 'or-fork')
1234 if ~isempty(preActs) && ~isempty(postActs)
1235 probs = [];
1236 if isfield(pd, 'probabilities')
1237 probs = pd.probabilities;
1238 if isstruct(probs), probs = cell2mat(struct2cell(probs)); end
1239 end
1240 if isempty(probs) && ~isempty(postParams)
1241 probs = postParams(:)';
1242 end
1243 if isempty(probs)
1244 n = length(postActs);
1245 probs = ones(1, n) / n;
1246 end
1247 ap = ActivityPrecedence.OrFork(preActs{1}, postActs, probs);
1248 task.addPrecedence(ap);
1249 end
1250 elseif strcmp(preType, 'or-join') && strcmp(postType, 'post')
1251 if ~isempty(preActs) && ~isempty(postActs)
1252 ap = ActivityPrecedence.OrJoin(preActs, postActs{1});
1253 task.addPrecedence(ap);
1254 end
1255 elseif strcmp(preType, 'pre') && strcmp(postType, 'loop')
1256 count = 1.0;
1257 if isfield(pd, 'loopCount'), count = pd.loopCount; end
1258 if count == 1.0 && ~isempty(postParams)
1259 count = postParams(1);
1260 end
1261 if ~isempty(preActs) && ~isempty(postActs)
1262 if length(postActs) > 1
1263 ap = ActivityPrecedence.Loop(preActs{1}, postActs(1:end-1), postActs{end}, count);
1264 else
1265 ap = ActivityPrecedence.Loop(preActs{1}, postActs, count);
1266 end
1267 task.addPrecedence(ap);
1268 end
1269 elseif strcmp(preType, 'pre') && strcmp(postType, 'post-CACHE')
1270 if ~isempty(preActs) && ~isempty(postActs)
1271 ap = ActivityPrecedence.CacheAccess(preActs{1}, postActs);
1272 task.addPrecedence(ap);
1273 end
1274 end
1275 else
1276 % Python schema
1277 ptype = pd.type;
1278 actNames = pd.activities;
1279 if ischar(actNames), actNames = {actNames}; end
1280
1281 % Resolve activity names to objects
1282 actObjs = {};
1283 for ai = 1:length(actNames)
1284 an = actNames{ai};
1285 if act_map.isKey(an)
1286 actObjs{end+1} = act_map(an); %#ok<AGROW>
1287 end
1288 end
1289 if length(actObjs) < 2
1290 continue;
1291 end
1292
1293 switch ptype
1294 case 'Serial'
1295 ap = ActivityPrecedence.Serial(actObjs{:});
1296 task.addPrecedence(ap);
1297 case 'AndFork'
1298 ap = ActivityPrecedence.AndFork(actObjs{1}, actObjs(2:end));
1299 task.addPrecedence(ap);
1300 case 'AndJoin'
1301 ap = ActivityPrecedence.AndJoin(actObjs(1:end-1), actObjs{end});
1302 task.addPrecedence(ap);
1303 case 'OrFork'
1304 probs = [];
1305 if isfield(pd, 'probabilities')
1306 probs = pd.probabilities;
1307 if isstruct(probs), probs = cell2mat(struct2cell(probs)); end
1308 end
1309 if isempty(probs)
1310 n = length(actObjs) - 1;
1311 probs = ones(1, n) / n;
1312 end
1313 ap = ActivityPrecedence.OrFork(actObjs{1}, actObjs(2:end), probs);
1314 task.addPrecedence(ap);
1315 case 'OrJoin'
1316 ap = ActivityPrecedence.OrJoin(actObjs(1:end-1), actObjs{end});
1317 task.addPrecedence(ap);
1318 case 'Loop'
1319 count = 1.0;
1320 if isfield(pd, 'loopCount'), count = pd.loopCount; end
1321 % Check for explicit preActivity field (new format)
1322 if isfield(pd, 'preActivity') && act_map.isKey(pd.preActivity)
1323 preAct = act_map(pd.preActivity);
1324 ap = ActivityPrecedence.Loop(preAct, actObjs, count);
1325 elseif length(actObjs) >= 3
1326 % Legacy format: first is pre, rest is body+end
1327 ap = ActivityPrecedence.Loop(actObjs{1}, actObjs(2:end-1), actObjs{end}, count);
1328 else
1329 ap = ActivityPrecedence.Loop(actObjs{1}, actObjs(2:end), count);
1330 end
1331 task.addPrecedence(ap);
1332 case 'CacheAccess'
1333 if length(actObjs) >= 2
1334 ap = ActivityPrecedence.CacheAccess(actObjs{1}, actObjs(2:end));
1335 task.addPrecedence(ap);
1336 end
1337 end
1338 end
1339 end
1340end
1341end
1342
1343
1344% =========================================================================
1345% Workflow deserialization
1346% =========================================================================
1347
1348function model = json2workflow(data)
1349% Reconstruct a Workflow from decoded JSON struct.
1350
1351modelName = 'workflow';
1352if isfield(data, 'name')
1353 modelName = data.name;
1354end
1355model = Workflow(modelName);
1356
1357% --- Activities ---
1358if isfield(data, 'activities')
1359 acts = data.activities;
1360 if isstruct(acts), acts = num2cell(acts); end
1361 for i = 1:length(acts)
1362 ad = acts{i};
1363 actName = ad.name;
1364 if isfield(ad, 'hostDemand') && ~isempty(ad.hostDemand)
1365 dist = json2dist(ad.hostDemand);
1366 model.addActivity(actName, dist);
1367 else
1368 model.addActivity(actName, 1.0);
1369 end
1370 end
1371end
1372
1373% --- Precedences ---
1374if isfield(data, 'precedences')
1375 precs = data.precedences;
1376 if isstruct(precs), precs = num2cell(precs); end
1377 for i = 1:length(precs)
1378 pd = precs{i};
1379
1380 % preActs
1381 if isfield(pd, 'preActs')
1382 preActs = cellify_string_array(pd.preActs);
1383 else
1384 preActs = {};
1385 end
1386
1387 % postActs
1388 if isfield(pd, 'postActs')
1389 postActs = cellify_string_array(pd.postActs);
1390 else
1391 postActs = {};
1392 end
1393
1394 % preType / postType - convert JAR strings to numeric IDs
1395 preType = ActivityPrecedenceType.PRE_SEQ;
1396 if isfield(pd, 'preType')
1397 preType = str_to_prectype(pd.preType);
1398 end
1399 postType = ActivityPrecedenceType.POST_SEQ;
1400 if isfield(pd, 'postType')
1401 postType = str_to_prectype(pd.postType);
1402 end
1403
1404 % preParams / postParams
1405 preParams = [];
1406 if isfield(pd, 'preParams') && ~isempty(pd.preParams)
1407 preParams = pd.preParams(:)';
1408 end
1409 postParams = [];
1410 if isfield(pd, 'postParams') && ~isempty(pd.postParams)
1411 postParams = pd.postParams(:)';
1412 end
1413
1414 ap = ActivityPrecedence(preActs, postActs, preType, postType, preParams, postParams);
1415 model.addPrecedence(ap);
1416 end
1417end
1418end
1419
1420
1421% =========================================================================
1422% Environment deserialization
1423% =========================================================================
1424
1425function model = json2environment(data, rawJson)
1426% Reconstruct an Environment from decoded JSON struct.
1427
1428modelName = 'env';
1429if isfield(data, 'name')
1430 modelName = data.name;
1431end
1432numStages = 0;
1433if isfield(data, 'numStages')
1434 numStages = data.numStages;
1435end
1436model = Environment(modelName, numStages);
1437
1438% --- Stages ---
1439stageNames = {};
1440if isfield(data, 'stages')
1441 stages = data.stages;
1442 if isstruct(stages), stages = num2cell(stages); end
1443 for i = 1:length(stages)
1444 sd = stages{i};
1445 stageName = sprintf('Stage%d', i);
1446 if isfield(sd, 'name')
1447 stageName = sd.name;
1448 end
1449 stageNames{end+1} = stageName; %#ok<AGROW>
1450
1451 stageType = '';
1452 if isfield(sd, 'type')
1453 stageType = sd.type;
1454 end
1455
1456 stageModel = [];
1457 if isfield(sd, 'model') && ~isempty(sd.model)
1458 stageModel = json2network(sd.model, rawJson);
1459 end
1460
1461 if ~isempty(stageModel)
1462 model.addStage(stageName, stageType, stageModel);
1463 end
1464 end
1465end
1466
1467% --- Transitions ---
1468if isfield(data, 'transitions')
1469 trans = data.transitions;
1470 if isstruct(trans), trans = num2cell(trans); end
1471 for i = 1:length(trans)
1472 td = trans{i};
1473 fromIdx = td.from + 1; % Convert from 0-indexed (JAR) to 1-indexed (MATLAB)
1474 toIdx = td.to + 1; % Convert from 0-indexed (JAR) to 1-indexed (MATLAB)
1475 if isfield(td, 'distribution') && ~isempty(td.distribution)
1476 dist = json2dist(td.distribution);
1477 if ~isempty(dist) && ~isa(dist, 'Disabled')
1478 % Use stage names for MATLAB Environment API
1479 if fromIdx <= length(stageNames) && toIdx <= length(stageNames)
1480 model.addTransition(stageNames{fromIdx}, stageNames{toIdx}, dist);
1481 end
1482 end
1483 end
1484 end
1485end
1486
1487model.init();
1488end
1489
1490
1491% =========================================================================
1492% Distribution deserialization
1493% =========================================================================
1494
1495function dist = json2dist(d)
1496% Convert a JSON distribution struct to a MATLAB Distribution object.
1497if isempty(d)
1498 dist = [];
1499 return;
1500end
1501
1502dtype = d.type;
1503
1504switch dtype
1505 case 'Disabled'
1506 dist = Disabled.getInstance();
1507 return;
1508 case 'Immediate'
1509 dist = Immediate.getInstance();
1510 return;
1511end
1512
1513% Direct params
1514if isfield(d, 'params') && ~isempty(d.params)
1515 p = d.params;
1516 switch dtype
1517 case 'Exp'
1518 lam = p.lambda;
1519 dist = Exp(lam);
1520 return;
1521 case 'Det'
1522 dist = Det(p.value);
1523 return;
1524 case 'Erlang'
1525 dist = Erlang(p.lambda, p.k);
1526 return;
1527 case 'HyperExp'
1528 pv = p.p;
1529 lv = p.lambda;
1530 if isscalar(pv)
1531 dist = HyperExp(pv, lv(1), lv(2));
1532 else
1533 dist = HyperExp(pv(1), lv(1), lv(2));
1534 end
1535 return;
1536 case 'Gamma'
1537 dist = Gamma(p.alpha, p.beta);
1538 return;
1539 case 'Lognormal'
1540 dist = Lognormal(p.mu, p.sigma);
1541 return;
1542 case 'Uniform'
1543 dist = Uniform(p.a, p.b);
1544 return;
1545 case 'Zipf'
1546 dist = Zipf(p.s, p.n);
1547 return;
1548 case 'Pareto'
1549 dist = Pareto(p.alpha, p.scale);
1550 return;
1551 case 'Weibull'
1552 % JSON: alpha = scale (getParam(1)), beta = shape (getParam(2))
1553 % Constructor: Weibull(shape, scale)
1554 dist = Weibull(p.beta, p.alpha);
1555 return;
1556 case 'Normal'
1557 dist = Normal(p.mu, p.sigma);
1558 return;
1559 case 'Geometric'
1560 dist = Geometric(p.p);
1561 return;
1562 case 'Binomial'
1563 dist = Binomial(p.n, p.p);
1564 return;
1565 case 'Poisson'
1566 dist = Poisson(p.lambda);
1567 return;
1568 case 'Bernoulli'
1569 dist = Bernoulli(p.p);
1570 return;
1571 case 'DiscreteUniform'
1572 dist = DiscreteUniform(p.min, p.max);
1573 return;
1574 case 'DiscreteSampler'
1575 pv = p.p(:)';
1576 xv = p.x(:)';
1577 dist = DiscreteSampler(pv, xv);
1578 return;
1579 case 'Coxian'
1580 mu = p.mu(:)';
1581 phi = p.phi(:)';
1582 dist = Coxian(mu, phi);
1583 return;
1584 case 'MMPP2'
1585 dist = MMPP2(p.lambda0, p.lambda1, p.sigma0, p.sigma1);
1586 return;
1587 case 'Replayer'
1588 % Try to load from file first
1589 if isfield(p, 'fileName') && exist(p.fileName, 'file') == 2
1590 dist = Replayer(p.fileName);
1591 return;
1592 end
1593 % Fallback to APH if available
1594 if isfield(d, 'ph') && ~isempty(d.ph)
1595 ph = d.ph;
1596 alpha = ph.alpha;
1597 T = ph.T;
1598 if ~isvector(alpha), alpha = alpha(:)'; end
1599 dist = PH(alpha, T);
1600 return;
1601 end
1602 % Fallback to Exp with stored mean
1603 m = 1.0;
1604 if isfield(p, 'mean'), m = p.mean; end
1605 dist = Exp(1.0 / m);
1606 return;
1607 end
1608end
1609
1610% Prior distribution (mixture of alternatives with prior probabilities)
1611if strcmp(dtype, 'Prior')
1612 if isfield(d, 'distributions') && isfield(d, 'probabilities')
1613 altJsons = d.distributions;
1614 probs = d.probabilities;
1615 if ~iscell(altJsons)
1616 % jsondecode may return struct array instead of cell
1617 altJsons = num2cell(altJsons);
1618 end
1619 alts = cell(1, length(altJsons));
1620 for ai = 1:length(altJsons)
1621 alts{ai} = json2dist(altJsons{ai});
1622 end
1623 probs = probs(:)';
1624 dist = Prior(alts, probs);
1625 return;
1626 end
1627end
1628
1629% PH/APH representation
1630if isfield(d, 'ph') && ~isempty(d.ph)
1631 ph = d.ph;
1632 alpha = ph.alpha;
1633 T = ph.T;
1634 alpha = alpha(:)'; % Ensure row vector (jsondecode returns column vectors)
1635 if strcmp(dtype, 'APH')
1636 dist = APH(alpha, T);
1637 else
1638 dist = PH(alpha, T);
1639 end
1640 return;
1641end
1642
1643% MAP representation
1644if isfield(d, 'map') && ~isempty(d.map)
1645 mapSpec = d.map;
1646 D0 = mapSpec.D0;
1647 D1 = mapSpec.D1;
1648 dist = MAP(D0, D1);
1649 return;
1650end
1651
1652% Fit specification
1653if isfield(d, 'fit') && ~isempty(d.fit)
1654 fit = d.fit;
1655 method = fit.method;
1656 switch method
1657 case 'fitMean'
1658 m = fit.mean;
1659 switch dtype
1660 case 'Exp'
1661 dist = Exp(1.0 / m);
1662 case 'Det'
1663 dist = Det(m);
1664 otherwise
1665 dist = Exp(1.0 / m);
1666 end
1667 return;
1668 case 'fitMeanAndSCV'
1669 m = fit.mean;
1670 scv = fit.scv;
1671 switch dtype
1672 case 'Erlang'
1673 dist = Erlang.fitMeanAndSCV(m, scv);
1674 case 'HyperExp'
1675 dist = HyperExp.fitMeanAndSCV(m, scv);
1676 otherwise
1677 dist = Exp(1.0 / m);
1678 end
1679 return;
1680 case 'fitMeanAndOrder'
1681 m = fit.mean;
1682 order = fit.order;
1683 switch dtype
1684 case 'Erlang'
1685 dist = Erlang.fitMeanAndOrder(m, order);
1686 otherwise
1687 dist = Exp(1.0 / m);
1688 end
1689 return;
1690 end
1691end
1692
1693% Fallback
1694dist = Exp(1.0);
1695end
1696
1697
1698% =========================================================================
1699% Routing parser (handles comma keys in JSON)
1700% =========================================================================
1701
1702function entries = parse_routing_keys(rawJson, class_map, node_map)
1703% Parse routing matrix from raw JSON text to handle keys with commas.
1704% Returns a cell array of structs with fields:
1705% className1, className2, fromNode, toNode, prob
1706entries = {};
1707
1708% Build reverse mapping: jsondecode-sanitized name -> original node name
1709% jsondecode uses matlab.lang.makeValidName which replaces spaces etc.
1710nodeNames = node_map.keys();
1711sanitized_map = containers.Map();
1712for ni = 1:length(nodeNames)
1713 origName = nodeNames{ni};
1714 sanitized = matlab.lang.makeValidName(origName);
1715 sanitized_map(sanitized) = origName;
1716end
1717
1718classNames = class_map.keys();
1719
1720% For each pair of class names, try to find the corresponding key in the JSON
1721for ri = 1:length(classNames)
1722 for si = 1:length(classNames)
1723 cn1 = classNames{ri};
1724 cn2 = classNames{si};
1725 keyStr = ['"', cn1, ',', cn2, '"'];
1726
1727 % Find this key in the raw JSON
1728 pos = strfind(rawJson, keyStr);
1729 if isempty(pos)
1730 continue;
1731 end
1732
1733 % For each occurrence, extract the nested from -> to -> prob structure
1734 for pidx = 1:length(pos)
1735 startPos = pos(pidx) + length(keyStr);
1736 % Skip whitespace and colon
1737 idx = startPos;
1738 while idx <= length(rawJson) && (rawJson(idx) == ' ' || rawJson(idx) == ':' || rawJson(idx) == newline || rawJson(idx) == char(13) || rawJson(idx) == char(9))
1739 idx = idx + 1;
1740 end
1741 if idx > length(rawJson) || rawJson(idx) ~= '{'
1742 continue;
1743 end
1744 % Extract the JSON object using brace counting
1745 objStr = extract_json_object(rawJson, idx);
1746 if isempty(objStr)
1747 continue;
1748 end
1749 % Parse the from -> to -> prob structure
1750 try
1751 fromTo = jsondecode(objStr);
1752 fromNames = fieldnames(fromTo);
1753 for fi = 1:length(fromNames)
1754 fromField = fromNames{fi};
1755 toStruct = fromTo.(fromField);
1756 toNames = fieldnames(toStruct);
1757 % Resolve sanitized field names back to original node names
1758 if sanitized_map.isKey(fromField)
1759 fromName = sanitized_map(fromField);
1760 else
1761 fromName = fromField;
1762 end
1763 for ti = 1:length(toNames)
1764 toField = toNames{ti};
1765 prob = toStruct.(toField);
1766 if sanitized_map.isKey(toField)
1767 toName = sanitized_map(toField);
1768 else
1769 toName = toField;
1770 end
1771 % Verify names exist in the model
1772 if node_map.isKey(fromName) && node_map.isKey(toName)
1773 re = struct();
1774 re.className1 = cn1;
1775 re.className2 = cn2;
1776 re.fromNode = fromName;
1777 re.toNode = toName;
1778 re.prob = prob;
1779 entries{end+1} = re; %#ok<AGROW>
1780 end
1781 end
1782 end
1783 catch
1784 % Skip if parsing fails
1785 end
1786 end
1787 end
1788end
1789end
1790
1791
1792function objStr = extract_json_object(str, startIdx)
1793% Extract a JSON object string starting at startIdx (must be '{').
1794if str(startIdx) ~= '{'
1795 objStr = '';
1796 return;
1797end
1798depth = 0;
1799inString = false;
1800escaped = false;
1801for i = startIdx:length(str)
1802 c = str(i);
1803 if escaped
1804 escaped = false;
1805 continue;
1806 end
1807 if c == '\'
1808 escaped = true;
1809 continue;
1810 end
1811 if c == '"'
1812 inString = ~inString;
1813 continue;
1814 end
1815 if ~inString
1816 if c == '{'
1817 depth = depth + 1;
1818 elseif c == '}'
1819 depth = depth - 1;
1820 if depth == 0
1821 objStr = str(startIdx:i);
1822 return;
1823 end
1824 end
1825 end
1826end
1827objStr = '';
1828end
1829
1830
1831% =========================================================================
1832% Helper functions
1833% =========================================================================
1834
1835function id = str_to_sched_id(str)
1836% Map scheduling string to SchedStrategy numeric ID.
1837switch upper(str)
1838 case 'INF', id = SchedStrategy.INF;
1839 case 'FCFS', id = SchedStrategy.FCFS;
1840 case 'LCFS', id = SchedStrategy.LCFS;
1841 case 'LCFSPR', id = SchedStrategy.LCFSPR;
1842 case 'PS', id = SchedStrategy.PS;
1843 case 'DPS', id = SchedStrategy.DPS;
1844 case 'GPS', id = SchedStrategy.GPS;
1845 case 'SIRO', id = SchedStrategy.SIRO;
1846 case 'RAND', id = SchedStrategy.SIRO; % alias
1847 case 'SJF', id = SchedStrategy.SJF;
1848 case 'LJF', id = SchedStrategy.LJF;
1849 case 'SEPT', id = SchedStrategy.SEPT;
1850 case 'LEPT', id = SchedStrategy.LEPT;
1851 case 'HOL', id = SchedStrategy.HOL;
1852 case 'FCFSPRIO', id = SchedStrategy.FCFSPRIO;
1853 case 'FORK', id = SchedStrategy.FORK;
1854 case 'EXT', id = SchedStrategy.EXT;
1855 case 'REF', id = SchedStrategy.REF;
1856 case 'POLLING', id = SchedStrategy.POLLING;
1857 case 'PSPRIO', id = SchedStrategy.PSPRIO;
1858 case 'DPSPRIO', id = SchedStrategy.DPSPRIO;
1859 case 'GPSPRIO', id = SchedStrategy.GPSPRIO;
1860 otherwise, id = SchedStrategy.FCFS;
1861end
1862end
1863
1864
1865function id = str_to_repl_id(str)
1866% Map replacement strategy string to ReplacementStrategy numeric ID.
1867switch upper(str)
1868 case 'LRU', id = ReplacementStrategy.LRU;
1869 case 'FIFO', id = ReplacementStrategy.FIFO;
1870 case 'RR', id = ReplacementStrategy.RR;
1871 case 'SFIFO', id = ReplacementStrategy.SFIFO;
1872 otherwise, id = ReplacementStrategy.LRU;
1873end
1874end
1875
1876
1877function id = str_to_prectype(str)
1878% Map JAR precedence type string to MATLAB ActivityPrecedenceType numeric ID.
1879switch str
1880 case 'pre', id = ActivityPrecedenceType.PRE_SEQ;
1881 case 'pre-AND', id = ActivityPrecedenceType.PRE_AND;
1882 case 'pre-OR', id = ActivityPrecedenceType.PRE_OR;
1883 case 'post', id = ActivityPrecedenceType.POST_SEQ;
1884 case 'post-AND', id = ActivityPrecedenceType.POST_AND;
1885 case 'post-OR', id = ActivityPrecedenceType.POST_OR;
1886 case 'post-LOOP', id = ActivityPrecedenceType.POST_LOOP;
1887 case 'post-CACHE', id = ActivityPrecedenceType.POST_CACHE;
1888 otherwise, id = ActivityPrecedenceType.PRE_SEQ;
1889end
1890end
1891
1892
1893function id = str_to_droprule(str)
1894% Map drop rule string to DropStrategy numeric ID.
1895switch str
1896 case 'drop', id = DropStrategy.DROP;
1897 case 'waitingQueue', id = DropStrategy.WAITQ;
1898 case 'blockingAfterService', id = DropStrategy.BAS;
1899 case 'retrial', id = DropStrategy.RETRIAL;
1900 case 'retrialWithLimit', id = DropStrategy.RETRIAL_WITH_LIMIT;
1901 otherwise, id = DropStrategy.WAITQ;
1902end
1903end
1904
1905
1906function c = cellify_string_array(arr)
1907% Convert a JSON string array (which may be decoded as a char, cell, or
1908% struct array) into a cell array of character vectors.
1909if ischar(arr)
1910 c = {arr};
1911elseif isstring(arr)
1912 c = cellstr(arr);
1913elseif iscell(arr)
1914 c = arr;
1915else
1916 % jsondecode can return a struct array or char matrix for string arrays
1917 c = cellstr(arr);
1918end
1919end
Definition mmt.m:124