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
###############################################################################
# Copyright (c) 2022-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.
# =============================================================================
#   @plugin
#       Compute and Display Device Statistics
#   @namespace
#       DeviceStatistics
#   @section
#       Analyze the Loaded Database
#   @description
#       Compute and display statistics about the devices used in the design.
#
#   @files
#       deviceStatistics.tcl
#   @example
#       demo/spice/gl85.sp
#   @cmdline
#       -userware @files[0]
#       -hspice @example[0]
#   @tag
#       spice gui report
###############################################################################

package require struct

namespace eval DeviceStatistics {
    variable _Name               "Device Statistics"
    variable _DeviceList         {}
    variable _BinningRange       {16n 20n 36n}
    variable _Table              ""
    variable _Tree               ""
    variable _TotalInstances     0
    variable _CurrentInstance    0
}


# =============================================================================
# Init - Initialize the plugin.
# =============================================================================
#
proc ::DeviceStatistics::Init {} {
    variable _Name

    ##
    # Add menu entries.
    #
    gui menu command [list $_Name "Show"] \
        [list ::DeviceStatistics::_showWidget]
    gui menu customizeEntry [list $_Name "Show"] \
        [list ::DeviceStatistics::_customizeMenu "show"]

    gui menu command [list $_Name "Hide"] \
        [list ::DeviceStatistics::_closeWidget]
    gui menu customizeEntry [list $_Name "Hide"] \
        [list ::DeviceStatistics::_customizeMenu "hide"]

    gui menu separator [list $_Name]
    gui menu command [list $_Name "Export CSV"] \
        [list ::DeviceStatistics::_exportCSV]
    gui menu customizeEntry [list $_Name "Export CSV"] \
        [list ::DeviceStatistics::_customizeMenu "hide"]
}


# =============================================================================
# Finit - Finalize the plugin.
# =============================================================================
#
proc ::DeviceStatistics::Finit {} {
    variable _Name

    ::DeviceStatistics::_closeWidget

    gui menu removeEntry [list $_Name]
}


# -----------------------------------------------------------------------------
# _showWidget -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_showWidget {} {
    variable _Name
    variable _Table
    variable _Tree

    set w [gui window insertCustomWidget \
        -pluginNamespace "DeviceStatistics" \
        -destroyCallback ::DeviceStatistics::_onWidgetClosed \
        $_Name]

    ttk::frame $w.f
    set _Table [ttk::treeview $w.f.table]
    gui window autoscroll $w.f $_Table

    $_Table column #0 -stretch false

    grid $w.f -row 0 -column 0 -sticky news
    grid rowconfigure    $w 0 -weight 1
    grid columnconfigure $w 0 -weight 1

    gui database runAndRegisterChangedCallback ::DeviceStatistics::_showTree
}


# -----------------------------------------------------------------------------
# _closeWidget -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_closeWidget {} {
    variable _Name

    gui window removeCustomWidget $_Name
}


# -----------------------------------------------------------------------------
# _onWidgetClosed -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_onWidgetClosed {} {
    gui database removeChangedCallback ::DeviceStatistics::_showTree
}


# -----------------------------------------------------------------------------
# _customizeMenu -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_customizeMenu {mode menu} {
    variable _Table

    switch -exact -- $mode {
        "show" {
            set state [expr {[winfo exists $_Table] ? "disabled" : "normal"}]
        }
        "hide" {
            set state [expr {[winfo exists $_Table] ? "normal" : "disabled"}]
        }
        default {
            error "Bad mode: $mode"
        }
    }

    $menu entryconfigure end -state $state
}


# -----------------------------------------------------------------------------
# _initialize -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_initialize {db} {
    variable _DeviceList
    variable _BinningRange
    variable _Tree

    set _DeviceList {}
    set _Tree [struct::tree]

    if {$db == {}} {
        return
    }

    lappend _DeviceList {"# of Instances"}
    $db foreach primitive prim {
        set name [$db oid oname $prim]
        switch -exact -- [$db primitiveFuncOf $prim] {
            "NMOS"  -
            "PMOS"  {
                set binningNames {}
                lappend binningNames "$name (< [lindex $_BinningRange 0])"
                foreach value $_BinningRange {
                    lappend binningNames "$name ($value)"
                }
                lappend binningNames "$name (> [lindex $_BinningRange end])"
                lappend _DeviceList $binningNames "Semi-Total"
            }
            "CAP"   -
            "RES"   -
            "DIODE" {
                lappend _DeviceList $name "Semi-Total"
            }
            default {}
        }
    }
}


# -----------------------------------------------------------------------------
# _showTree -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_showTree {{db {}}} {
    variable _DeviceList
    variable _Table
    variable _TotalInstances
    variable _CurrentInstance

    if {$db == {}} {
        set db [gui database get]
    }

    ::DeviceStatistics::_initialize $db

    $_Table delete [$_Table children {}]

    set columnList {}
    foreach columns $_DeviceList {
        foreach col $columns {
            lappend columnList $col
        }
    }

    $_Table configure -columns $columnList
    set no -1
    foreach col $columnList {
        $_Table heading [incr no] -text $col
        $_Table column $no -stretch false
    }

    if {$db == {}} {
        return
    }

    zprogress begin
    zprogress push "Calculate Device Statistic" 1.0
    set _TotalInstances  [$db report objCount -inst]
    set _CurrentInstance 0

    ::DeviceStatistics::_start $db

    if {![zprogress pop]} {
        ::DeviceStatistics::_populateTree root {}
        $_Table item [lindex [$_Table children {}] 0] -open true
    }
    zprogress end
}


# -----------------------------------------------------------------------------
# _start -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_start {db} {
    set top [$db get_top_design]
    array set childDeviceTable {}
    ::DeviceStatistics::_calculate $db $top root 1 childDeviceTable
}


# -----------------------------------------------------------------------------
# _equal -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_equal {a b {epsilon 1e-15}} {
    set b [zdb formatvalue fromspice -hspice $b]
    return [expr {abs($a - $b) < $epsilon}]
}


# -----------------------------------------------------------------------------
# _getBinningName -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_getBinningName {value} {
    variable _BinningRange

    set a [zdb formatvalue fromspice -hspice $value]
    foreach binningValue $_BinningRange {
        set b [zdb formatvalue fromspice -hspice $binningValue]
        if {[::DeviceStatistics::_equal $a $b]} {
            return " ($binningValue)"
        }
    }

    set binningValue [lindex $_BinningRange 0]
    set b [zdb formatvalue fromspice -hspice $binningValue]
    if {$a < $b} {
        return " (< $binningValue)"
    }

    set binningValue [lindex $_BinningRange end]
    set b [zdb formatvalue fromspice -hspice $binningValue]
    if {$a > $b} {
        return " (> $binningValue)"
    }

    return ""
}


# -----------------------------------------------------------------------------
# _populateTree -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_populateTree {node item} {
    variable _Tree
    variable _Table
    variable _DeviceList

    if {$node ne "root"} {
        set     name      [$_Tree get $node name]
        set     valueList {}
        lappend valueList [$_Tree get $node numberOfInstances]

        foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
            foreach col $columns {
                lappend valueList [$_Tree get $node $col]
            }
            lappend valueList [$_Tree get $node ${col}_s]
        }

        set item [$_Table insert $item end -text $name -values $valueList]
    }

    foreach child [$_Tree children $node] {
        ::DeviceStatistics::_populateTree $child $item
    }
}


# -----------------------------------------------------------------------------
# _calculate -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_calculate {
    db parent node numberOfInstances deviceTableName
} {
    variable _DeviceList
    variable _Tree
    variable _TotalInstances
    variable _CurrentInstance

    upvar 1 $deviceTableName deviceTable

    if {[zprogress isinterrupted]} {
        return
    }

    set parentName [$db oid oname $parent]
    set id [$_Tree insert $node end]
    $_Tree set $id name $parentName

    foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
        foreach col $columns {
            set deviceTable($col) 0
        }
    }

    array set _cellTable {}

    set childList {}
    $db foreach inst $parent inst {
        set cellName [$db oid cname $inst]
        set isModule [$db isModule $inst]
        set count 1

        if {[zprogress update "" [incr _CurrentInstance] $_TotalInstances]} {
            return
        }

        if {!$isModule} {
            set func [$db primitiveFuncOf $inst]
            if {($func eq "NMOS") || ($func eq "PMOS")} {
                set length [$db flatattr $inst getMergedValue "L"]
                append cellName [::DeviceStatistics::_getBinningName $length]
            }

            set m [$db flatattr $inst getMergedValue "M"]
            if {[string is integer -strict $m]} {
                set count $m
            }

            set nfin [$db flatattr $inst getMergedValue "nfin"]
            if {[string is integer -strict $nfin]} {
                set count [expr {$count * $nfin}]
            }
        }

        if {[info exists _cellTable($cellName)]} {
            incr _cellTable($cellName) $count
        } else {
            set _cellTable($cellName) $count
            if {$isModule} {
                lappend childList [$db moduleOf $inst]
            }
        }
    }

    foreach child $childList {
        set childName [$db oid oname $child]
        set numberOfChildInstances $_cellTable($childName)

        array set childDeviceTable {}
        ::DeviceStatistics::_calculate $db $child $id \
            $numberOfChildInstances childDeviceTable

        foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
            foreach col $columns {
                incr deviceTable($col) \
                    [expr {$numberOfChildInstances * $childDeviceTable($col)}]
            }
        }
    }

    foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
        foreach col $columns {
            if {[info exists _cellTable($col)]} {
                incr deviceTable($col) $_cellTable($col)
            }
        }
    }

    set valueList [list $numberOfInstances]
    $_Tree set $id numberOfInstances $numberOfInstances
    foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
        set semiTotal 0
        foreach col $columns {
            $_Tree set $id $col $deviceTable($col)
            incr semiTotal $deviceTable($col)
        }
        $_Tree set $id ${col}_s [expr {$numberOfInstances * $semiTotal}]
    }
}


# -----------------------------------------------------------------------------
# _traverseTree -
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_traverseTree {channel node} {
    variable _Tree
    variable _DeviceList

    if {$node ne "root"} {
        set     row [list [$_Tree get $node name]]
        lappend row [$_Tree get $node numberOfInstances]
        foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
            foreach col $columns {
                lappend row [$_Tree get $node $col]
            }
            lappend row [$_Tree get $node ${col}_s]
        }
        puts $channel [join $row ","]
    }

    foreach child [$_Tree children $node] {
        set     row [list [$_Tree get $child name]]
        lappend row [$_Tree get $child numberOfInstances]
        foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
            foreach col $columns {
                lappend row [$_Tree get $child $col]
            }
            lappend row [$_Tree get $child ${col}_s]
        }

        puts $channel [join $row ","]
    }

    set length [llength $_DeviceList]
    incr length

    set sep {}
    for {set c 0} {$c < [llength $row]} {incr c} {
        lappend sep ""
    }
    puts $channel [join $sep ","]
    puts $channel [join $sep ","]

    foreach child [$_Tree children $node] {
        if {[llength [$_Tree children $child]] > 0} {
            DeviceStatistics::_traverseTree $channel $child
        }
    }
}


# -----------------------------------------------------------------------------
# _doExportCSV - Export a CSV file.
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_doExportCSV {fname} {
    variable _DeviceList

    set out [open $fname w]

    ##
    # Print a CSV file header.
    #
    set header [list "Module"]
    lappend header [lindex $_DeviceList 0]
    foreach {columns semiTotal} [lrange $_DeviceList 1 end] {
        foreach col $columns {
            lappend header $col
        }
        lappend header $semiTotal
    }
    puts $out [join $header ","]

    DeviceStatistics::_traverseTree $out root

    close $out
}


# -----------------------------------------------------------------------------
# _exportCSV - Export a CSV file.
# -----------------------------------------------------------------------------
#
proc ::DeviceStatistics::_exportCSV {} {
    variable _Table

    if {![winfo exists $_Table]} {
        return
    }

    set title "Export Device Statistics as CSV"
    set file_types {{"CSV Files" .csv}}
    set file_name [gui window fileDialog saveFile $title $file_types]

    if {$file_name ne ""} {
        ::DeviceStatistics::_doExportCSV $file_name
    }
}


##
# Initialize the plugin only if running in a *Vision GUI.
#
if {[string match "*vision*" [file tail [info nameofexecutable]]]} {
    ::DeviceStatistics::Init
}