All files / src/app/models petri.ts

70.29% Statements 142/202
46.03% Branches 29/63
75% Functions 18/24
71% Lines 142/200

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445                    44x       84x 84x 84x 84x 84x                   52x       102x 102x 102x 102x 102x 102x                 212x 212x 212x 212x 212x 212x 212x 212x   188x 104x 104x     84x 84x   188x         24x 24x 24x 24x   24x 24x 24x 24x 24x 24x   24x 24x 24x                     53x 53x 53x                 53x 53x 53x                                                     212x                             1x 1x 1x 1x 1x   1x   1x                           1x 1x 44x     1x   1x 52x     1x 1x 53x 53x 53x   1x 1x 53x 53x 53x     1x                     93x 51x     42x   93x 93x 4929x 106x     93x                                                     1x 1x 1x 1x 1x 1x 1x 1x 480x 480x 93x 106x 92x 92x       480x 480x   480x   1x             1x   1x 1x     1x   1x     1x 93x 58x   93x       1x 58x 93x         1x                                                                                                                                                                 1x 1x 93x   1x         2x     2x 2x         2x 2x 2x   2x 2x 2x 2x   2x 106x 106x 106x 106x       2x 106x 106x 106x 106x       2x 88x 88x 84x         2x 104x 104x 102x                    
import { Point, ViewWindow, Zone, Drawer, TextStyle, DrawObject, lightPalette, darkPalette, ColorPalette, EdgeStyle, SurfaceStyle } from './canvas';
 
abstract class PetriNode{
 
}
 
class Place extends PetriNode{
    name: string;
 
    static deserialize(json: PlaceInterface): Place{
        return Object.assign(new Place(), json);
    }
 
    draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow, position: Point, radius: number){
        const drawer = new Drawer(context);
        const positionVW = viewWindow.canvasPoint(position);
        const radius2 = viewWindow.size(radius);
        drawer.drawCircle(positionVW.x, positionVW.y, radius2, new SurfaceStyle(palette.foreground, 1, palette.border));
        drawer.drawText(this.name, positionVW.x, positionVW.y, new TextStyle(palette.border));
 
    }
 
}
 
class Transition extends PetriNode{
    condition: string;
 
    static deserialize(json: TransitionInterface): Transition{
        return Object.assign(new Transition(), json);
    }
 
    draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow, position: Point, width: number, height: number){
        const drawer = new Drawer(context);
        const positionVW = viewWindow.canvasPoint(position);
        const width2 = viewWindow.size(width);
        const height2 = viewWindow.size(height);
        drawer.drawRectangle(positionVW.x-0.5*width2, positionVW.y-0.5*height2, width2, height2, new SurfaceStyle(palette.foreground, 1, palette.border));
        drawer.drawText(this.condition, positionVW.x, positionVW.y, new TextStyle(palette.border));
    }
 
}
 
abstract class Arc{
 
    draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow, sourcePosition: Point, destinationPosition: Point,
         placeRadius: number, transitionHeight: number){
        const drawer = new Drawer(context);
        const sourcePositionVW = viewWindow.canvasPoint(sourcePosition);
        const destinationPositionVW = viewWindow.canvasPoint(destinationPosition);
        const radius = viewWindow.size(placeRadius);
        const height = viewWindow.size(transitionHeight);
        const edgeStyle = new EdgeStyle(1, palette.border);
        const surfaceStyle = new SurfaceStyle(null , 1, palette.border);
        if (sourcePositionVW.y < destinationPositionVW.y){
            // Downstream
            if (this instanceof InputArc){
                sourcePositionVW.y += radius;
                destinationPositionVW.y -= 0.5*height;
            }
            else{
                sourcePositionVW.y += 0.5*height;
                destinationPositionVW.y -= radius;
            }
            drawer.drawArrow(sourcePositionVW, destinationPositionVW, edgeStyle);
 
        }
        else{
            // Upstream
            const dX = sourcePositionVW.x - destinationPositionVW.x;
            const dY = sourcePositionVW.y - destinationPositionVW.y;
            const absDxUp = Math.max(1.5*dX, 0.1*dY, 3*height);
            const yMargin = Math.max(0.05*Math.abs(dY), 1.1*height);
 
            const p2 = sourcePositionVW.add(new Point(0, yMargin));
            const p5 = destinationPositionVW.add(new Point(0, -yMargin));
            const dxUp = dX != 0 ? Math.sign(dX)*absDxUp : absDxUp;
            const xUp = sourcePositionVW.x + dxUp;
            const p3 = new Point(xUp, p2.y);
            const p4 = new Point(xUp, p5.y);
 
            const points = [sourcePositionVW, p2, p3, p4, p5];
            drawer.drawPolygon(points, surfaceStyle);
            drawer.drawArrow(p5, destinationPositionVW ,edgeStyle);
        }
    }
}
 
 
class InputArc extends Arc{
    source: Place;
    destination: Transition;
 
    constructor(source: Place, destination: Transition){
        super();
        this.source = source;
        this.destination = destination;
    }
}
 
class OutputArc extends Arc{
    source: Transition;
    destination: Place;
 
    constructor(source: Transition, destination: Place){
        super();
        this.source = source;
        this.destination = destination;
    }
}
 
interface PlaceInterface{
    name: string;
}
 
interface TransitionInterface{
    condition: string;
}
 
interface ArcInterface{
    source: string;
    destination: string;
    weight: number;
}
 
 
export interface PetriNetworkInterface{
    places: PlaceInterface[]
    transitions: TransitionInterface[]
    input_arcs: ArcInterface[];
    output_arcs: ArcInterface[];
}
 
function jsonPointerToIndex(jsonPointer: string){
    return Number(jsonPointer.split('/').at(-1));
}
 
class PetriLayout extends Map<PetriNode, Point>{
 
}
 
export class PetriNetwork extends DrawObject{
    places: Place[];
    transitions: Transition[];
    inputArcs: InputArc[];
    outputArcs: OutputArc[];
    layout: PetriLayout;
 
    constructor(places: Place[], transitions: Transition[], inputArcs: InputArc[], outputArcs: OutputArc[]){
        super();
        this.places = places;
        this.transitions = transitions;
        this.inputArcs = inputArcs;
        this.outputArcs = outputArcs;
 
        this.layout = this.computeLayout();
 
        window.addEventListener('keydown', (event) => {
            if (event.key == 'r'){
                this.layout = this.relaxLayout(this.layout, 1, 1);
            }
            if (event.key == 't'){
                this.layout = this.computeLayout();
            }
 
          });
 
    }
 
    static deserialize(jsonPetri: PetriNetworkInterface): PetriNetwork{
 
        const places: Place[] = [];
        for (const placeJson of jsonPetri['places']){
            places.push(Place.deserialize(placeJson));
        }
 
        const transitions: Transition[] = [];
 
        for (const json of jsonPetri['transitions']){
            transitions.push(Transition.deserialize(json));
        }
 
        const inputArcs: InputArc[] = [];
        for (const json of jsonPetri['input_arcs']){
            const sourceIndex = jsonPointerToIndex(json["source"]);
            const destinationIndex = jsonPointerToIndex(json["destination"]);
            inputArcs.push(new InputArc(places[sourceIndex], transitions[destinationIndex]));
        }
        const outputArcs: OutputArc[] = [];
        for (const json of jsonPetri['output_arcs']){
            const sourceIndex = jsonPointerToIndex(json["source"]);
            const destinationIndex = jsonPointerToIndex(json["destination"]);
            outputArcs.push(new OutputArc(transitions[sourceIndex], places[destinationIndex]));
        }
 
        return new PetriNetwork(places, transitions, inputArcs, outputArcs);
 
    }
 
    // eslint-disable-next-line
    override mouseDownCallback(clickPoint: Point, viewWindow: ViewWindow){
        return true;
    }
 
    successors(node: PetriNode): PetriNode[]{
        let arcs;
        if (node instanceof Transition){
            arcs = this.outputArcs;
        }
        else{
            arcs = this.inputArcs;
        }
        const successors: (Place | Transition)[] = [];
        for (const arc of arcs){
            if (arc.source == node){
                successors.push(arc.destination);
            }
        }
        return successors;
    }
 
    predecessors(node: PetriNode): PetriNode[]{
        let arcs;
        if (node instanceof Transition){
            arcs = this.inputArcs;
        }
        else{
            arcs = this.outputArcs;
        }
        const predecessors: (Place | Transition)[] = [];
        for (const arc of arcs){
            if (arc.destination == node){
                predecessors.push(arc.source);
            }
        }
        return predecessors;
    }
 
    neighbors(node: PetriNode): PetriNode[]{
         return this.successors(node).concat(this.predecessors(node));
    }
 
 
 
    private assignLayers(): Map<PetriNode, number> {
        const layers: Map<PetriNode, number> = new Map();
        layers.set(this.places[0], 0);
        let layerNumber = 1;
        const nNodes = this.places.length + this.transitions.length;
        let currentNodes: PetriNode[] = [this.places[0]];
        let nIter = 0;
        const nIterMax = 5*nNodes;
        while (layers.size < nNodes && nIter < nIterMax){
            const visitedNodes: PetriNode[] = [];
            for (const node1 of currentNodes){
                for (const node2 of this.successors(node1)){
                    if (!layers.has(node2)){
                        layers.set(node2, layerNumber);
                        visitedNodes.push(node2);
                    }
                }
            }
            currentNodes = visitedNodes;
            layerNumber += 1;
 
            nIter += 1;
        }
        return layers;
 
 
    }
 
 
    computeLayout(): PetriLayout {
        const layers = this.assignLayers();  // Step 2: Assign layers
 
        const layerHeight = -1; // Vertical distance between layers
        const nodeSpacing = 1; // Horizontal distance between nodes in a layer
 
        // Create coordinates for each node
        const layout = new PetriLayout();
 
        const layersGrouped = new Map<number, PetriNode[]>();
 
        // Group nodes by their layers
        layers.forEach((layer, node) => {
            if (!layersGrouped.has(layer)) {
                layersGrouped.set(layer, []);
            }
            layersGrouped.get(layer)!.push(node);
        });
 
        // Assign coordinates
        layersGrouped.forEach((nodes, layer) => {
            nodes.forEach((node, index) => {
                layout.set(node, new Point(index * nodeSpacing, layer * layerHeight));
            });
        });
 
 
        return layout;
    }
 
    relaxLayout(layout: PetriLayout, nodeSpacing:number, iterations: number=1): Map<PetriNode, Point> {
 
        // Finding the most relaxable node
        for (let iter=0;iter < iterations;iter++){
            let bestMark = 0;
            let bestNode: PetriNode | null = null;
            let bestNodeNewX: number = 0;
            let bestNodeY: number = 0;
 
            for (const [node, nodePosition] of layout){
                const neighborX: number[] = [];
                for (const neighbor of this.neighbors(node)){
                    const position = layout.get(neighbor);
                    if (position !== undefined){
                        neighborX.push(position.x);
                    }
                }
                let sum = 0.;
                neighborX.forEach((el) => sum += el);
                let idealX = sum / (neighborX.length);
 
                if (idealX != nodePosition.x){
 
 
                    // Find Layer neighbor
                    let nearestLayerNeighbor: PetriNode | null = null;
                    let layerNeighborDistance = 10000;
                    const pointDistance = nodePosition.x - idealX;
 
                    for (const [node2, node2Position] of layout){
                        if (node2Position.y == nodePosition.y){
                            const point2Distance = node2Position.x - idealX;
                            if (point2Distance / pointDistance > 0){
                                if (Math.abs(point2Distance) < layerNeighborDistance){
                                    nearestLayerNeighbor = node2;
                                    layerNeighborDistance = Math.abs(point2Distance);
                                }
                            }
                        }
                    }
 
                    // restrict ideal X with spacing constraints
                    if (nearestLayerNeighbor !== null){
                        const neighborPosition = layout.get(nearestLayerNeighbor);
                        if (neighborPosition !== undefined){
                            const neighborDistance = Math.abs(neighborPosition.x - nodePosition.x);
                            const margin = neighborDistance - nodeSpacing - pointDistance;
                            if (margin < 0){
                                if (nodePosition.x - idealX < 0){
                                    idealX -= margin;
                                }
                                else{
                                    idealX += margin;
                                }
                            }
                        }
                    }
 
 
                    const mark = Math.abs(nodePosition.x - idealX);
                    if (mark > bestMark){
                        bestNode = node;
                        bestMark = mark;
                        bestNodeNewX = idealX;
                        bestNodeY = nodePosition.y;
                    }
                }
 
            }
            if (bestNode !== null){
                layout.set(bestNode, new Point(bestNodeNewX, bestNodeY));
            }
 
        }
        return layout;
    }
 
    override get zone(): Zone{
        const points: Point[] = [];
        for (const point of this.layout.values()) {
            points.push(point);
        }
        return Zone.fromPoints(points);
    }
 
    override draw(context: CanvasRenderingContext2D, viewWindow: ViewWindow){
 
        const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
 
 
        let palette = lightPalette;
        Iif (isDarkMode){
            palette = darkPalette;
        }
 
        // Drawing background
        context.rect(0, 0, context.canvas.width, context.canvas.height);
        context.fillStyle = palette.background;
        context.fill();
 
        const size = 0.2;
        const radius = 0.5*size;
        const transitionHeight = size;
        const transitionWidth = 3*transitionHeight;
 
        for (const arc of this.inputArcs){
            const sourcePosition = this.layout.get(arc.source);
            const destinationPosition = this.layout.get(arc.destination);
            Eif (sourcePosition instanceof Point && destinationPosition instanceof Point){
                arc.draw(context, palette, viewWindow, sourcePosition, destinationPosition, radius, transitionHeight);
            }
        }
 
        for (const arc of this.outputArcs){
            const sourcePosition = this.layout.get(arc.source);
            const destinationPosition = this.layout.get(arc.destination);
            Eif (sourcePosition instanceof Point && destinationPosition instanceof Point){
                arc.draw(context, palette, viewWindow, sourcePosition, destinationPosition, radius, transitionHeight);
            }
        }
 
        for (const place of this.places){
            const position = this.layout.get(place);
            if (position instanceof Point){
                place.draw(context, palette, viewWindow, position, radius);
            }
 
        }
 
        for (const transition of this.transitions){
            const position = this.layout.get(transition);
            if (position instanceof Point){
                transition.draw(context, palette, viewWindow, position, transitionWidth, transitionHeight);
            }
        }
 
 
 
 
    }
 
}