All files / src/app/models petri.ts

76.07% Statements 194/255
50.6% Branches 42/83
83.87% Functions 26/31
76.2% Lines 189/248

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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512      110x 110x     490x 260x   230x 110x               88x       220x   220x 220x 220x 220x 220x 220x 3x   220x 220x                   108x       270x 270x 270x 270x   270x   270x 270x 270x 270x 270x   270x 270x                 550x 550x 550x 550x 550x 550x 550x 550x   485x 270x 270x     215x 215x   485x         65x 65x 65x 65x   65x 65x 65x 65x 65x 65x   65x 65x 65x                     110x 110x 110x                 110x 110x 110x                                                     440x                           2x 2x     2x 2x 2x 2x 2x 2x   2x   2x                           2x 2x 88x     2x   2x 108x     2x 2x 110x 110x 110x   2x 2x 110x 110x 110x     2x         2x 2x 2x 2x 88x 108x 2x 196x 196x     196x 196x 2x 2x     2x 1x   1x 1x   2x         194x 106x     88x   194x 194x 10670x 218x     194x                                                     2x 2x 2x 2x 2x 2x 2x 2x 122x 122x 194x 218x 194x 194x       122x 122x   122x   2x             2x   2x 2x     2x   2x     2x 196x 124x   196x       2x 124x 196x         2x                                                                                                                                                                 2x 2x 196x   2x         5x     5x 5x         5x 5x 5x   5x 5x 5x 5x   5x 275x 275x 275x 275x       5x 275x 275x 275x 275x       5x 5x 220x     5x 3x 3x 3x       5x 220x 220x 220x 220x     220x         5x 270x 270x 270x                    
import { Point, ViewWindow, Zone, Drawer, TextStyle, DrawObject, lightPalette, darkPalette, ColorPalette, EdgeStyle, SurfaceStyle } from './canvas';
import { of, max, min, Subject } from 'rxjs';
 
export abstract class PetriNode{
    static fontSize: number = 0.15;
 
    shortenText(text: string, maxTextWidth: number): string {
        if (text.length * PetriNode.fontSize > maxTextWidth) {
            return text.slice(0, Math.floor(maxTextWidth / PetriNode.fontSize)).trim() + "...";
        }
        return text;
    }
}
 
export class Place extends PetriNode{
    name: string;
    code_lines: string[];
 
    static deserialize(json: PlaceInterface): Place{
        return Object.assign(new Place(), json);
    }
 
    draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow, position: Point, radius: number, numberTokens:number=0){
        const textToDraw = this.shortenText(this.name, 15 * radius);
 
        const drawer = new Drawer(context);
        const positionVW = viewWindow.canvasPoint(position);
        const radius2 = viewWindow.size(radius);
        const fontSize = viewWindow.size(PetriNode.fontSize);
        let placeColor = palette.foreground;
        if (numberTokens > 0){
            placeColor = palette.alert;
        }
        drawer.drawCircle(positionVW.x, positionVW.y, radius2, new SurfaceStyle(placeColor, 1, palette.border));
        drawer.drawText(textToDraw, positionVW.x, positionVW.y, new TextStyle(palette.border), fontSize);
 
    }
 
}
 
export 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 maxTextWidth: number = 5 * height;
        let transitionTextWidth: number = width;
        of(width, PetriNode.fontSize * this.condition.length).pipe(max()).subscribe(v => transitionTextWidth = v);
        of(transitionTextWidth, maxTextWidth).pipe(min()).subscribe(v => transitionTextWidth = v);
 
        const textToDraw: string = this.shortenText(this.condition, transitionTextWidth);
 
        const drawer = new Drawer(context);
        const positionVW = viewWindow.canvasPoint(position);
        const rectangleWidth = viewWindow.size(transitionTextWidth);
        const rectangleHeight = viewWindow.size(height);
        const fontSize = viewWindow.size(PetriNode.fontSize);
 
        drawer.drawRectangle(positionVW.x-0.5*rectangleWidth, positionVW.y-0.5*rectangleHeight, rectangleWidth, rectangleHeight, new SurfaceStyle(palette.foreground, 1, palette.border));
        drawer.drawText(textToDraw, positionVW.x, positionVW.y, new TextStyle(palette.border), fontSize);
    }
 
}
 
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;
    tokens: number[];
    selectedPlace: Subject<Place | null> = new Subject();
    selectedTransition: Subject<Transition | null> = new Subject();
 
    constructor(places: Place[], transitions: Transition[], inputArcs: InputArc[], outputArcs: OutputArc[], tokens:number[]=[]){
        super();
        this.places = places;
        this.transitions = transitions;
        this.inputArcs = inputArcs;
        this.outputArcs = outputArcs;
        this.tokens = tokens;
 
        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);
 
    }
 
    override mouseDownCallback(clickPoint: Point, viewWindow: ViewWindow){
        const clickPoint2 = viewWindow.zonePoint(clickPoint);
        let distance = Infinity;
        let bestNode: PetriNode | null = null;
        const nodes: PetriNode[] = [];
        this.places.forEach(place => nodes.push(place));
        this.transitions.forEach(transition => nodes.push(transition));
        for (const node of nodes) {
            const position = this.layout.get(node);
            Iif (position === undefined) {
                continue;
            }
            const compDistance = clickPoint2.distance(position);
            if (compDistance < distance && compDistance < 0.3){// Todo: adapt this from scene size of view window size and from component bounding box
                distance = compDistance;
                bestNode = node;
            }
        }
        if (this.places.indexOf(bestNode as Place) > -1) {
            this.selectedPlace.next(bestNode as Place);
        }
        else Eif (this.transitions.indexOf(bestNode as Transition) > -1) {
            this.selectedTransition.next(bestNode as Transition);
        }
        return bestNode === null;
    }
 
    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);
            }
        }
 
        const placeNumberTokens: Map<Place, number> = new Map();
        for (const place of this.places){
            placeNumberTokens.set(place, 0);
        }
 
        for (const index of this.tokens){
            const numberTokens = placeNumberTokens.get(this.places[index]);
            Eif (numberTokens !== undefined){
                placeNumberTokens.set(this.places[index], numberTokens+1);
            }
        }
 
        for (const place of this.places){
            const position = this.layout.get(place);
            Eif (position instanceof Point){
                let numberTokens = placeNumberTokens.get(place);
                Iif (numberTokens === undefined){
                    numberTokens = 0;
                }
                place.draw(context, palette, viewWindow, position, radius, numberTokens);
            }
 
        }
 
        for (const transition of this.transitions){
            const position = this.layout.get(transition);
            Eif (position instanceof Point){
                transition.draw(context, palette, viewWindow, position, transitionWidth, transitionHeight);
            }
        }
 
 
 
 
    }
 
}