Skip to content

Commit 2d542df

Browse files
committed
feat: Add native Tcl path correlation extraction and QoR plotter
1 parent 107b46a commit 2d542df

10 files changed

Lines changed: 650 additions & 8 deletions

‎flow/BUILD‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,3 +242,23 @@ py_binary(
242242
],
243243
visibility = ["//visibility:public"],
244244
)
245+
246+
py_binary(
247+
name = "aggregate_path_data",
248+
srcs = ["scripts/aggregate_path_data.py"],
249+
deps = [
250+
"@orfs-pip//pandas",
251+
],
252+
visibility = ["//visibility:public"],
253+
)
254+
255+
py_binary(
256+
name = "qor_plotter",
257+
srcs = ["scripts/qor_plotter.py"],
258+
deps = [
259+
"@orfs-pip//pandas",
260+
"@orfs-pip//pyside6",
261+
"@orfs-pip//matplotlib",
262+
],
263+
visibility = ["//visibility:public"],
264+
)

‎flow/scripts/dump_paths_grt.tcl‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
set ::env(DUMP_STAGE_PREFIX) "5_grt"
2+
set ::env(DUMP_OUT_FILE) "$::env(DUMP_DIR)/5_grt_timing_paths.csv"
3+
source flow/scripts/dump_paths_native.tcl

‎flow/scripts/dump_paths_native.tcl‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Native Tcl script to extract path details directly from OpenSTA into CSV
2+
# Usage: source dump_paths_native.tcl
3+
4+
set out_file $::env(DUMP_OUT_FILE)
5+
set stage_prefix $::env(DUMP_STAGE_PREFIX)
6+
7+
if {![info exists ::env(DUMP_OUT_FILE)] || ![info exists ::env(DUMP_STAGE_PREFIX)]} {
8+
puts "Error: DUMP_OUT_FILE or DUMP_STAGE_PREFIX not set."
9+
exit 1
10+
}
11+
12+
puts "Extracting paths natively for stage: $stage_prefix to $out_file"
13+
14+
set fp [open $out_file w]
15+
# We only write the header if the file is empty (we might append in Python, or write standalone)
16+
puts $fp "startpoint,endpoint,${stage_prefix}_slack,${stage_prefix}_path_delay,${stage_prefix}_net_delay,${stage_prefix}_logic_delay,${stage_prefix}_total_cap,${stage_prefix}_buffers"
17+
18+
# Get top 2000 paths
19+
set paths [find_timing_paths -path_delay max -group_count 2000]
20+
21+
foreach path_end $paths {
22+
set slack [$path_end slack]
23+
set path_delay [$path_end arrival]
24+
25+
set start_path [$path_end start_path]
26+
set start_pin [$start_path pin]
27+
set end_pin [$path_end pin]
28+
29+
set startpoint [get_name $start_pin]
30+
set endpoint [get_name $end_pin]
31+
32+
# Capture the detailed report for this path in memory
33+
utl::redirectStringBegin
34+
report_checks -path $path_end -digits 4 -fields {capacitance net slew}
35+
set report_str [utl::redirectStringEnd]
36+
37+
set net_delay 0.0
38+
set logic_delay 0.0
39+
set total_cap 0.0
40+
set buffers 0
41+
42+
# Parse the report lines
43+
set lines [split $report_str "\n"]
44+
foreach line $lines {
45+
# Check for cap: looking for a line with cap value and delay
46+
# Format typical: cap net delay
47+
if {[regexp {^\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([v\^])\s+([^\s]+)\s+\(([^\)]+)\)} $line -> cap slew delay edge pin_name cell_type]} {
48+
set total_cap [expr {$total_cap + $cap}]
49+
if {[regexp {^sky130_fd_sc_hd__(buf|dly)} $cell_type] || [regexp {^BUFx} $cell_type]} {
50+
incr buffers
51+
}
52+
}
53+
54+
# In OpenSTA report_checks, net delay lines often have net name
55+
if {[regexp {^\s+([0-9\.]+)\s+([0-9\.]+)\s+([v\^])\s+([^\s]+)\s+\(net\)} $line -> incr_delay total_delay edge net_name]} {
56+
set net_delay [expr {$net_delay + $incr_delay}]
57+
}
58+
# Wait, the column format is different with -fields {capacitance net slew}. Let's be careful.
59+
}
60+
61+
# Since exact regex parsing of report_checks column is brittle, an easier way is to just know
62+
# that Path_delay = Net_delay + Logic_delay.
63+
# Actually, logic delay lines have the cell instance name. Let's do it robustly:
64+
set logic_delay 0.0
65+
set net_delay 0.0
66+
foreach line $lines {
67+
if {[regexp {^\s+([0-9\.]+)\s+[0-9\.]+\s+[v\^]\s+[^\s]+\s+\((net|in|out|.*)\)} $line -> incr_delay type]} {
68+
if {$type == "net"} {
69+
set net_delay [expr {$net_delay + $incr_delay}]
70+
} elseif {$type != "in" && $type != "out"} {
71+
# Cell delay
72+
set logic_delay [expr {$logic_delay + $incr_delay}]
73+
if {[regexp {buf|dly} $type] || [regexp {BUF} $type]} {
74+
incr buffers
75+
}
76+
}
77+
}
78+
if {[regexp {^\s+([0-9\.]+)\s+[0-9\.]+\s+[0-9\.]+\s+[0-9\.]+\s+[v\^]\s+[^\s]+\s+\(net\)} $line -> cap]} {
79+
set total_cap [expr {$total_cap + $cap}]
80+
}
81+
}
82+
83+
puts $fp "$startpoint,$endpoint,$slack,$path_delay,$net_delay,$logic_delay,$total_cap,$buffers"
84+
}
85+
86+
close $fp
87+
puts "Dump complete."

‎flow/scripts/dump_paths_place.tcl‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
set ::env(DUMP_STAGE_PREFIX) "3_place"
2+
set ::env(DUMP_OUT_FILE) "$::env(DUMP_DIR)/3_place_timing_paths.csv"
3+
source flow/scripts/dump_paths_native.tcl

‎flow/scripts/dump_paths_route.tcl‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
set ::env(DUMP_STAGE_PREFIX) "6_route"
2+
set ::env(DUMP_OUT_FILE) "$::env(DUMP_DIR)/6_route_timing_paths.csv"
3+
source flow/scripts/dump_paths_native.tcl

‎flow/scripts/global_place.tcl‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,14 @@ append_env_var global_placement_args GPL_ROUTABILITY_DRIVEN -routability_driven
2828

2929
append_env_var global_placement_args GPL_RANDOM_SEED -random_seed 1
3030

31-
if { [info exists ::env(GPL_WIRELENGTH_PENALTY)] } {
32-
lappend global_placement_args -init_wirelength_coef $::env(GPL_WIRELENGTH_PENALTY)
33-
}
31+
if { !$::env(GPL_USE_ENGINE_DEFAULTS) } {
32+
if { [info exists ::env(GPL_WIRELENGTH_PENALTY)] } {
33+
lappend global_placement_args -init_wirelength_coef $::env(GPL_WIRELENGTH_PENALTY)
34+
}
3435

35-
if { [info exists ::env(GPL_TIMING_SPAN_CLOCK_PERCENT)] } {
36-
lappend global_placement_args -virtual_cts_max_skew_fraction $::env(GPL_TIMING_SPAN_CLOCK_PERCENT)
36+
if { [info exists ::env(GPL_TIMING_SPAN_CLOCK_PERCENT)] } {
37+
lappend global_placement_args -virtual_cts_max_skew_fraction $::env(GPL_TIMING_SPAN_CLOCK_PERCENT)
38+
}
3739
}
3840

3941
# Parameters for timing driven mode in global placement

‎flow/scripts/qor_plotter.py‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import sys
2+
import os
3+
import subprocess
4+
import pandas as pd
5+
try:
6+
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTableView, QComboBox, QLabel, QMessageBox
7+
from PySide6.QtCore import QAbstractTableModel, Qt
8+
except ImportError:
9+
print("PySide6 is required. Please install it.")
10+
sys.exit(1)
11+
12+
import matplotlib
13+
matplotlib.use('Qt5Agg')
14+
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
15+
from matplotlib.figure import Figure
16+
17+
class PandasModel(QAbstractTableModel):
18+
def __init__(self, data):
19+
super().__init__()
20+
self._data = data
21+
22+
def rowCount(self, parent=None):
23+
return self._data.shape[0]
24+
25+
def columnCount(self, parent=None):
26+
return self._data.shape[1]
27+
28+
def data(self, index, role=Qt.DisplayRole):
29+
if index.isValid() and role == Qt.DisplayRole:
30+
val = self._data.iloc[index.row(), index.column()]
31+
if pd.isna(val):
32+
return ""
33+
if isinstance(val, float):
34+
return f"{val:.4f}"
35+
return str(val)
36+
return None
37+
38+
def headerData(self, col, orientation, role):
39+
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
40+
return self._data.columns[col]
41+
return None
42+
43+
class QoRPlotter(QMainWindow):
44+
def __init__(self, csv_file):
45+
super().__init__()
46+
self.setWindowTitle(f"QoR Path Correlation Debugger - {os.path.basename(csv_file)}")
47+
self.df = pd.read_csv(csv_file)
48+
49+
main_widget = QWidget()
50+
self.setCentralWidget(main_widget)
51+
layout = QVBoxLayout(main_widget)
52+
53+
# Controls
54+
ctrl_layout = QHBoxLayout()
55+
self.x_axis_cb = QComboBox()
56+
self.y_axis_cb = QComboBox()
57+
58+
numeric_cols = self.df.select_dtypes(include=['float64', 'int64']).columns
59+
self.x_axis_cb.addItems(numeric_cols)
60+
self.y_axis_cb.addItems(numeric_cols)
61+
62+
# Try to set sensible defaults
63+
slack_cols = [c for c in numeric_cols if 'slack' in c]
64+
if len(slack_cols) >= 2:
65+
self.x_axis_cb.setCurrentText(slack_cols[0])
66+
self.y_axis_cb.setCurrentText(slack_cols[-1])
67+
68+
self.x_axis_cb.currentTextChanged.connect(self.update_plot)
69+
self.y_axis_cb.currentTextChanged.connect(self.update_plot)
70+
71+
ctrl_layout.addWidget(QLabel("X-Axis:"))
72+
ctrl_layout.addWidget(self.x_axis_cb)
73+
ctrl_layout.addWidget(QLabel("Y-Axis:"))
74+
ctrl_layout.addWidget(self.y_axis_cb)
75+
layout.addLayout(ctrl_layout)
76+
77+
# Plot
78+
self.fig = Figure(figsize=(8, 6))
79+
self.canvas = FigureCanvas(self.fig)
80+
self.ax = self.fig.add_subplot(111)
81+
layout.addWidget(self.canvas)
82+
83+
# Table
84+
self.table = QTableView()
85+
self.model = PandasModel(self.df)
86+
self.table.setModel(self.model)
87+
layout.addWidget(self.table)
88+
89+
self.update_plot()
90+
91+
def update_plot(self):
92+
self.ax.clear()
93+
x_col = self.x_axis_cb.currentText()
94+
y_col = self.y_axis_cb.currentText()
95+
96+
if x_col and y_col:
97+
x_data = self.df[x_col]
98+
y_data = self.df[y_col]
99+
self.ax.scatter(x_data, y_data, alpha=0.5)
100+
101+
# Diagonal line
102+
min_val = min(x_data.min(), y_data.min())
103+
max_val = max(x_data.max(), y_data.max())
104+
self.ax.plot([min_val, max_val], [min_val, max_val], 'r--')
105+
106+
self.ax.set_xlabel(x_col)
107+
self.ax.set_ylabel(y_col)
108+
self.ax.grid(True)
109+
self.ax.set_title(f"Correlation: {x_col} vs {y_col}")
110+
self.fig.tight_layout()
111+
self.canvas.draw()
112+
113+
def build_and_extract_data(pdk, design):
114+
print(f"Building and extracting path data for {pdk} {design}...")
115+
cwd = os.getcwd()
116+
dump_dir = os.path.join(cwd, f"qor_dumps_{pdk}_{design}")
117+
os.makedirs(dump_dir, exist_ok=True)
118+
119+
cmd = [
120+
"bazelisk", "build",
121+
"--define=GPL_USE_ENGINE_DEFAULTS=1",
122+
"--spawn_strategy=local",
123+
f"--action_env=DUMP_DIR={dump_dir}",
124+
f"--define=POST_GLOBAL_PLACE_TCL={cwd}/flow/scripts/dump_paths_place.tcl",
125+
f"--define=POST_GLOBAL_ROUTE_TCL={cwd}/flow/scripts/dump_paths_grt.tcl",
126+
f"--define=POST_DETAIL_ROUTE_TCL={cwd}/flow/scripts/dump_paths_route.tcl",
127+
f"//flow/designs/{pdk}/{design}:{design}_route"
128+
]
129+
130+
result = subprocess.run(cmd, cwd=cwd)
131+
if result.returncode != 0:
132+
print(f"Error: Build failed for {pdk} {design}.")
133+
sys.exit(1)
134+
135+
# Aggregate
136+
try:
137+
df3 = pd.read_csv(os.path.join(dump_dir, "3_place_timing_paths.csv"))
138+
df5 = pd.read_csv(os.path.join(dump_dir, "5_grt_timing_paths.csv"))
139+
df6 = pd.read_csv(os.path.join(dump_dir, "6_route_timing_paths.csv"))
140+
except Exception as e:
141+
print(f"Error reading CSVs: {e}")
142+
sys.exit(1)
143+
144+
df_merged = df3.merge(df5, on=['startpoint', 'endpoint'], how='outer')
145+
df_merged = df_merged.merge(df6, on=['startpoint', 'endpoint'], how='outer')
146+
147+
out_csv = os.path.join(cwd, f"path_data_{pdk}_{design}.csv")
148+
df_merged.to_csv(out_csv, index=False)
149+
print(f"Saved aggregated data to {out_csv}")
150+
return out_csv
151+
152+
if __name__ == "__main__":
153+
app = QApplication(sys.argv)
154+
155+
csv_file = None
156+
if len(sys.argv) < 2:
157+
# Build for both pdks
158+
csv_sky130 = build_and_extract_data("sky130hd", "gcd")
159+
csv_asap7 = build_and_extract_data("asap7", "gcd")
160+
161+
# Combine them or just open sky130 by default and let user know
162+
# For simplicity, let's open sky130 and asap7 in different windows
163+
w1 = QoRPlotter(csv_sky130)
164+
w1.resize(1000, 800)
165+
w1.show()
166+
167+
w2 = QoRPlotter(csv_asap7)
168+
w2.resize(1000, 800)
169+
w2.show()
170+
171+
sys.exit(app.exec())
172+
else:
173+
csv_file = sys.argv[1]
174+
window = QoRPlotter(csv_file)
175+
window.resize(1000, 800)
176+
window.show()
177+
sys.exit(app.exec())

‎flow/scripts/variables.yaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,12 @@ GPL_TIMING_DRIVEN:
664664
stages:
665665
- place
666666
default: 1
667+
GPL_USE_ENGINE_DEFAULTS:
668+
description: |
669+
If set to 1, ignores ORFS-specific parameters and forces the global placement engine to use its internal hardcoded defaults.
670+
stages:
671+
- place
672+
default: 0
667673
GPL_WIRELENGTH_PENALTY:
668674
description: |
669675
Global placement wirelength penalty (passed as -init_wirelength_coef or similar logic).

‎flow/util/requirements.in‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
matplotlib==3.10.0
22
PyYAML==6.0.2
33
optuna
4+
PySide6
5+
pandas

0 commit comments

Comments
 (0)