1function model = linemodel_load(filename)
2% LINEMODEL_LOAD Load a LINE model (Network or LayeredNetwork) from JSON.
4% MODEL = LINEMODEL_LOAD(FILENAME) loads a model from the specified JSON
5% file (conforming to line-model.schema.json) and returns a Network or
6% LayeredNetwork
object.
9% filename - path to a .json file
12% model - Network or LayeredNetwork
object
15% model = linemodel_load('mm1.json');
16% solver = SolverMVA(model);
17% AvgTable = solver.getAvgTable();
19% Copyright (c) 2012-2026, Imperial College London
22jsonText = fileread(filename);
23doc = jsondecode(jsonText);
25if ~isfield(doc, 'model')
26 error('linemodel_load:noModel', 'JSON file does not contain a "model" field.');
34 model = json2network(data, jsonText);
36 model = json2layered(data);
38 error('linemodel_load:unknownType', 'Unsupported model type: %s', mtype);
43% =========================================================================
44% Network deserialization
45% =========================================================================
47function model = json2network(data, rawJson)
48% Reconstruct a Network from decoded JSON struct.
49% rawJson
is the original text, used for parsing routing keys with commas.
52if isfield(data, 'name')
53 modelName = data.name;
55model = Network(modelName);
57% --- Create
nodes (before
classes, since ClosedClass needs refstat) ---
59if isfield(data,
'nodes')
73 node = create_node(model, nd, nd_name, nd_type);
74 nodeList{end+1} = node; %#ok<AGROW>
77node_map = containers.Map();
78for i = 1:length(nodeList)
79 node_map(nodeList{i}.name) = nodeList{i};
82% --- Deferred node linking (Fork/Join, Fork tasksPerLink) ---
83if isfield(data,
'nodes')
86 nds2 = num2cell(nds2);
88 for i = 1:length(nds2)
91 node2 = node_map(nd_name2);
92 % Join: link to paired Fork
93 if isfield(nd2,
'forkNode') && isa(node2,
'Join')
94 if node_map.isKey(nd2.forkNode)
95 node2.joinOf = node_map(nd2.forkNode);
98 % Fork: set tasksPerLink
99 if isfield(nd2, 'tasksPerLink') && isa(node2, 'Fork')
100 node2.setTasksPerLink(nd2.tasksPerLink);
107if isfield(data,
'classes')
112 for i = 1:length(cls)
119 if isfield(cd,
'priority'), prio = cd.priority; end
120 jc = OpenClass(model, cname, prio);
124 if isfield(cd,
'refNode') && node_map.isKey(cd.refNode)
125 refNode = node_map(cd.refNode);
128 if isfield(cd,
'priority'), prio = cd.priority; end
130 error(
'linemodel_load:noRefNode', ...
131 'ClosedClass "%s" has no valid refNode.', cname);
133 jc = ClosedClass(model, cname, pop, refNode, prio);
135 jc = OpenClass(model, cname);
137 classesList{end+1} = jc; %#ok<AGROW>
140class_map = containers.Map();
141for i = 1:length(classesList)
142 class_map(classesList{i}.name) = classesList{i};
145% --- Set service/arrival distributions ---
146if isfield(data,
'nodes')
151 for i = 1:length(nds)
154 node = node_map(nd_name);
156 if isfield(nd,
'service') && ~isempty(nd.service)
158 svcFields = fieldnames(svc);
159 for f = 1:length(svcFields)
160 cname = svcFields{f};
161 distJson = svc.(cname);
162 if ~class_map.isKey(cname)
165 jc = class_map(cname);
166 dist = json2dist(distJson);
168 if isa(node,
'Source')
169 node.setArrival(jc, dist);
170 elseif isa(node, 'Queue') || isa(node, 'Delay')
171 node.setService(jc, dist);
177 % ClassSwitch matrix (dict format: classSwitchMatrix)
178 if isfield(nd, 'classSwitchMatrix') && isa(node, 'ClassSwitch')
179 csm_data = nd.classSwitchMatrix;
183 class_idx = containers.Map();
185 class_idx(
classes{ci}.name) = ci;
187 fromFields = fieldnames(csm_data);
188 for fi = 1:length(fromFields)
189 fromName = fromFields{fi};
190 if ~class_idx.isKey(fromName),
continue; end
191 ri = class_idx(fromName);
192 toStruct = csm_data.(fromName);
193 toFields = fieldnames(toStruct);
194 for ti = 1:length(toFields)
195 toName = toFields{ti};
196 if ~class_idx.isKey(toName),
continue; end
197 ci = class_idx(toName);
198 mat(ri, ci) = toStruct.(toName);
201 node.server = node.server.updateClassSwitch(mat);
202 % Legacy 2D array format: csMatrix (from older JAR saves)
203 elseif isfield(nd,
'csMatrix') && isa(node,
'ClassSwitch')
208 node.server = node.server.updateClassSwitch(mat);
211 % DPS scheduling parameters
212 if isfield(nd, 'schedParams') && isa(node, 'Queue')
214 spFields = fieldnames(sp);
215 for sfi = 1:length(spFields)
216 cname = spFields{sfi};
217 if class_map.isKey(cname)
218 jc = class_map(cname);
220 for ki = 1:length(classesList)
221 if strcmp(classesList{ki}.name, cname)
227 node.schedStrategyPar(cidx) = sp.(cname);
233 % Cache hit/miss
class mappings and popularity distributions
234 if isa(node, 'Cache') && isfield(nd,
'cache')
237 if isfield(cc, 'hitClass')
238 hcData = cc.hitClass;
239 hcFields = fieldnames(hcData);
240 for hci = 1:length(hcFields)
241 inName = hcFields{hci};
242 outName = hcData.(inName);
243 if class_map.isKey(inName) && class_map.isKey(outName)
244 node.setHitClass(class_map(inName), class_map(outName));
249 if isfield(cc, 'missClass')
250 mcData = cc.missClass;
251 mcFields = fieldnames(mcData);
252 for mci = 1:length(mcFields)
253 inName = mcFields{mci};
254 outName = mcData.(inName);
255 if class_map.isKey(inName) && class_map.isKey(outName)
256 node.setMissClass(class_map(inName), class_map(outName));
260 % Popularity distributions (setRead)
261 if isfield(cc,
'popularity')
262 popData = cc.popularity;
263 popFields = fieldnames(popData);
264 for pfi = 1:length(popFields)
265 cname = popFields{pfi};
266 if class_map.isKey(cname)
267 popDist = json2dist(popData.(cname));
269 node.setRead(class_map(cname), popDist);
278% --- Configure Transition modes ---
279if isfield(data,
'nodes')
282 nds3 = num2cell(nds3);
284 for i = 1:length(nds3)
286 if ~isfield(nd3,
'modes'),
continue; end
287 if ~strcmp(nd3.type,
'Transition'),
continue; end
288 tnode = node_map(nd3.name);
289 modesData = nd3.modes;
290 if isstruct(modesData)
291 modesData = num2cell(modesData);
293 for mi = 1:length(modesData)
296 if isfield(md,
'name'), modeName = md.name; end
297 mode = tnode.addMode(modeName);
299 if isfield(md,
'distribution') && ~isempty(md.distribution)
300 dist = json2dist(md.distribution);
302 tnode.setDistribution(mode, dist);
306 if isfield(md, 'timingStrategy')
307 if strcmp(md.timingStrategy, 'IMMEDIATE')
308 tnode.setTimingStrategy(mode, TimingStrategy.IMMEDIATE);
310 tnode.setTimingStrategy(mode, TimingStrategy.TIMED);
314 if isfield(md, 'numServers') && md.numServers > 1
315 tnode.setNumberOfServers(mode, md.numServers);
318 if isfield(md, 'firingPriority')
319 tnode.setFiringPriorities(mode, md.firingPriority);
322 if isfield(md, 'firingWeight')
323 tnode.setFiringWeights(mode, md.firingWeight);
325 % Enabling conditions
326 if isfield(md, 'enablingConditions')
327 ecList = md.enablingConditions;
328 if isstruct(ecList), ecList = num2cell(ecList); end
329 for ei = 1:length(ecList)
331 if node_map.isKey(ec.node) && class_map.isKey(ec.class)
332 tnode.setEnablingConditions(mode, class_map(ec.class), node_map(ec.node), ec.count);
336 % Inhibiting conditions
337 if isfield(md,
'inhibitingConditions')
338 icList = md.inhibitingConditions;
339 if isstruct(icList), icList = num2cell(icList); end
340 for ii = 1:length(icList)
342 if node_map.isKey(ic.node) && class_map.isKey(ic.class)
343 tnode.setInhibitingConditions(mode, class_map(ic.class), node_map(ic.node), ic.count);
348 if isfield(md,
'firingOutcomes')
349 foList = md.firingOutcomes;
350 if isstruct(foList), foList = num2cell(foList); end
351 for fi = 1:length(foList)
353 if node_map.isKey(fo.node) && class_map.isKey(fo.class)
354 tnode.setFiringOutcome(mode, class_map(fo.class), node_map(fo.node), fo.count);
362% --- Build routing ---
363if isfield(data,
'routing') && isfield(data.routing,
'type') && strcmp(data.routing.type,
'matrix')
364 P = model.initRoutingMatrix();
365 K = length(classesList);
366 M = length(nodeList);
368 % Build node/class index maps
369 nodeIdx = containers.Map();
371 nodeIdx(nodeList{i}.name) = i;
373 classIdx = containers.Map();
375 classIdx(classesList{i}.name) = i;
378 % Parse routing keys from raw JSON to preserve commas
379 routingEntries = parse_routing_keys(rawJson, class_map, node_map);
381 for e = 1:length(routingEntries)
382 re = routingEntries{e};
383 r = classIdx(re.className1);
384 s = classIdx(re.className2);
385 ii = nodeIdx(re.fromNode);
386 jj = nodeIdx(re.toNode);
387 P{r,s}(ii, jj) = re.prob;
395function node = create_node(model, nd, name, ntype)
396% Create a node from JSON data.
399 node = Source(model, name);
401 node = Sink(model, name);
403 node = Delay(model, name);
406 if isfield(nd,
'scheduling')
407 schedStr = nd.scheduling;
409 schedId = str_to_sched_id(schedStr);
410 node = Queue(model, name, schedId);
411 if isfield(nd, 'servers') && nd.servers > 1
412 node.setNumberOfServers(nd.servers);
414 if isfield(nd, 'buffer') && isfinite(nd.buffer)
415 node.cap = nd.buffer;
418 node = Fork(model, name);
420 node = Join(model, name);
422 node = Router(model, name);
424 node = ClassSwitch(model, name);
427 if isfield(nd, 'cache')
431 if isfield(cc, 'items'), nitems = cc.items; end
433 if isfield(cc, 'capacity'), cap = cc.capacity; end
435 if isfield(cc, 'replacement'), replStr = cc.replacement; end
436 replId = str_to_repl_id(replStr);
437 node = Cache(model, name, nitems, cap, replId);
439 node = Place(model, name);
441 node = Transition(model, name);
443 node = Queue(model, name, SchedStrategy.FCFS);
448% =========================================================================
449% LayeredNetwork deserialization
450% =========================================================================
452function model = json2layered(data)
453% Reconstruct a LayeredNetwork from decoded JSON struct.
456if isfield(data, 'name')
457 modelName = data.name;
459model = LayeredNetwork(modelName);
462proc_map = containers.Map();
463if isfield(data, 'processors')
464 procs = data.processors;
465 if isstruct(procs), procs = num2cell(procs); end
466 for i = 1:length(procs)
470 if isfield(pd,
'multiplicity'), mult = pd.multiplicity; end
472 if isfield(pd,
'scheduling'), schedStr = pd.scheduling; end
473 schedId = str_to_sched_id(schedStr);
475 if isfield(pd,
'quantum'), quantum = pd.quantum; end
477 if isfield(pd,
'speedFactor'), sf = pd.speedFactor; end
478 proc = Host(model, pname, mult, schedId, quantum, sf);
479 if isfield(pd,
'replication') && pd.replication > 1
480 proc.setReplication(pd.replication);
482 proc_map(pname) = proc;
487task_map = containers.Map();
488if isfield(data,
'tasks')
490 if isstruct(tsks), tsks = num2cell(tsks); end
491 for i = 1:length(tsks)
495 if isfield(td,
'multiplicity'), mult = td.multiplicity; end
497 if isfield(td,
'scheduling'), schedStr = td.scheduling; end
498 schedId = str_to_sched_id(schedStr);
499 task = Task(model, tname, mult, schedId);
500 % Assign to processor
501 if isfield(td,
'processor') && proc_map.isKey(td.processor)
502 task.on(proc_map(td.processor));
505 if isfield(td,
'thinkTime')
506 dist = json2dist(td.thinkTime);
508 task.setThinkTime(dist);
512 if isfield(td, 'fanIn') && isstruct(td.fanIn)
513 fnames = fieldnames(td.fanIn);
514 for fi = 1:length(fnames)
515 task.setFanIn(fnames{fi}, td.fanIn.(fnames{fi}));
519 if isfield(td,
'fanOut') && isstruct(td.fanOut)
520 fnames = fieldnames(td.fanOut);
521 for fi = 1:length(fnames)
522 task.setFanOut(fnames{fi}, td.fanOut.(fnames{fi}));
526 if isfield(td,
'replication') && td.replication > 1
527 task.setReplication(td.replication);
529 task_map(tname) = task;
534entry_map = containers.Map();
535if isfield(data,
'entries')
537 if isstruct(ents), ents = num2cell(ents); end
538 for i = 1:length(ents)
541 entry = Entry(model, ename);
542 if isfield(ed,
'task') && task_map.isKey(ed.task)
543 entry.on(task_map(ed.task));
545 entry_map(ename) = entry;
550act_map = containers.Map();
551if isfield(data,
'activities')
552 acts = data.activities;
553 if isstruct(acts), acts = num2cell(acts); end
554 for i = 1:length(acts)
559 hd = GlobalConstants.FineTol;
560 if isfield(ad,
'hostDemand')
561 hdDist = json2dist(ad.hostDemand);
569 if isfield(ad, 'boundTo')
573 act = Activity(model, aname, hd, bte);
576 if isfield(ad, 'task') && task_map.isKey(ad.task)
577 act.on(task_map(ad.task));
581 if isfield(ad, 'repliesTo') && entry_map.isKey(ad.repliesTo)
582 act.repliesTo(entry_map(ad.repliesTo));
586 if isfield(ad, 'synchCalls')
588 if isstruct(scs), scs = num2cell(scs); end
589 for j = 1:length(scs)
593 if isfield(sc,
'mean'), meanCalls = sc.mean; end
594 if entry_map.isKey(ename)
595 act.synchCall(entry_map(ename), meanCalls);
601 if isfield(ad,
'asynchCalls')
602 acs = ad.asynchCalls;
603 if isstruct(acs), acs = num2cell(acs); end
604 for j = 1:length(acs)
608 if isfield(ac,
'mean'), meanCalls = ac.mean; end
609 if entry_map.isKey(ename)
610 act.asynchCall(entry_map(ename), meanCalls);
615 act_map(aname) = act;
620if isfield(data,
'precedences')
621 precs = data.precedences;
622 if isstruct(precs), precs = num2cell(precs); end
623 for i = 1:length(precs)
625 if ~isfield(pd,
'task') || ~task_map.isKey(pd.task)
628 task = task_map(pd.task);
630 actNames = pd.activities;
631 if ischar(actNames), actNames = {actNames}; end
633 % Resolve activity names to objects
635 for ai = 1:length(actNames)
638 actObjs{end+1} = act_map(an); %#ok<AGROW>
641 if length(actObjs) < 2
647 ap = ActivityPrecedence.Serial(actObjs{:});
648 task.addPrecedence(ap);
650 ap = ActivityPrecedence.AndFork(actObjs{1}, actObjs(2:end));
651 task.addPrecedence(ap);
653 ap = ActivityPrecedence.AndJoin(actObjs(1:end-1), actObjs{end});
654 task.addPrecedence(ap);
657 if isfield(pd,
'probabilities')
658 probs = pd.probabilities;
659 if isstruct(probs), probs = cell2mat(struct2cell(probs)); end
662 n = length(actObjs) - 1;
663 probs = ones(1, n) / n;
665 ap = ActivityPrecedence.OrFork(actObjs{1}, actObjs(2:end), probs);
666 task.addPrecedence(ap);
668 ap = ActivityPrecedence.OrJoin(actObjs(1:end-1), actObjs{end});
669 task.addPrecedence(ap);
672 if isfield(pd,
'loopCount'), count = pd.loopCount; end
673 % Loop(preAct, postActs, counts)
674 % preAct = first, loop body = middle, end = last
675 if length(actObjs) >= 3
676 ap = ActivityPrecedence.Loop(actObjs{1}, actObjs(2:end-1), actObjs{end}, count);
678 ap = ActivityPrecedence.Loop(actObjs{1}, actObjs(2:end), count);
680 task.addPrecedence(ap);
687% =========================================================================
688% Distribution deserialization
689% =========================================================================
691function dist = json2dist(d)
692% Convert a JSON distribution
struct to a MATLAB Distribution object.
702 dist = Disabled.getInstance();
705 dist = Immediate.getInstance();
710if isfield(d,
'params') && ~isempty(d.params)
721 dist = Erlang(p.lambda, p.k);
727 dist = HyperExp(pv, lv(1), lv(2));
729 dist = HyperExp(pv(1), lv(1), lv(2));
733 dist = Gamma(p.alpha, p.beta);
736 dist = Lognormal(p.mu, p.sigma);
739 dist = Uniform(p.a, p.b);
742 dist = Zipf(p.s, p.n);
745 dist = Pareto(p.alpha, p.scale);
747 case 'DiscreteSampler'
750 dist = DiscreteSampler(pv, xv);
756if isfield(d, 'ph') && ~isempty(d.ph)
760 if ~isvector(alpha), alpha = alpha(:)'; end
766if isfield(d, '
map') && ~isempty(d.
map)
775if isfield(d, 'fit') && ~isempty(d.fit)
795 dist = Erlang.fitMeanAndSCV(m, scv);
797 dist = HyperExp.fitMeanAndSCV(m, scv);
802 case 'fitMeanAndOrder'
807 dist = Erlang.fitMeanAndOrder(m, order);
820% =========================================================================
821% Routing parser (handles comma keys in JSON)
822% =========================================================================
824function entries = parse_routing_keys(rawJson, class_map, node_map)
825% Parse routing matrix from raw JSON text to handle keys with commas.
826% Returns a cell array of structs with fields:
827% className1, className2, fromNode, toNode, prob
830% Build reverse mapping: jsondecode-sanitized name -> original node name
831% jsondecode uses matlab.lang.makeValidName which replaces spaces etc.
832nodeNames = node_map.keys();
833sanitized_map = containers.Map();
834for ni = 1:length(nodeNames)
835 origName = nodeNames{ni};
836 sanitized = matlab.lang.makeValidName(origName);
837 sanitized_map(sanitized) = origName;
840classNames = class_map.keys();
842% For each pair of
class names, try to find the corresponding key in the JSON
843for ri = 1:length(classNames)
844 for si = 1:length(classNames)
845 cn1 = classNames{ri};
846 cn2 = classNames{si};
847 keyStr = [
'"', cn1,
',', cn2,
'"'];
849 % Find
this key in the raw JSON
850 pos = strfind(rawJson, keyStr);
855 % For each occurrence, extract the nested from -> to -> prob structure
856 for pidx = 1:length(pos)
857 startPos = pos(pidx) + length(keyStr);
858 % Skip whitespace and colon
860 while idx <= length(rawJson) && (rawJson(idx) ==
' ' || rawJson(idx) ==
':' || rawJson(idx) == newline || rawJson(idx) == char(13) || rawJson(idx) == char(9))
863 if idx > length(rawJson) || rawJson(idx) ~=
'{'
866 % Extract the JSON
object using brace counting
867 objStr = extract_json_object(rawJson, idx);
871 % Parse the from -> to -> prob structure
873 fromTo = jsondecode(objStr);
874 fromNames = fieldnames(fromTo);
875 for fi = 1:length(fromNames)
876 fromField = fromNames{fi};
877 toStruct = fromTo.(fromField);
878 toNames = fieldnames(toStruct);
879 % Resolve sanitized field names back to original node names
880 if sanitized_map.isKey(fromField)
881 fromName = sanitized_map(fromField);
883 fromName = fromField;
885 for ti = 1:length(toNames)
886 toField = toNames{ti};
887 prob = toStruct.(toField);
888 if sanitized_map.isKey(toField)
889 toName = sanitized_map(toField);
893 % Verify names exist in the model
894 if node_map.isKey(fromName) && node_map.isKey(toName)
898 re.fromNode = fromName;
901 entries{end+1} = re; %#ok<AGROW>
906 % Skip
if parsing fails
914function objStr = extract_json_object(str, startIdx)
915% Extract a JSON
object string starting at startIdx (must be
'{').
916if str(startIdx) ~=
'{'
923for i = startIdx:length(str)
934 inString = ~inString;
943 objStr = str(startIdx:i);
953% =========================================================================
955% =========================================================================
957function
id = str_to_sched_id(str)
958% Map scheduling
string to SchedStrategy numeric ID.
960 case 'INF',
id = SchedStrategy.INF;
961 case 'FCFS',
id = SchedStrategy.FCFS;
962 case 'LCFS',
id = SchedStrategy.LCFS;
963 case 'LCFSPR',
id = SchedStrategy.LCFSPR;
964 case 'PS',
id = SchedStrategy.PS;
965 case 'DPS',
id = SchedStrategy.DPS;
966 case 'GPS',
id = SchedStrategy.GPS;
967 case 'SIRO',
id = SchedStrategy.SIRO;
968 case 'RAND',
id = SchedStrategy.SIRO; % alias
969 case 'SJF',
id = SchedStrategy.SJF;
970 case 'LJF',
id = SchedStrategy.LJF;
971 case 'SEPT',
id = SchedStrategy.SEPT;
972 case 'LEPT',
id = SchedStrategy.LEPT;
973 case 'HOL',
id = SchedStrategy.HOL;
974 case 'FCFSPRIO',
id = SchedStrategy.FCFSPRIO;
975 case 'FORK',
id = SchedStrategy.FORK;
976 case 'EXT',
id = SchedStrategy.EXT;
977 case 'REF',
id = SchedStrategy.REF;
978 case 'POLLING',
id = SchedStrategy.POLLING;
979 case 'PSPRIO',
id = SchedStrategy.PSPRIO;
980 case 'DPSPRIO',
id = SchedStrategy.DPSPRIO;
981 case 'GPSPRIO',
id = SchedStrategy.GPSPRIO;
982 otherwise,
id = SchedStrategy.FCFS;
987function
id = str_to_repl_id(str)
988% Map replacement strategy
string to ReplacementStrategy numeric ID.
990 case 'LRU',
id = ReplacementStrategy.LRU;
991 case 'FIFO',
id = ReplacementStrategy.FIFO;
992 case 'RR',
id = ReplacementStrategy.RR;
993 case 'SFIFO',
id = ReplacementStrategy.SFIFO;
994 otherwise,
id = ReplacementStrategy.LRU;