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
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
###############################################################################
# Copyright (c) 2012-2024 by Altair Engineering, Inc.
# All rights reserved.
#
# Altair Engineering, Inc. makes this software available as part of the Vision
# tool platform.  As long as you are a licensee of the Vision tool platform
# you may make copies of the software and modify it to be used within the
# Vision tool platform, but you must include all of this notice on any copy.
# Redistribution without written permission to any third party, with or
# without modification, is not permitted.
# Altair Engineering, Inc. does not warrant that this software is error free
# or fit for any purpose.  Altair Engineering, Inc. disclaims any liability for
# all claims, expenses, losses, damages and costs any user may incur as a
# result of using, copying or modifying the software.
# =============================================================================
#   @script
#       spicevisionpro \
#           -top TOP -pspice \
#           -symlib TNIelement.sym \
#           -userware TNIvision.tcl \
#           <NETLIST.cir>
###############################################################################


# =============================================================================
# This is the configuration section. All used color values and other settings
# are defined below.
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#
# All sub-circuits with names starting with "M_" should be red.
# =============================================================================
#
gui settings set "color:objectHighlight0" #FF0000
gui settings set "color:hicolorbg0"       #5A0000

##
# All sub-circuits with names starting with prefix "MT_" should be magenta.
#
gui settings set "color:objectHighlight1" #FF00FF
gui settings set "color:hicolorbg1"       #5A005A

##
# All wires connected to pins with names starting with prefix "m_" should be
# red (all galvanically connected).
#
gui settings set "color:objectHighlight2" #FF0000
gui settings set "color:hicolorbg2"       #5A0000

##
# All wires connected to pins with prefix "v_" should be orange (all
# galvanically connected).
#
gui settings set "color:objectHighlight3" #FF7600
gui settings set "color:hicolorbg3"       #4C2200

##
# All wires connected to pins with prefix "t_" should be green (up to the
# next network node only).
#
gui settings set "color:objectHighlight4" #00FF00
gui settings set "color:hicolorbg4"       #005A00

##
# All wires connected to pins named innerwall and outerwall should be blue.
#
gui settings set "color:objectHighlight5" #005BF2
gui settings set "color:hicolorbg5"       #00384E

##
# Identify checkpoint pins.
#
gui settings set "color:objectHighlight6" #69AFE9
gui settings set "color:hicolorbg6"       #69AFE9

##
# Display net attributes only at the wire, not at the connected pin.
#
gui settings set "nlv:netattrwire" 1
gui settings set "nlv:netattrpin"  0

##
# Do not split the schematic view into multiple pages.
#
gui settings set "schem:splitpage" 0

##
# Suppress the display of net names for optionally hidden connections.
#
gui settings set "nlv:showhidenetnames" 0

##
# Inform the GUI that the settings have been changed.
#
gui settings changed


# =============================================================================
# Below are configuration options related only to this script.
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#
# Default value for showing the schematic grid.
# =============================================================================
#
set TNIvision(ShowGrid) 0

##
# Default value for level annotation.
#
set TNIvision(AnnotateLevel) 0

##
# Default value for showing results.
#
set TNIvision(ShowResults) 0

##
# Default value for displaying checkpoints.
#
set TNIvision(ShowCheckpoints) 0


# =============================================================================
# TNIvision - Main procedure that always starts the sub-procedure.
# =============================================================================
#
proc TNIvision {db} {
    ##
    # Return if the database is empty.
    #
    if {$db == {}} {
        return
    }

    ##
    # Run all sub-procedures.
    #
    StartColorize   $db         ;# Start implicit coloring based on names.
    StartOutDisplay false       ;# Read the .out file and add attributes.
    StartPreplace   false       ;# Read .top file and preplace components.
}


# =============================================================================
# StartColorize - Start the colorize procedure to show instances and nodes in
#                 the colors according to following chromatics.
#
#                 Chromatics of pressure and thermal networks:
#                 - sub-circuits names starting with "M_" should be red
#                 - sub-circuits names starting with "MT_" should be magenta.
#                 - wires connected to pins with names starting with "m_"
#                   should be red (all galvanically connected).
#                 - all wires connected to pins with "v_" should be orange (all
#                   galvanically connected).
#                 - all wires connected to pins with "t_" should be green (up
#                   to the next network node only).
# =============================================================================
#
proc StartColorize {db} {
    ##
    # Delete all existing highlights.
    #
    $db hilight * deleteAll

    ##
    # Get the top module.
    #
    set top [_getTopModule $db]

    ##
    # Inside the given module loop over all instances.
    #
    $db foreach inst $top inst {
        ##
        # Depending on the name of the referenced sub-circuit (cell name)
        # set a highlight color.
        #
        switch -glob [$db oid cname $inst] {
            "M_*"      {$db hilight $inst set 0}
            "MT_*"     -
            "TM_Node*" {$db hilight $inst set 1}
        }
    }

    ##
    # Inside the given module loop over all nets.
    #
    $db foreach net $top net {
        ##
        # Initialize variables to count the pin type connection.
        #
        set onlyM 0
        set onlyV 0
        set onlyT 0
        set other 0

        ##
        # Loop over all pins of this net
        #
        $db foreach pin $net pin {
            ##
            # Count the number of connections to pins starting with one of
            # the following characters.
            #
            switch -glob [$db oid pname $pin] {
                "m_*"   {incr onlyM}
                "v_*"   {incr onlyV}
                "ti_*"  -
                "to_*"  {incr onlyT}
                "innerwall" -
                "outerwall" {
                    $db hilight $net set 5
                }
                default {incr other}
            }
        }

        ##
        # Apply colors if a net only connects to one kind of pin.
        #
        if { $onlyM && !$onlyV && !$onlyT} {$db hilight $net set 2}
        if {!$onlyM &&  $onlyV && !$onlyT} {$db hilight $net set 3}
        if {!$onlyM && !$onlyV &&  $onlyT} {$db hilight $net set 4}
    }

    ##
    # Inform the GUI that the highlight has changed and apply the highlight.
    #
    gui highlight changed
}


# =============================================================================
# StartOutDisplay - Annotate values from a result file (extension .out).
#
#                   Features:
#                   o parse out files and add the values from the file as
#                     attributes to the loaded database.
#                   o Add the possibility to show/hide the attribute values
#                     in the schematic.
# =============================================================================
#
proc StartOutDisplay {browse} {
    ##
    # Get the name of the result file.
    #
    set fname [_getOutName $browse "out"]

    ##
    # If the result file name is not empty read and apply the topology info.
    #
    if {$fname != ""} {
        _readResult  $fname
        _showResults
        _showCheckpoints
    }
}


# =============================================================================
# StartPreplace - If a file with the same base name as the loaded netlist and
#                 the extension .top exists then open this file and apply the
#                 preplace information from the file to the generated
#                 schematic.
# =============================================================================
#
proc StartPreplace {browse} {
    ##
    # Get the name of the topology file.
    #
    set fname [_getOutName $browse "top"]

    ##
    # If the topology file name is not empty read and apply the topology info.
    #
    if {$fname != ""} {
        _readTopology  $fname
        _applyTopology
    }
}


# -----------------------------------------------------------------------------
# _getTopModule - Get the top module of the loaded Spice netlist.
# -----------------------------------------------------------------------------
#
proc _getTopModule {db {topName "TOP"}} {
    ##
    # Only process the top module automatically generated by PSpice parser
    # of SpiceVision PRO. This module is always named 'TOP'.
    #
    set top [$db search top $topName]

    ##
    # Show an error if this module could not be found.
    #
    if {[$db oid isnull $top]} {
        error "Top module ($topName) not found."
    }

    ##
    # Return the found top module.
    #
    return $top
}


# -----------------------------------------------------------------------------
# _getOutName - Return a filename with the same basename as the read Spice
#               file but add the given extension.
# -----------------------------------------------------------------------------
#
proc _getOutName {browse ext} {
    ##
    # Check for a valid extension.
    #
    switch -- $ext {
        "out"   {set fType "Result"}
        "top"   {set fType "Topology"}
        default {error "Unknown extension '$ext' (need 'out' or 'top')."}
    }

    ##
    # Either manually browse for the topology file or
    # derive the topology file name from the loaded Spice netlist file.
    #
    if {$browse} {
        set fTypeLst [list [list $fType ".$ext"]]
        set fname    [gui window fileDialog openFile \
            "Open a $fType File" $fTypeLst]
    } else {
        ##
        # Set the name of the loaded Spice file.
        #
        set spiceFile [gui settings get "Spice:fname:F"]

        ##
        # Get the root name of the file (without the extension).
        #
        set rootName [file rootname $spiceFile]

        ##
        # First check if a file with the same name exists.
        #
        set fname $rootName.$ext

        ##
        # If no file with the same name exists then check the Spice netlist
        # base name (all before the last underscore character).
        #
        if {![file exists $fname]} {
            set index [string last "_" $rootName]

            if {$index > 1} {
                set fname [string range $rootName 0 $index-1].$ext

                if {![file exists $fname]} {
                    zmessage print WAR "Could not find $fType file '$fname'."
                    set fname ""
                }
            } else {
                zmessage print WAR \
                    "No '_' character found in Spice file '$spiceFile'."
                set fname ""
            }
        }
    }

    return $fname
}


# -----------------------------------------------------------------------------
# _readTopology - Read the topology file.
# -----------------------------------------------------------------------------
#
proc _readTopology {fname} {
    global TNI_Placement

    set db [gui database get]
    if {$db == {}} {
        zmessage print ERR "No database loaded."
        return
    }

    ##
    # Get the top module.
    #
    set top [_getTopModule $db]

    array unset TNI_Placement
    array   set TNI_Placement {instList {} netList {} portList {}}

    foreach objType {inst net port pin} {
        set TNI_Placement(colorList:$objType) {}
    }
    set TNI_Placement(annotateLevel) {}

    set nextCol 7
    set placementHints {}
    set in [open $fname rb]
    while {![eof $in]} {
        set line [gets $in]
        set line [string trim $line]

        if {($line == "") || [string match "#*" $line]} {
            continue
        }

        set type   [lindex $line 0]
        set name   [lindex $line 1]

        switch -- $type {
            "color" {
                switch -- $name {
                    "define" {
                        set colName  [lindex $line 2]
                        set colValue [lindex $line 3]
                        if {[info exists TNI_Placement(color:$colName)]} {
                            zmessage print WAR "Redefinition of color $colName."
                        }
                        gui settings set "color:objectHighlight$nextCol" \
                            $colValue
                        set TNI_Placement(color:$colName) $nextCol
                        incr nextCol
                    }
                    "set" {
                        set objType [lindex $line 2]
                        set objPatt [lindex $line 3]
                        set objCol  [lindex $line 4]
                        set colObj  [list $objPatt $objCol]
                        #checker -scope block exclude warnStyleNesting
                        switch -- $objType {
                            "inst" -
                            "net"  -
                            "port" -
                            "pin"  {}
                            default {
                                set    msg "Unknown color object type "
                                append msg "'$objType' (expect inst, net, port "
                                append msg "or pin)."
                                zmessage print ERR $msg
                                continue
                            }
                        }
                        lappend TNI_Placement(colorList:$objType) $colObj
                    }
                    default {}
                }
            }
            "annotate" {
                switch -- $name {
                    "level" {
                        lappend TNI_Placement(annotateLevel) [lrange $line 2 4]
                    }
                    default {
                        zmessage print ERR "Unknown annotation $name'."
                    }
                }
            }
            "inst" {
                lappend TNI_Placement(instList) $name
                set TNI_Placement($name:orient) [lindex $line 2]
                set TNI_Placement($name:level)  [lindex $line 3]
                set TNI_Placement($name:yPos)   [lindex $line 4]
                set TNI_Placement($name:pHide)  [lindex $line 5]
                set TNI_Placement($name:oHide)  [lindex $line 6]
                set TNI_Placement($name:attrs)  [lindex $line 7]
            }
            "net" {
                set net [$db search net $top $name]
                if {[$db oid isnull $net]} {
                    zmessage print ERR "Net '$name' not found."
                    continue
                }
                lappend TNI_Placement(netList) $name
            }
            "port" {
                set pOrient [lindex $line 2]
                set pLevel  [lindex $line 3]
                set pyPos   [lindex $line 4]

                if {($pOrient != "top")  && ($pOrient != "bottom") &&
                    ($pOrient != "left") && ($pOrient != "right")} {
                    error "Wrong port orientation '$pOrient' @$name."
                }

                if {($pLevel != "") && ($pyPos != "")} {
                    error "Level and yPos are mutual exclusive @$name."
                }

                lappend TNI_Placement(portList)  $name
                set TNI_Placement($name:pOrient) $pOrient
                set TNI_Placement($name:pLevel)  $pLevel
                set TNI_Placement($name:pyPos)   $pyPos
            }
            default {
                error "Syntax error in topology file."
            }
        }
    }
    close $in

    gui settings changed
}


# -----------------------------------------------------------------------------
# _applyTopology - Apply the topology from the .top file to the schem and cone.
# -----------------------------------------------------------------------------
#
proc _applyTopology {} {
    global TNI_Placement

    set db [gui database get]
    if {$db == {}} {
        zmessage print ERR "No database loaded."
        return
    }

    ##
    # Get the top module.
    #
    set top [_getTopModule $db]

    set preplace ""

    ##
    # Process all instances listed in the topology file.
    #
    set instList {}
    set maxLevel -1
    foreach instName $TNI_Placement(instList) {
        set inst [$db search inst $top $instName]
        if {[$db oid isnull $inst]} {
            zmessage print ERR "Instance '$instName' not found."
            continue
        }
        lappend instList $inst

        ##
        # Rotate the instance.
        #
        $db orient $inst $TNI_Placement($instName:orient)

        ##
        # Hide net connections to specified pins.
        #
        foreach pinName $TNI_Placement($instName:pHide) {
            set pin [$db search pin $inst $pinName]
            if {[$db oid isnull $pin]} {
                zmessage print ERR \
                    "Pin '$pinName' at inst '$instName' not found"
                continue
            }
            $db flag $pin set hide
        }

        ##
        # Hide net connections to specified pins.
        #
        foreach pinName $TNI_Placement($instName:oHide) {
            set pin [$db search pin $inst $pinName]
            if {[$db oid isnull $pin]} {
                zmessage print ERR \
                    "Pin '$pinName' at inst '$instName' not found"
                continue
            }
            if {[$db isConnected $pin]} {
                set net [$db connectedNet $pin]
                $db flag $net set hide
            }
        }
        set formatString "@nlv="
        foreach attr $TNI_Placement($instName:attrs) {
            set prefix [lindex $attr 0]
            set aName  [lindex $attr 1]
            set factor [lindex $attr 2]
            set trunc  [lindex $attr 3]
            set attrValue [$db attr $inst getValue $aName]
            if {$attrValue != ""} {
                set dspName @$aName
                set dspValue [_roundTo [expr {$attrValue * $factor}] $trunc]
                $db attr $inst set "$dspName=$dspValue"
                append formatString "${prefix}%$dspName\n"
            }
        }
        if {$formatString != "@nlv="} {
            set module [$db down $inst]
            $db attr $module set [string trimright $formatString "\n"]
        }

        ##
        # Assign level and y position.
        #
        set level $TNI_Placement($instName:level)
        set yPos  $TNI_Placement($instName:yPos)
        append preplace "preplace inst $instName -pg 1 -lvl $level -y $yPos\n"
        if {$level > $maxLevel} {
            set maxLevel $level
        }
    }

    ##
    # To avoid instances be placed into new levels between the already
    # predefined instances move all components behind the last preplace level.
    #
    set y 2600
    set l [incr maxLevel]
    $db foreach inst $top inst {
        set instName [$db oid oname $inst]
        if {[info exists TNI_Placement($instName:orient)]} {
            continue
        }
        append preplace "preplace inst $instName -pg 1 -lvl $l -y $y\n"
        if {[incr y 100] > 4000} {incr l; set y 2600}
    }

    ##
    # Move all ports without preplace information to the right side.
    #
    $db foreach port $top port {
        set portName [$db oid oname $port]
        if {[info exists TNI_Placement($portName:pOrient)]} {
            continue
        }
        $db flag $port set right
    }

    ##
    # Process all ports listed in the topology file.
    #
    foreach portName $TNI_Placement(portList) {
        set port [$db search port $top $portName]
        if {[$db oid isnull $port]} {
            zmessage print ERR "Port '$portName' not found."
            continue
        }

        $db flag $port set $TNI_Placement($portName:pOrient)

        set level $TNI_Placement($portName:pLevel)
        set yPos  $TNI_Placement($portName:pyPos)

        if {$level != ""} {
            append preplace "preplace port $portName -pg 1 -lvl $level\n"
        }
        if {$yPos != ""} {
            append preplace "preplace port $portName -pg 1 -y $yPos\n"
        }
    }

    ##
    # Process all nets listed in the topology file to flag priority nets.
    #
    foreach netName $TNI_Placement(netList) {
        append preplace "flag \{net $netName\} -priority\n"
    }

    ##
    # Process the color object list.
    #
    foreach objType {inst net port pin} {
        if {$TNI_Placement(colorList:$objType) == {}} {
            continue
        }

        switch -- $objType {
            "port"  -
            "net"   -
            "inst"  {
                $db foreach $objType $top obj {
                    set iName [$db oid oname $obj]
                    foreach colObj $TNI_Placement(colorList:$objType) {
                        set objPatt [lindex $colObj 0]
                        set color   [lindex $colObj 1]
                        if {[string match $objPatt $iName]} {
                            set col $TNI_Placement(color:$color)
                            $db flathilight $obj set $col
                        }
                    }
                }
            }
            "pin" {
                $db foreach inst $top inst {
                    set iName [$db oid oname $inst]
                    foreach colObj $TNI_Placement(colorList:$objType) {
                        set objPatt [lindex $colObj 0]
                        set color   [lindex $colObj 1]
                        set iPatt   [lindex $objPatt 0]
                        set pPatt   [lindex $objPatt 1]
                        if {[string match $iPatt $iName]} {
                            $db foreach pin $inst pin {
                                set pName [$db oid pname $pin]
                                if {[string match $pPatt $pName]} {
                                    set col $TNI_Placement(color:$color)
                                    $db flathilight $pin set $col
                                }
                            }
                        }
                    }
                }
            }
            default {}
        }
    }

    ##
    # Show the new topology in the Schem window.
    #
    gui schem setCurrentModule -activate {}
    gui tree  setCurrentModule           {}
    gui schem clearCache -all
    $db oid setSchematicCache $top $preplace
    gui schem setCurrentModule -activate $top
    gui tree  setCurrentModule           $top

    ##
    # Apply optionally hidden pins.
    #
    set schem_nlv [gui schem nlv]
    $schem_nlv increment
    $db foreach net $top net {
        if {[$db flag $net is hide]} {
            set nlvOid [$schem_nlv search net [$db oid oname $net]]
            if {$nlvOid != {}} {
                $schem_nlv flag [list net [$db oid oname $net]] -hide
            }
        }
    }
    $schem_nlv show
    gui schem zoom fullfit

    ##
    # Load all elements from the topology file into the Cone window.
    #
    set pinList  {}
    set appendConeList {}
    foreach inst $instList {
        set inm [$db oid oname $inst]
        if {[string match "X_TOP_*" $inm] || [string match "X_BOTTOM_*" $inm]} {
            lappend appendConeList $inst
            continue
        }
        $db foreach pin $inst pin {
            lappend pinList $pin
        }
    }
    gui cone load $pinList
    gui cone append $appendConeList

    ##
    # Apply same topology as in the Schem window also to the Cone.
    #
    set cone_nlv [gui cone nlv]
    $cone_nlv increment -reroute
    $cone_nlv grestore -string $preplace
    $cone_nlv show
    gui cone zoom fullfit
    gui bookmark add Cone "Pressure Network"

    _toggleLevel
    _showGrid
}


# -----------------------------------------------------------------------------
# _makeOID - Create an OID based on a string extracted from the result file.
# -----------------------------------------------------------------------------
#
proc _makeOID {db top type txt} {
    set hierPath {}

    set path [split $txt ":"]

    set prefix ""
    if {$type == "inst"} {
        set prefix [lindex $path 0]
        if {$prefix == "b"} {
            set prefix "e"
        }
        set path   [lrange $path 1 end]
    }

    foreach p [lrange $path 0 end-1] {
        lappend hierPath x$p
    }

    set p [lindex $path end]
    if {($type == "net") && ([string index $p 0] == "y")} {
        set sep [string last "_" $p]

        switch -nocase -- [string index $p $sep-1] {
            "t" {
                set ir 2
                set nr 1
            }
            "m" {
                set ir 3
                set nr 2
            }
            default {}
        }
        set inst [string range $p 1 $sep-$ir]
        set node [string range $p $sep-$nr end]
        lappend hierPath x$inst $node
    } else {
        lappend hierPath ${prefix}$p
    }

    set name [join $hierPath :]

    if {[catch {
        set oid [$db oid createFromString $type $top $name : -icase]
    }]} {
        set oid [$db oid create null]
    }
    return $oid
}


# -----------------------------------------------------------------------------
# _processResultSection - Process the 'CHECKPOINT' section of the .out file.
# -----------------------------------------------------------------------------
#
proc _processResultSection {db top line} {
    set node [lindex $line 1]
    set oid  [_makeOID $db $top "net" $node]
    if {[$db oid isnull $oid]} {
        zmessage print WAR "Cannot find node $node"
        return
    }

    set initials ""
    foreach attr [lrange $line 2 end] {
        set attrName  [lindex [split $attr "="] 0]
        set attrValue [lindex [split $attr "="] 1]
        if {$attrName != "NAME"} {
            continue
        }
        set initials [string index $attrValue 0]
        break
    }
    foreach attr [lrange $line 2 end] {
        set attrName  [lindex [split $attr "="] 0]
        set attrValue [lindex [split $attr "="] 1]
        set checkpoint 0
        if {$attrName == "POS"} {
            set checkpoint 1
        }
        $db flatattr $oid set $attr
        $db foreach pin $oid pin {
            $db flatattr $pin set $attr
            if {[$db oid type $pin] == "port"} {$db flag $pin set hide}
            if {$checkpoint} {
                $db flatattr $pin set "checkpoint=td,#69AFE9"
                $db flatattr $pin set "CHECKVAL=${initials}$attrValue"
                $db flathilight $pin set 6
            }
        }
    }
}


# -----------------------------------------------------------------------------
# _processNodeVoltageSection - Process the 'NODE/VOLTAGE' section.
# -----------------------------------------------------------------------------
#
proc _processNodeVoltageSection {db top line} {
    set node  [string trim [lindex $line 0] ()]
    set value [lindex $line 1]
    set oid [_makeOID $db $top "net" $node]
    if {[$db oid isnull $oid]} {
        zmessage print WAR "Cannot find node $node"
        return
    }

    set attr VAL=[_roundTo $value 2]
    $db flatattr $oid set $attr
    $db foreach pin $oid pin {
        switch -glob [$db oid pname $pin] {
            "m*"  {
                $db flatattr $pin set MASS_FLOW_RATE=[_roundTo $value 4]
            }
            "v_*" {
                $db flatattr $pin set VELOCITY=[_roundTo $value 3]
            }
            default {$db flatattr $pin set $attr}
        }
    }
}


# -----------------------------------------------------------------------------
# _processBranchCurrentSection - Process the 'BRANCH/CURRENT' section.
# -----------------------------------------------------------------------------
#
proc _processBranchCurrentSection {db top line} {
    set branch [string trim [lindex $line 0] ()]
    set branch [string range $branch 0 end-7]

    set oid [_makeOID $db $top "inst" $branch]
    if {[$db oid isnull $oid]} {
        zmessage print WAR "Cannot find inst $branch"
        return
    }

    set current [lindex $line 1]
    $db flatattr $oid set CURRENT=[_roundTo $current 2]
}


# -----------------------------------------------------------------------------
# _showCheckpoints - Show checkpoints at pins.
# -----------------------------------------------------------------------------
#
proc _showCheckpoints {} {
    global TNIvision

    set db [gui database get]

    if {$TNIvision(ShowCheckpoints)} {
        $db attr -db set @nlv:marks=%checkpoint
        $db attr -db set @nlv:pin=%CHECKVAL
    } else {
        $db attr -db delete @nlv:marks
        $db attr -db delete @nlv:pin
    }
    gui attribute changed
}


# -----------------------------------------------------------------------------
# _showResults - Show result values at the nets.
# -----------------------------------------------------------------------------
#
proc _showResults {} {
    global TNIvision

    set db [gui database get]

    if {$TNIvision(ShowResults)} {
        $db attr -db set @nlv:net=%VAL
    } else {
        $db attr -db delete @nlv:net
    }

    gui attribute changed
}


# -----------------------------------------------------------------------------
# _readResult - Read the .out result file.
# -----------------------------------------------------------------------------
#
proc _readResult {fname} {
    set db [gui database get]
    if {$db == {}} {
        zmessage print ERR "No database loaded."
        return
    }

    ##
    # Get the top module.
    #
    set top [_getTopModule $db]

    set section 0
    set results 1
    set voltage 2
    set current 4

    set in [open $fname r]
    while {![eof $in]} {
        set line [gets $in]
        if {[string trim $line] == ""} {
            continue
        }

        switch -glob -- $line {
            "*RESULTS:*" {
                set section $results
                continue
            }
            "*NODE*VOLTAGE*" {
                set section $voltage
                continue
            }
            "*BRANCH*CURRENT*" {
                set section $current
                continue
            }
            default {
            }
        }

        ##
        # Depending on the current section call a procedure to read the values.
        #
        if {$section & $results} {
            _processResultSection $db $top $line
        }
        if {$section & $voltage} {
            _processNodeVoltageSection $db $top $line
        }
        if {$section & $current} {
            _processBranchCurrentSection $db $top $line
        }
    }
    close $in
}


# -----------------------------------------------------------------------------
# _showGrid - Enable debug options to show a grid, bounding boxes etc.
# -----------------------------------------------------------------------------
#
proc _showGrid {} {
    global TNIvision

    foreach nlv [list \
        [gui schem nlv] \
        [gui cone  nlv] \
    ] {
        ##
        # Show coordinates, a dotted grid as well as a 50x50 rectangle.
        #
        $nlv property showgrid [expr {$TNIvision(ShowGrid) ? 255 : 0}]

        ##
        # Show all levels.
        #
        $nlv property showlevels [expr {$TNIvision(ShowGrid) ?  15 : 0}]

        ##
        # Show debug bounding boxes.
        #
        $nlv dbg [expr {$TNIvision(ShowGrid) ? "-drawbbox" : "-reset"}]
        $nlv redraw
    }
}


# -----------------------------------------------------------------------------
# _annotateLevels - Annotate levels according to the level info in the
#                   topology file.
# -----------------------------------------------------------------------------
#
proc _annotateLevels {w} {
    global TNI_Placement TNIvision

    ##
    # Return if no schematic page exists.
    #
    if {[gui schem pages] == 0} {
        return
    }

    set db     [gui database get]
    set curMod [gui schem getCurrentModule]
    if {[$db oid oname $curMod] != "TOP"} {
        return
    }

    ##
    # Remove all existing comment graphic objects.
    #
    foreach obj [$w search cgraphic *] {
        $w unload [lindex $obj end-1] [lindex $obj end]
    }

    if {!$TNIvision(AnnotateLevel)} {
        return
    }

    set pageSize  [$w pagesize -db -bbox]
    set yStart    [lindex $pageSize 1]
    set yEnd      [lindex $pageSize 3]
    set yDelta    [expr {$yEnd - $yStart}]
    set levelInfo [$w levelinfo -pg 1]

    ##
    # Define colors for level annotation.
    #
    array set _colorMap {}
    set nextCol 3
    foreach lvlInfo $TNI_Placement(annotateLevel) {
        set lvlColor [lindex $lvlInfo 1]
        if {[info exists _colorMap($lvlColor)]} {
            continue
        }
        if {[info exists TNI_Placement(color:$lvlColor)]} {
            set colNo  $TNI_Placement(color:$lvlColor)
            set colVal [gui settings get "color:objectHighlight$colNo"]
        } else {
            zmessage print ERR \
                "Cannot find color value for '$lvlColor' (using black)."
            set colVal #000000
        }
        set _colorMap($lvlColor) $nextCol
        $w property boxcolor$nextCol $colVal
        incr nextCol
    }

    ##
    # Get placement information for all instances sorted by level.
    #
    array set _levelHash {}
    foreach inst [$w search -shortfmt inst *] {
        set level [$w getplacement -lvl $inst]
        lappend _levelHash($level) $inst
    }

    set id 0
    foreach lvlInfo $TNI_Placement(annotateLevel) {
        set lvlRange  [lindex $lvlInfo 0]
        set lvlColor  [lindex $lvlInfo 1]
        set lvlLabel  [lindex $lvlInfo 2]

        set from      [lindex $lvlRange 0]
        set to        [lindex $lvlRange 1]

        if {[info exists _levelHash($from)]} {
            set minX 0xFFFFFFFF
            foreach inst $_levelHash($from) {
                set curMinX [lindex [$w bbox -db $inst] 0]
                if {$curMinX < $minX} {
                    set minX $curMinX
                }
            }
            set xStart $minX
        } else {
            set xStart [lindex $levelInfo $from]
        }

        if {[info exists _levelHash($to)]} {
            set maxX -0xFFFFFFFF
            foreach inst $_levelHash($to) {
                set curMaxX [lindex [$w bbox -db $inst] 2]
                if {$curMaxX > $maxX} {
                    set maxX $curMaxX
                }
            }
            set xEnd $maxX
        } else {
            set xEnd [lindex $levelInfo $to]
        }

        set xDelta    [expr {$xEnd - $xStart}]
        set xMid      [expr {$xStart + ($xDelta / 2)}]

        set colNo $_colorMap($lvlColor)

        $w load cgraphic cgraphic_$id linkto 1 \
            place abs $xStart $yStart  \
            linewidth 3 \
            linecolor $colNo \
            path 0 0 $xDelta 0 $xDelta $yDelta 0 $yDelta 0 0
        incr id

        $w load cgraphic cgraphic_$id linkto 1 \
            place abs $xMid $yStart  \
            linewidth 3 \
            linecolor $colNo \
            textcolor $colNo \
            text $lvlLabel -lc 0 -12 30
        incr id
    }
}


# -----------------------------------------------------------------------------
# _toggleLevel - Toggle the level annotation on or off.
# -----------------------------------------------------------------------------
#
proc _toggleLevel {} {
    foreach nlv [list \
        [gui schem nlv] \
        [gui cone  nlv] \
    ] {
        _annotateLevels $nlv
    }
}


# -----------------------------------------------------------------------------
# _pageNotifyCB - Add a call to _annotateLevels after the original page notify
#                 callback.
# -----------------------------------------------------------------------------
#
proc _pageNotifyCB {nlv origCB} {
    eval $origCB
    _annotateLevels $nlv
}


##
# Register a page notify callbacks to annotate the levels according to the
# current page layout.
#
foreach nlv [list \
    [gui schem nlv] \
    [gui cone  nlv] \
] {
    set origCB [$nlv cget -pagenotify]
    $nlv configure -pagenotify [list _pageNotifyCB $nlv $origCB]
}


# -----------------------------------------------------------------------------
# _roundTo - Round function that allow to specify the number of decimal places.
# -----------------------------------------------------------------------------
#
proc _roundTo {value decimalplaces} {
    set power [expr {pow(10, $decimalplaces)}]
    return [expr {round(($power * $value)) / $power}]
}


# =============================================================================
# Add a new main menu entry 'TNI' to access the procedures of this script.
# =============================================================================
#
gui menu command     {"TNI" "Load Topology"} {StartPreplace   true}
gui menu command     {"TNI" "Load Result"}   {StartOutDisplay true}
gui menu separator   {"TNI"}
gui menu checkbutton {"TNI" "Show Results"}     \
                     {_showResults}             \
                        TNIvision(ShowResults)
gui menu checkbutton {"TNI" "Show Checkpoints"} \
                     {_showCheckpoints}         \
                     TNIvision(ShowCheckpoints)
gui menu checkbutton {"TNI" "Annotate Levels"}  \
                     {_toggleLevel}             \
                     TNIvision(AnnotateLevel)
gui menu separator   {"TNI"}
gui menu checkbutton {"TNI" "Debug Grid"}       \
                     {_showGrid}                \
                     TNIvision(ShowGrid)


##
# Use gui database runOrRegisterChangedCallback to immediately run TNIvision
# if we have a database, furthermore register the proc to be executed after
# the database is available.
#
gui database runAndRegisterChangedCallback TNIvision