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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import re
import argparse
import os
import json
import operator
from collections import defaultdict

# make sure the working dir is flow/
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

htmlOutput = "reports/report-table.html"
cssOutput = "reports/table.css"
designPathFile = "design-dir.txt"

dontUse = re.compile(
    r"""
clocks__details |
commit |
cpu__total |
mem__peak |
runtime__total |
total_time |
uuid |
version
""",
    re.VERBOSE | re.IGNORECASE,
)

# list of metrics that should be considered green if they increase
# all other metrics are considered better if they decrease in value
higherIsBetter = re.compile(
    r"""
__ws |
__wns |
__drv__max.*_limit |
__clock__slack |
__tns
""",
    re.VERBOSE | re.IGNORECASE,
)


helpText = """
Creates a HTML table with metric comparison between golden and current run
for each design.
"""
parser = argparse.ArgumentParser(description=helpText)
parser.add_argument("--variant", default="base")
args = parser.parse_args()

goldFilename = f"metadata-{args.variant}-ok.json"
runFilename = f"metadata.json"


def readMetrics(fname, justLoad=False):
    global tableDict
    try:
        with open(fname, "r") as f:
            tempDict = json.loads(f.read())
    except BaseException:
        print("Failed to open {}.".format(fname))
        return None
    if justLoad:
        return tempDict
    metrics = dict()
    for metric, value in tempDict.items():
        if not re.search(dontUse, metric):
            metrics[metric] = value
        else:
            continue
        if metric not in tableDict.keys():
            tableDict[metric] = list()
    return metrics


ops = {
    "<": operator.lt,
    ">": operator.gt,
    "<=": operator.le,
    ">=": operator.ge,
    "==": operator.eq,
    "!=": operator.ne,
}


def getDiff(metric, gold, run, rules):
    diff = "-"
    style = "no_change"
    if isNumber:
        diff = run - gold
        if gold != 0:
            percentage = "{:.2f}%".format(abs(diff / gold) * 100)
        else:
            percentage = "#DIV/0!"
        if run > gold:
            style = "green" if re.search(higherIsBetter, metric) else "orange"
        elif gold > run:
            style = "orange" if re.search(higherIsBetter, metric) else "green"
        for field, rule in rules.items():
            if metric != field:
                continue
            op = ops[rule["compare"]]
            value = rule["value"]
            if not op(run, value):
                style = "red"
        if diff != 0:
            if abs(diff) < 0.01:
                diff = "{:+.2} ({})".format(diff, percentage)
            else:
                diff = "{:+.2f} ({})".format(diff, percentage)
    return diff, style


tableDict = dict()
testList = list()
status = dict()

for logDir, dirs, files in sorted(os.walk("logs", topdown=False)):
    dirList = logDir.split(os.sep)
    if len(dirList) != 4:
        continue

    # basic info about test design
    platform = dirList[1]
    design = dirList[2]
    variant = dirList[3]
    test = "{} {} {}".format(platform, design, variant)
    reportDir = logDir.replace("logs", "reports")
    errors = 0

    print("-" * 79)
    print(test)
    print("-" * 79)

    try:
        with open(os.path.join(reportDir, designPathFile), "r") as f:
            designDir = f.read().strip()
    except BaseException:
        print("Failed to open {}.".format(designPathFile))
        designDir = os.path.join("designs", platform, design)
        errors += 1

    gold = readMetrics(os.path.join(designDir, goldFilename))
    if gold is None:
        errors += 1
        goldKeys = None
    else:
        goldKeys = gold.keys()

    run = readMetrics(os.path.join(reportDir, runFilename))
    if run is None:
        errors += 1
        runKeys = None
    else:
        runKeys = run.keys()

    rulesFilename = f"rules-{variant}.json"
    rules = readMetrics(os.path.join(designDir, rulesFilename), justLoad=True)
    if rules is None:
        errors += 1

    testList.append(test)
    if test not in status.keys():
        status[test] = dict()
        status[test]["error"] = errors
        status[test]["red"] = 0
        status[test]["orange"] = 0
        status[test]["no_change"] = 0
        status[test]["green"] = 0

    for metric in tableDict.keys():
        try:
            if metric in goldKeys:
                goldValue = gold[metric]
            else:
                goldValue = "N/A"
        except BaseException:
            goldValue = "ERR"
        try:
            if metric in runKeys:
                runValue = run[metric]
            else:
                runValue = "N/A"
        except BaseException:
            runValue = "ERR"
        try:
            goldValue = float(goldValue)
            runValue = float(runValue)
            isNumber = True
        except BaseException:
            isNumber = False
        tableDict[metric].append(goldValue)
        tableDict[metric].append(runValue)
        diff, style = getDiff(metric, goldValue, runValue, rules)
        tableDict[metric].append([diff, style])
        status[test][style] += 1

    print()

cssStyle = """/* table styles */
table {
  border-collapse: collapse;
  margin: 25px 0;
  font-size: 0.9em;
  font-family: sans-serif;
  min-width: 400px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
table thead tr {
  background-color: #009879;
  color: #ffffff;
  text-align: left;
}
table th,
table td {
  padding: 12px 15px;
}
table tbody tr {
  border-bottom: 1px solid #dddddd;
}
table tbody tr:nth-of-type(even) {
  background-color: #f3f3f3;
}
table td:nth-child(n+2) {
  text-align: center;
}
table tbody tr:last-of-type {
  border-bottom: 2px solid #009879;
}
table tbody tr.active-row {
  font-weight: bold;
  color: #009879;
}
table th,
table td:nth-child(1),
.image-table td,
.summary-table td {
  border-right: solid 2px;
  border-left: solid 2px;
}
table th {
  border-top: solid 2px;
}
.main-table th {
  position: sticky;
  top: 0;
  background-color: #727272;
  color: #e0e0e0;
}
.main-table tr:nth-of-type(even) td:nth-child(1) {
  background-color: #f3f3f3;
}
.main-table tr:nth-of-type(odd) td:nth-child(1) {
  background-color: #ffffff;
}
.main-table tr:nth-child(2),
.main-table tr:nth-child(2) td:nth-child(1) {
  position: sticky;
  top: 44px;
  background-color: #727272;
  color: #e0e0e0;
  z-index: 2;
}
.main-table th:nth-child(1),
.main-table td:nth-child(1) {
  position: sticky;
  left: 0;
}
.main-table th:nth-child(1){
  z-index: 2;
}
.main-table td:nth-child(3n+4) {
  border-left: dotted 1px;
}
.main-table td:nth-child(3n+1) {
  border-right: solid 2px;
}
div.gallery {
  margin: 5px;
  float: left;
  height: 300px;
}
div.gallery:hover {
  border: 1px solid #777;
}
div.gallery img {
  max-height: 300px;
  width: auto;
}
div.desc {
  padding: 10px;
  text-align: center;
}
"""

with open(cssOutput, "w") as f:
    f.writelines(cssStyle)

head = """<!DOCTYPE html>
<html lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="table.css">
</head>

<body>
"""

tail = """</body>
</html>
"""


def add_image(path, platform, view):
    return f"""<td>
  <div class="gallery">
    <div class="desc">
      {platform} - {view}
    </div>
    <a target="_blank" href="{path}">
      <img src="{path}" alt="{platform}/{view}">
    </a>
  </div>
</td>
"""


# save_images.tcl asks OpenROAD for .webp, but the GUI silently falls back to
# .png when the Qt build has no webp writer, which used to leave the gallery
# empty. Accept either, and derive the view name by stripping whatever image
# extensions the file ended up with rather than a fixed number of characters.
IMAGE_EXTENSIONS = (".webp", ".png")


def image_view_name(file):
    view, ext = os.path.splitext(file)
    while ext.lower() in IMAGE_EXTENSIONS:
        file = view
        view, ext = os.path.splitext(file)
    return file


platforms = set()
designs = set()
views = set()
images = defaultdict(lambda: defaultdict(dict))
for parents, dirs, files in sorted(os.walk("reports", topdown=False)):
    for file in files:
        if file.lower().endswith(IMAGE_EXTENSIONS):
            path = os.path.join(parents, file).replace("reports", ".")
            platform, design = path.split(os.sep)[1:3]
            view = image_view_name(file)
            designs.add(design)
            platforms.add(platform)
            views.add(view)
            images[design][platform][view] = path

platforms = sorted(platforms)
designs = sorted(designs)
view = sorted(views)


def write_gallery(design, platforms, views):
    htmlGallery = f"reports/report-gallery-{design}.html"
    with open(htmlGallery, "w") as f:
        gallery = "  <h1>Image Gallery</h1>\n"
        gallery += '<table class="image-table">\n'
        gallery += "<tr>\n"
        for key in platforms:
            gallery += f"<th>{key}</th>\n"
        gallery += "</tr>\n"
        for view in views:
            gallery += "<tr>\n"
            for platform in platforms:
                if platform in images[design] and view in images[design][platform]:
                    gallery += add_image(images[design][platform][view], platform, view)
                else:
                    gallery += "<td>\n</td>\n"
            gallery += "</tr>\n"
        gallery += "</table>\n"
        html = head + gallery + tail
        f.writelines(html)


for design in designs:
    write_gallery(design, platforms, views)

subColumns = ["Gold", "Current", "Diff (%)"]

table = ""
with open(htmlOutput, "w") as f:
    # Compute summary rows
    noChangeList = list()
    improvementList = list()
    degradationList = list()
    failedMetricsList = list()
    parsingErrorList = list()
    designsMoreImprovements = list()
    designsMoreDegradations = list()
    designsNoChange = list()
    designsSameNumber = list()
    designsRed = list()
    designsParsingErrors = list()
    for test, value in status.items():
        noChange = value["no_change"]
        improvements = value["green"]
        degradations = value["orange"]
        failedMetrics = value["red"]
        parsingErrors = value["error"]
        noChangeList.append(noChange)
        improvementList.append(improvements)
        degradationList.append(degradations)
        failedMetricsList.append(failedMetrics)
        parsingErrorList.append(parsingErrors)
        if parsingErrors > 0:
            designsParsingErrors.append(test)
        if failedMetrics > 0:
            designsRed.append(test)
        elif improvements == degradations:
            if improvements == 0:
                designsNoChange.append(test)
            else:
                designsSameNumber.append(test)
        elif improvements > degradations:
            designsMoreImprovements.append(test)
        else:
            designsMoreDegradations.append(test)

    # Summary table begin
    table += "\n<h1>Metrics Overview</h1>\n"

    txt = "Number of designs that failed parsing: "
    txt += "{}\n".format(len(designsParsingErrors))
    txt += "    {}\n".format(", ".join(designsParsingErrors))
    table += "<pre>\n{}\n</pre>\n".format(txt.strip())

    txt = "Number of designs failing metrics checks: "
    txt += "{}\n".format(len(designsRed))
    txt += "    {}\n".format(", ".join(designsRed))
    table += "<pre>\n{}\n</pre>\n".format(txt.strip())

    txt = "Number of designs with more improvements: "
    txt += "{}\n".format(len(designsMoreImprovements))
    txt += "    {}\n".format(", ".join(designsMoreImprovements))
    table += "<pre>\n{}\n</pre>\n".format(txt.strip())

    txt = "Number of designs with more degradations: "
    txt += "{}\n".format(len(designsMoreDegradations))
    txt += "    {}\n".format(", ".join(designsMoreDegradations))
    table += "<pre>\n{}\n</pre>\n".format(txt.strip())

    txt = "Number of designs with same number of degradations and improvements: "
    txt += "{}\n".format(len(designsSameNumber))
    txt += "    {}\n".format(", ".join(designsSameNumber))
    table += "<pre>\n{}\n</pre>\n".format(txt.strip())

    txt = "Number of designs with no change: "
    txt += "{}\n".format(len(designsNoChange))
    txt += "    {}\n".format(", ".join(designsNoChange))
    table += "<pre>\n{}\n</pre>\n".format(txt.strip())

    table += '\n<table class="summary-table">\n'
    # Summary header
    table += "  <tr>\n"
    table += "    <th>Summary</th>\n"
    for test in testList + ["Total"]:
        table += "    <th>{}</th>\n".format(test)
    table += "  </tr>\n"

    # Summary rows

    title = "Parsing Errors"
    table += "  <tr>\n"
    table += '    <td bgcolor="brown">{}</td>\n'.format(title)
    for value in parsingErrorList:
        table += '    <td title="{}">{}</td>\n'.format(title, value)
    table += "    <td>{}</td>\n".format(sum(parsingErrorList))
    table += "  </tr>\n"

    title = "Failed Metrics"
    table += "  <tr>\n"
    table += '    <td bgcolor="red">{}</td>\n'.format(title)
    for value in failedMetricsList:
        table += '    <td title="{}">{}</td>\n'.format(title, value)
    table += "    <td>{}</td>\n".format(sum(failedMetricsList))
    table += "  </tr>\n"

    title = "Degradation"
    table += "  <tr>\n"
    table += '    <td bgcolor="orange">{}</td>\n'.format(title)
    for value in degradationList:
        table += '    <td title="{}">{}</td>\n'.format(title, value)
    table += "    <td>{}</td>\n".format(sum(degradationList))
    table += "  </tr>\n"

    title = "No Change"
    table += "  <tr>\n"
    table += "    <td>{}</td>\n".format(title)
    for value in noChangeList:
        table += '    <td title="{}">{}</td>\n'.format(title, value)
    table += "    <td>{}</td>\n".format(sum(noChangeList))
    table += "  </tr>\n"

    title = "Improvement"
    table += "  <tr>\n"
    table += '    <td bgcolor="green">{}</td>\n'.format(title)
    for value in improvementList:
        table += '    <td title="{}">{}</td>\n'.format(title, value)
    table += "    <td>{}</td>\n".format(sum(improvementList))
    table += "  </tr>\n"

    table += "</table>\n"

    # Main table begin
    table += "\n<h1>Metrics Comparison Per Design</h1>\n"
    table += '<table class="main-table">\n'
    # Main table header
    table += "  <tr>\n"
    table += "    <th>Metric</th>\n"
    for test in testList:
        table += '    <th colspan="3">{}</th>\n'.format(test)
    table += "  </tr>\n"

    # Main table header subdivision
    table += "  <tr>\n"
    table += "    <td>Name</td>\n"
    for _ in testList:
        for col in subColumns:
            table += "    <td>{}</td>\n".format(col)
    table += "  </tr>\n"

    # Main table rows
    for metric, entry in tableDict.items():
        table += "  <tr>\n"
        table += "    <td>{}</td>\n".format(metric)
        title = 'title="{}"'.format(metric)

        for num in range(0, len(entry), len(subColumns)):
            goldValue = "{}".format(entry[num])
            props = title
            if goldValue == "N/A":
                props += "bgcolor=yellow"
            elif goldValue == "ERR":
                props += "bgcolor=brown"
            table += "    <td {}>{}</td>\n".format(props, goldValue)

            runValue = "{}".format(entry[num + 1])
            props = title
            if runValue == "N/A":
                props += "bgcolor=yellow"
            elif runValue == "ERR":
                props += "bgcolor=brown"
            table += "    <td {}>{}</td>\n".format(props, runValue)

            diffValue, style = entry[num + 2]
            props = title
            if style == "no_change":
                style = ""
            props = '{} bgcolor="{}"'.format(props, style)
            table += "    <td {}>{}</td>\n".format(props, diffValue)

        table += "  </tr>\n"

    table += "</table>\n\n"

    fname = "reports/report.log"
    content = ""
    if os.path.isfile(fname):
        with open(fname, "r") as reportFile:
            content = "".join(reportFile.readlines()[4:])
        content = "<pre>\n" + content + "\n</pre>\n"
        content = "<h1>Flow Finish State and Log Summary</h1>\n" + content

    html = head + table + content + tail
    f.writelines(html)