Created
December 31, 2019 15:11
-
-
Save wires/48e7be45a434cd19c9c591804afb4b71 to your computer and use it in GitHub Desktop.
petrinet runner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// list of transitions | |
// places start at index 1, not zero | |
// doesn't support multiple tokens in same place / 1-safe | |
net = [ | |
[1],[2,3], | |
[2],[4], | |
[3],[5], | |
[4,5],[6] | |
] | |
let all = xs => xs.reduce((x, acc) => acc && x, true, xs) | |
function engine (net) { | |
// nr of transitions | |
let T = net.length / 2 | |
// nr of places (maximum index used in array) | |
let P = Math.max.apply(Math, net.flat()) | |
// new empty state | |
let marking = new Array(P).fill(0) | |
// assume place 1 is the initial marking | |
marking[0] = 1 | |
// retrieving a transition | |
let transition = i => { | |
let idx = ((i - 1) % T) * 2 | |
let consume = net[idx] | |
let produce = net[idx + 1] | |
let enabled = () => { | |
let haz = consume.map(p => marking[p - 1] > 0) | |
return all(haz) | |
} | |
let fire = () => { | |
if (enabled()) { | |
for(let p of consume) { | |
marking[p - 1] -= 1 | |
} | |
for(let p of produce) { | |
marking[p - 1] += 1 | |
} | |
} | |
} | |
return {enabled, fire} | |
} | |
return {transition, marking, T, P} | |
} | |
let showState = (e) => { | |
console.log(`marking: ${e.marking.join(' ')}`) | |
let s = '' | |
for(let t = 1; t <= e.T; t += 1) { | |
s = s + `${e.transition(t).enabled() ? '!' : '_'} ` | |
} | |
console.log(`enabled: ${s}\n------------------`) | |
} | |
let e = engine(net) | |
showState(e) | |
e.transition(1).fire() | |
showState(e) | |
// console.log(e.transition(1).enabled()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment