From 8e9c16d55ffe7777ce46e93cb4b24d2632d7eaf0 Mon Sep 17 00:00:00 2001 From: Arthur Koucher Date: Fri, 31 Jul 2026 14:54:30 -0300 Subject: [PATCH 1/6] correlation RC mechanism clean-up: 1) Bundle write_segment_rc and write_net_rc into write_rc which now generates two .csv files. 2) Make correlateRC.py be able to consume both files as input. Nets file is used for plotting, segments file is used for set_layer_rc. 3) Adjust make commands accordingly and remove unused code comment. Signed-off-by: Arthur Koucher --- docs/tutorials/SetRC.md | 19 +- flow/util/correlateRC.py | 615 +++++++++++--------------- flow/util/utils.mk | 31 +- flow/util/write_net_rc.tcl | 84 ---- flow/util/write_net_rc_script.tcl | 13 - flow/util/write_rc.tcl | 20 + flow/util/write_rc_helper.tcl | 179 ++++++++ flow/util/write_segment_rc.tcl | 90 ---- flow/util/write_segment_rc_script.tcl | 10 - 9 files changed, 476 insertions(+), 585 deletions(-) delete mode 100644 flow/util/write_net_rc.tcl delete mode 100644 flow/util/write_net_rc_script.tcl create mode 100644 flow/util/write_rc.tcl create mode 100644 flow/util/write_rc_helper.tcl delete mode 100644 flow/util/write_segment_rc.tcl delete mode 100644 flow/util/write_segment_rc_script.tcl diff --git a/docs/tutorials/SetRC.md b/docs/tutorials/SetRC.md index e17cd3d382..46995600fa 100644 --- a/docs/tutorials/SetRC.md +++ b/docs/tutorials/SetRC.md @@ -29,11 +29,14 @@ Unit RC values can be extracted by completing P&R flow for relevant designs in O ``` % cd OpenROAD-flow-scripts/flow % make DESIGN_CONFIG=./designs/asap7/ibex/config.mk -% make DESIGN_CONFIG=./designs/asap7/ibex/config.mk write_segment_rc +% make DESIGN_CONFIG=./designs/asap7/ibex/config.mk write_rc ``` -This will generate a segment RC CSV file under results directory. For -example, ./results/asap7/ibex/base/6_segment_rc.csv. +This will generate a segment RC CSV file and a net RC CSV file under results +directory. For example, ./results/asap7/ibex/base/6_segments_rc.csv and +./results/asap7/ibex/base/6_nets_rc.csv. The segments data is used to fit the +RC values, while the nets data is used to plot the difference between the +global route estimates and the extracted parasitics. ``` % make DESIGN_CONFIG=./designs/asap7/ibex/config.mk correlate_rc @@ -60,12 +63,12 @@ Segment RC CSV files from multiple designs can be combined to produce one large ``` % make DESIGN_CONFIG=./designs/asap7/ibex/config.mk -% make DESIGN_CONFIG=./designs/asap7/ibex/config.mk write_segment_rc +% make DESIGN_CONFIG=./designs/asap7/ibex/config.mk write_rc % make DESIGN_CONFIG=./designs/asap7/jpeg/config.mk -% make DESIGN_CONFIG=./designs/asap7/jpeg/config.mk write_segment_rc -% cat ./results/asap7/ibex/base/6_segment_rc.csv ./results/asap7/jpeg/base/6_segment_rc.csv > combined_segment_rc.csv -% ./util/correlateRC.py --mode segment combined_segment_rc.csv -reading combined_segment_rc.csv +% make DESIGN_CONFIG=./designs/asap7/jpeg/config.mk write_rc +% cat ./results/asap7/ibex/base/6_segments_rc.csv ./results/asap7/jpeg/base/6_segments_rc.csv > combined_segments_rc.csv +% ./util/correlateRC.py -segments_rc_file combined_segments_rc.csv +Reading combined_segments_rc.csv. Units: resistance [kohm/um], capacitance [pf/um] diff --git a/flow/util/correlateRC.py b/flow/util/correlateRC.py index b8d75922ac..c20c1bee68 100755 --- a/flow/util/correlateRC.py +++ b/flow/util/correlateRC.py @@ -3,20 +3,22 @@ # Script for generating and comparing per-layer parasitics values. # These values are used by set_layer_rc and will be the base # values for the parasitics estimations across the flow. +# +# Both input files are written by "make write_rc": the set_layer_rc and +# set_wire_rc values are fitted from the segments data, while the plots +# compare the GRT estimates against the RCX values of the nets. -import os from sys import exit, stderr from collections import defaultdict -import traceback -import collections import argparse -import re import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt -LAYER_HEADER_RE = re.compile("^([^\\(]+)\\(([^\\)]+)\\)$") +# Auxiliary variables to catch swapped input .csv files. +SEGMENTS_COLUMNS = 6 +NETS_MIN_COLUMNS = 7 # Helper functions # ============================================================================= @@ -64,437 +66,324 @@ def parse_args(): help="Plot grt/rcx resistance differences", ) parser.add_argument( - "--mode", + "-nets_rc_file", required=False, - choices=["net", "segment"], - default="net", - help="Input mode: 'net' for net-level RC (make write_net_rc), 'segment' for segment-level RC (make write_segment_rc)", + nargs="+", + default=[], + metavar="FILE", + help="Net RC csv file(s) written by make write_rc, required for the plots", ) parser.add_argument( - "rc_file", nargs="+", help="rc csv file written by make compare_rc" + "-segments_rc_file", + required=True, + nargs="+", + metavar="FILE", + help="Segment RC csv file(s) written by make write_rc, used to fit the layer RC values", ) args = parser.parse_args() + if (args.plot_cap or args.plot_res) and not args.nets_rc_file: + parser.error("-nets_rc_file is required to plot the grt/rcx differences") + return args -args = parse_args() +# Parser Helpers +# ============================================================================= -# kohm/ff nangate45, asap7 -# kohm/pf sky130hd, sky130hs -res_unit = args.res_unit -if res_unit == "ohm": - res_scale = 1 -elif res_unit == "kohm": - res_scale = 1e3 -else: - print("unknown resistance unit") - exit(1) +def read_nets_rc(file_names): + nets = [] -cap_unit = args.cap_unit -if cap_unit == "ff": - cap_scale = 1e-15 -elif cap_unit == "pf": - cap_scale = 1e-12 -else: - print("unknown capacitance unit") - exit(1) + for file_name in file_names: + print(f"Reading {file_name}.") + with open(file_name) as file: + for line in file: + line = line.strip() + if not line or line.startswith("#"): + continue -def makeDict(): - return collections.defaultdict(makeDict) + tokens = line.split(",") + if len(tokens) < NETS_MIN_COLUMNS: + print(f"Malformed net RC line: {line}", file=stderr) + exit(1) -data = makeDict() + nets.append( + { + "file_name": file_name, + "name": tokens[0], + "type": tokens[1], + "grt_res": float(tokens[2]), + "grt_cap": float(tokens[3]), + "rcx_res": float(tokens[4]), + "rcx_cap": float(tokens[5]), + } + ) -stack = [] -stack_line = None + if not nets: + print("No net RC data found.", file=stderr) + exit(1) -# For segment mode. -layer_segments = defaultdict( - lambda: {"lengths": [], "resistances": [], "capacitances": []} -) -layer_net_type_length = defaultdict(lambda: defaultdict(float)) -routing_layers = [] -routing_layers_line = None - -# indices of relevant layers (routable layers or via layers) -active_layers = set() - -# Parse the cap CSV file generated by compare_rc_script.tcl -for rc_file in args.rc_file: - design = rc_file - print("reading", design) - with open(rc_file) as f: - nonGrtNets = 0 - for line in f: - if line.startswith("# routing layers: "): - if routing_layers_line is not None and routing_layers_line != line: - print(f"layer stack inconsistent", file=stderr) - exit(1) - elif routing_layers_line is None: - routing_layers = ( - line.removeprefix("# routing layers: ").strip().split(" ") - ) - routing_layers_line = line - continue - - if line.startswith("# stack: "): - if stack_line is not None and stack_line != line: - print(f"layer stack inconsistent", file=stderr) + return nets + + +def read_segments_rc(file_names): + layer_segments = defaultdict( + lambda: {"lengths": [], "resistances": [], "capacitances": []} + ) + layer_net_type_length = defaultdict(lambda: defaultdict(float)) + routing_layers = [] + routing_layers_line = None + + for file_name in file_names: + print(f"Reading {file_name}.") + with open(file_name) as file: + for line in file: + if line.startswith("# routing layers: "): + if routing_layers_line is None: + routing_layers = ( + line.removeprefix("# routing layers: ").strip().split(" ") + ) + routing_layers_line = line + elif routing_layers_line != line: + print("Layer stack inconsistent.", file=stderr) + exit(1) + continue + + line = line.strip() + + if not line or line.startswith("#"): + continue + + tokens = line.split(",") + + if len(tokens) != SEGMENTS_COLUMNS: + print(f"Malformed segment RC line: {line}", file=stderr) exit(1) - elif stack_line is None: - for layer in line.removeprefix("# stack: ").strip().split(" "): - name = layer - is_routing = False - via_resist = 0.0 - if layer.endswith(")"): - # layer name has extra data - match = LAYER_HEADER_RE.match(layer) - assert match - name = match.group(1) - if match.group(2) == "routing": - is_routing = True - else: - via_resist = float(match.group(2)) - stack.append((name, is_routing, via_resist)) - stack_line = line - continue - - tokens = line.strip().split(",") - - if args.mode == "segment": - layer_segments[tokens[2]]["lengths"].append(float(tokens[3])) - layer_segments[tokens[2]]["resistances"].append(float(tokens[4])) - layer_segments[tokens[2]]["capacitances"].append(float(tokens[5])) - layer_net_type_length[tokens[2]][tokens[1]] += float(tokens[3]) - else: - netName = tokens[0] - - data[design][netName] = { - "type": tokens[1], - "grt_res": float(tokens[2]), - "grt_cap": float(tokens[3]), - "rcx_res": float(tokens[4]), - "rcx_cap": float(tokens[5]), - } - - layer_lengths = [float(tok) for tok in tokens[6:]] - for i, length in enumerate(layer_lengths): - if length > 0: - active_layers.add(i) - - data[design][netName]["layer_lengths"] = layer_lengths - data[design][netName]["routable_layer_lengths"] = [ - length - for i, length in enumerate(layer_lengths) - # ignore non-routable layers - if stack[i][1] - ] - data[design][netName]["wire_length"] = sum( - length - for i, length in enumerate(layer_lengths) - # ignore non-routable layers - if stack[i][1] - ) - data[design][netName]["grt_via_res"] = sum( - (length * stack[i][2]) - for i, length in enumerate(layer_lengths) - if not stack[i][1] - ) -################################################################ + net_type = tokens[1] + layer = tokens[2] + length = float(tokens[3]) -if args.mode == "net" and args.plot_cap: - # Compare the GRT cap estimate vs. OpenRCX SPEF cap - - diff_x = [] - diff_percent_x = [] - for design in data: - for net in data[design]: - grt_cap = data[design][net]["grt_cap"] - rcx_cap = data[design][net]["rcx_cap"] - diff = grt_cap - rcx_cap - if abs(diff) > 1e-12: - print("large discrapancy:", design, net, diff) - if rcx_cap != 0.0: - normDiff = (diff / rcx_cap) * 100 - diff_x.append(diff / cap_scale) - diff_percent_x.append(normDiff) + layer_segments[layer]["lengths"].append(length) + layer_segments[layer]["resistances"].append(float(tokens[4])) + layer_segments[layer]["capacitances"].append(float(tokens[5])) + layer_net_type_length[layer][net_type] += length - # Generate histograms - num_bins = 200 - fig = plt.figure() - fig.suptitle("Difference between GRT est. Cap and RCX Cap") - plt.subplot(2, 2, 1) - plt.hist(diff_x, num_bins, facecolor="blue", alpha=0.5) - plt.ylabel("# Nets") - plt.xlabel( - "Capacitance ({})\n\nMean: {:.3f}{}\nStd. dev: {:.3f}fF".format( - cap_unit, np.mean(diff_x), cap_unit, np.std(diff_x) - ) - ) + if not routing_layers: + print("No routing layers header found in the segment RC data.", file=stderr) + exit(1) - plt.subplot(2, 2, 2) - plt.hist(diff_percent_x, num_bins, range={-1000, 1000}, facecolor="blue", alpha=0.5) - plt.ylabel("# Nets") - plt.xlabel( - "%\n\nMean: {:.3f}%\nStd. dev: {:.3f}%".format( - np.mean(diff_percent_x), np.std(diff_percent_x) - ) - ) - plt.show() + if not layer_segments: + print("No segment RC data found.", file=stderr) + exit(1) -################################################################ + return routing_layers, layer_segments, layer_net_type_length + + +# Plot Helpers +# ============================================================================= + + +def plot_grt_rcx_diff(nets, quantity, name, unit, scale, discrepancy_threshold): + differences = [] + differences_percent = [] -if args.mode == "net" and args.plot_res: - # Compare the GRT res estimate vs. OpenRCX SPEF res - - diff_x = [] - diff_percent_x = [] - for design in data: - for net in data[design]: - grt_res = data[design][net]["grt_res"] - rcx_res = data[design][net]["rcx_res"] - if grt_res > 0 and rcx_res > 0: - diff = grt_res - rcx_res - if abs(diff) > 1e3: - print("large discrapancy:", design, net, diff) - if rcx_res != 0.0: - normDiff = (diff / rcx_res) * 100 - diff_x.append(diff / res_scale) - diff_percent_x.append(normDiff) + for net in nets: + grt_value = net[f"grt_{quantity}"] + rcx_value = net[f"rcx_{quantity}"] + + if grt_value <= 0.0 or rcx_value <= 0.0: + continue + + difference = grt_value - rcx_value + + if abs(difference) > discrepancy_threshold: + print(f"Large discrepancy: {net['file_name']} {net['name']} {difference}") + + differences.append(difference / scale) + differences_percent.append(difference / rcx_value * 100) + + if not differences: + print(f"No net {name.lower()} data to plot.", file=stderr) + exit(1) # Generate histograms num_bins = 200 fig = plt.figure() - fig.suptitle("Difference between GRT est. Res and RCX Res") + fig.suptitle(f"Difference between GRT est. and RCX {name}") plt.subplot(2, 2, 1) - plt.hist(diff_x, num_bins, facecolor="blue", alpha=0.5) + plt.hist(differences, num_bins, facecolor="blue", alpha=0.5) plt.ylabel("# Nets") plt.xlabel( - "Resistance ({})\n\nMean: {:.3f}{}\nStd. dev: {:.3f}fF".format( - res_unit, np.mean(diff_x), res_unit, np.std(diff_x) + "{} ({})\n\nMean: {:.3f}{}\nStd. dev: {:.3f}{}".format( + name, unit, np.mean(differences), unit, np.std(differences), unit ) ) plt.subplot(2, 2, 2) - plt.hist(diff_percent_x, num_bins, range={-1000, 1000}, facecolor="blue", alpha=0.5) + plt.hist( + differences_percent, num_bins, range=(-1000, 1000), facecolor="blue", alpha=0.5 + ) plt.ylabel("# Nets") plt.xlabel( "%\n\nMean: {:.3f}%\nStd. dev: {:.3f}%".format( - np.mean(diff_percent_x), np.std(diff_percent_x) + np.mean(differences_percent), np.std(differences_percent) ) ) plt.show() -################################################################ - -if args.mode == "net": - # Use linear regression to find updated layer resistances. - - x = [] - y = [] - for design in data: - for net in data[design]: - rcx_res = data[design][net]["rcx_res"] - if rcx_res > 0: - x.append(data[design][net]["routable_layer_lengths"]) - y.append(rcx_res - data[design][net]["grt_via_res"]) - - x = np.array(x) - y = np.array(y) - res_model = LinearRegression(fit_intercept=False).fit(x, y) - r_sq = res_model.score(x, y) - print("# Resistance coefficient of determination: {:.4f}".format(r_sq)) - - ################################################################ +################################################################ - # Use linear regression to find updated layer capacitances. +args = parse_args() - x = [] - y = [] - for design in data: - for net in data[design]: - x.append(data[design][net]["routable_layer_lengths"]) - y.append(data[design][net]["rcx_cap"]) +# kohm/ff nangate45, asap7 +# kohm/pf sky130hd, sky130hs - x = np.array(x) - y = np.array(y) +res_unit = args.res_unit +if res_unit == "ohm": + res_scale = 1 +elif res_unit == "kohm": + res_scale = 1e3 +else: + print("Unknown resistance unit.") + exit(1) - cap_model = LinearRegression(fit_intercept=False).fit(x, y) - r_sq = cap_model.score(x, y) - print("# Capacitance coefficient of determination: {:.4f}".format(r_sq)) - print( - "# Updated layer resistance {}/um capacitance {}/um".format(res_unit, cap_unit) - ) +cap_unit = args.cap_unit +if cap_unit == "ff": + cap_scale = 1e-15 +elif cap_unit == "pf": + cap_scale = 1e-12 +else: + print("Unknown capacitance unit.") + exit(1) - routable_layers = [layer for layer in stack if layer[1]] - for i, layer in enumerate(routable_layers): - res_coeff = res_model.coef_[i] - cap_coeff = cap_model.coef_[i] - if res_coeff != 0.0 or cap_coeff != 0.0: - print( - "set_layer_rc -layer {} -resistance {:.5E} -capacitance {:.5E}".format( - layer[0], res_coeff / res_scale, cap_coeff / cap_scale - ) - ) +routing_layers, layer_segments, layer_net_type_length = read_segments_rc( + args.segments_rc_file +) - ################################################################ - - def generic_rc_fit(type_sieve): - x = [] - y = [] - for design in data: - for net in data[design]: - net_type = data[design][net]["type"] - wire_res = data[design][net]["rcx_res"] - wire_length = data[design][net]["wire_length"] - if net_type in type_sieve and wire_res != 0.0: - x.append([wire_length]) - y.append(wire_res) - x = np.array(x) - y = np.array(y) - wire_res_model = LinearRegression(fit_intercept=False).fit(x, y) - wire_res = wire_res_model.coef_[0] - - x = [] - y = [] - for design in data: - for net in data[design]: - net_type = data[design][net]["type"] - if net_type in type_sieve: - wire_length = data[design][net]["wire_length"] - wire_cap = data[design][net]["rcx_cap"] - x.append([wire_length]) - y.append(wire_cap) - x = np.array(x) - y = np.array(y) - wire_cap_model = LinearRegression(fit_intercept=False).fit(x, y) - wire_cap = wire_cap_model.coef_[0] - - return "-resistance {:.5E} -capacitance {:.5E}".format( - wire_res / res_scale, wire_cap / cap_scale - ) +if args.nets_rc_file: + nets = read_nets_rc(args.nets_rc_file) - print("# Combined fit:") - print("set_wire_rc " + generic_rc_fit(["signal", "clock"])) + if args.plot_cap: + plot_grt_rcx_diff(nets, "cap", "Capacitance", cap_unit, cap_scale, 1e-12) - print("# Split signal/clock fit:") - print("set_wire_rc -signal " + generic_rc_fit(["signal"])) - print("set_wire_rc -clock " + generic_rc_fit(["clock"])) + if args.plot_res: + plot_grt_rcx_diff(nets, "res", "Resistance", res_unit, res_scale, 1e3) ################################################################ -if args.mode == "segment": - print("\nUnits: resistance [{}/um], capacitance [{}/um]".format(res_unit, cap_unit)) +# Use linear regression to find the layer resistances and capacitances. - # Note that the .csv data comes from ODB which stores capacitance in fF. - cap_ff_to_f = 1e-15 +print("\nUnits: resistance [{}/um], capacitance [{}/um]".format(res_unit, cap_unit)) - layer_models = {} - for layer_name in routing_layers: - # There may be routing layers with no segments, so we check if the - # layer exists in the dict. - if layer_name not in layer_segments: - continue +# Note that the .csv data comes from ODB which stores capacitance in fF. +cap_ff_to_f = 1e-15 - # sklearn requires the input to be 2D, so we reshape to add a dimension - # to the list. - lengths = np.array(layer_segments[layer_name]["lengths"]).reshape(-1, 1) - resistances = np.array(layer_segments[layer_name]["resistances"]) - capacitances_ff = np.array(layer_segments[layer_name]["capacitances"]) - - res_model = LinearRegression(fit_intercept=False).fit(lengths, resistances) - cap_model = LinearRegression(fit_intercept=False).fit(lengths, capacitances_ff) - layer_models[layer_name] = ( - res_model, - cap_model, - lengths, - resistances, - capacitances_ff, - ) +layer_models = {} +for layer_name in routing_layers: + # There may be routing layers with no segments, so we check if the + # layer exists in the dict. + if layer_name not in layer_segments: + continue - # Print R² table - print("{:<13s} | {:>8s} | {:>8s}".format("\nLayer", "Res R²", "Cap R²")) - print("-" * 34) - for layer_name, ( - res_model, - cap_model, - lengths, - resistances, - capacitances_ff, - ) in layer_models.items(): - r_sq_res = compute_through_origin_fit_score(res_model, lengths, resistances) - r_sq_cap = compute_through_origin_fit_score(cap_model, lengths, capacitances_ff) - print("{:<12s} | {:>8s} | {:>8s}".format(layer_name, r_sq_res, r_sq_cap)) - print("-" * 34) - print("") - - for layer_name, ( + # sklearn requires the input to be 2D, so we reshape to add a dimension + # to the list. + lengths = np.array(layer_segments[layer_name]["lengths"]).reshape(-1, 1) + resistances = np.array(layer_segments[layer_name]["resistances"]) + capacitances_ff = np.array(layer_segments[layer_name]["capacitances"]) + + res_model = LinearRegression(fit_intercept=False).fit(lengths, resistances) + cap_model = LinearRegression(fit_intercept=False).fit(lengths, capacitances_ff) + layer_models[layer_name] = ( res_model, cap_model, lengths, resistances, capacitances_ff, - ) in layer_models.items(): - print( - "set_layer_rc -layer {} -resistance {:.5E} -capacitance {:.5E}".format( - layer_name, - res_model.coef_[0] / res_scale, - cap_model.coef_[0] * cap_ff_to_f / cap_scale, - ) + ) + +# Print R² table +print("{:<13s} | {:>8s} | {:>8s}".format("\nLayer", "Res R²", "Cap R²")) +print("-" * 34) +for layer_name, ( + res_model, + cap_model, + lengths, + resistances, + capacitances_ff, +) in layer_models.items(): + r_sq_res = compute_through_origin_fit_score(res_model, lengths, resistances) + r_sq_cap = compute_through_origin_fit_score(cap_model, lengths, capacitances_ff) + print("{:<12s} | {:>8s} | {:>8s}".format(layer_name, r_sq_res, r_sq_cap)) +print("-" * 34) +print("") + +for layer_name, ( + res_model, + cap_model, + lengths, + resistances, + capacitances_ff, +) in layer_models.items(): + print( + "set_layer_rc -layer {} -resistance {:.5E} -capacitance {:.5E}".format( + layer_name, + res_model.coef_[0] / res_scale, + cap_model.coef_[0] * cap_ff_to_f / cap_scale, ) - print("") - - def wire_rc_fit(target_net_type=None): - total_length = 0.0 - total_resistance = 0.0 - total_capacitance = 0.0 - - for layer_name, (res_model, cap_model, lengths, _, _) in layer_models.items(): - if target_net_type is not None: - layer_length = sum( - layer_net_type_length[layer_name][net_type] - for net_type in target_net_type - ) - else: - layer_length = float(lengths.sum()) + ) +print("") - total_resistance += res_model.coef_[0] * layer_length - total_capacitance += cap_model.coef_[0] * layer_length - total_length += layer_length - if total_length == 0.0: - return None +def wire_rc_fit(target_net_type=None): + total_length = 0.0 + total_resistance = 0.0 + total_capacitance = 0.0 - return ( - total_resistance / total_length / res_scale, - total_capacitance / total_length * cap_ff_to_f / cap_scale, - ) + for layer_name, (res_model, cap_model, lengths, _, _) in layer_models.items(): + if target_net_type is not None: + layer_length = sum( + layer_net_type_length[layer_name][net_type] + for net_type in target_net_type + ) + else: + layer_length = float(lengths.sum()) - resistance, capacitance = wire_rc_fit() + total_resistance += res_model.coef_[0] * layer_length + total_capacitance += cap_model.coef_[0] * layer_length + total_length += layer_length - print( - "set_wire_rc -resistance {:.5E} -capacitance {:.5E}".format( - resistance, capacitance - ) + if total_length == 0.0: + return None + + return ( + total_resistance / total_length / res_scale, + total_capacitance / total_length * cap_ff_to_f / cap_scale, ) - for net_type in ["signal", "clock"]: - result = wire_rc_fit([net_type]) - if result is None: - print("[Warning] No {} nets were found.".format(net_type)) - continue +resistance, capacitance = wire_rc_fit() - resistance, capacitance = result +print( + "set_wire_rc -resistance {:.5E} -capacitance {:.5E}".format(resistance, capacitance) +) - print( - "set_wire_rc -{} -resistance {:.5E} -capacitance {:.5E}".format( - net_type, resistance, capacitance - ) +for net_type in ["signal", "clock"]: + result = wire_rc_fit([net_type]) + + if result is None: + print("[Warning] No {} nets were found.".format(net_type)) + continue + + resistance, capacitance = result + + print( + "set_wire_rc -{} -resistance {:.5E} -capacitance {:.5E}".format( + net_type, resistance, capacitance ) - print("") + ) +print("") diff --git a/flow/util/utils.mk b/flow/util/utils.mk index 0dbeb1ea6e..d1359cece3 100644 --- a/flow/util/utils.mk +++ b/flow/util/utils.mk @@ -84,33 +84,30 @@ update_metadata_autotuner: #------------------------------------------------------------------------------- -.PHONY: write_net_rc -write_net_rc: $(RESULTS_DIR)/6_net_rc.csv +.PHONY: write_rc +write_rc: $(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv -#$(RESULTS_DIR)/6_net_rc.csv: $(RESULTS_DIR)/4_cts.odb $(RESULTS_DIR)/6_final.spef -$(RESULTS_DIR)/6_net_rc.csv: - $(RUN_CMD) --log $(LOG_DIR)/6_write_net_rc.log --tee -- $(OPENROAD_CMD) $(UTILS_DIR)/write_net_rc_script.tcl - -.PHONY: write_segment_rc -write_segment_rc: $(RESULTS_DIR)/6_segment_rc.csv - -$(RESULTS_DIR)/6_segment_rc.csv: - $(RUN_CMD) --log $(LOG_DIR)/6_write_segment_rc.log --tee -- $(OPENROAD_CMD) $(UTILS_DIR)/write_segment_rc_script.tcl +$(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv &: + $(RUN_CMD) --log $(LOG_DIR)/6_write_rc.log --tee -- $(OPENROAD_CMD) $(UTILS_DIR)/write_rc.tcl .PHONY: correlate_rc -correlate_rc: $(RESULTS_DIR)/6_net_rc.csv - $(PYTHON_EXE) $(UTILS_DIR)/correlateRC.py $(RESULTS_DIR)/6_net_rc.csv +correlate_rc: $(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv + $(PYTHON_EXE) $(UTILS_DIR)/correlateRC.py \ + -nets_rc_file $(RESULTS_DIR)/6_nets_rc.csv \ + -segments_rc_file $(RESULTS_DIR)/6_segments_rc.csv # TODO Make always wants to redo designs with this rule, regardless of which variations are tried. -# $(MAKE) DESIGN_CONFIG=$$config write_net_rc; \ -#$(foreach config,$(wildcard designs/$(PLATFORM)/*/config.mk),$(MAKE) DESIGN_CONFIG=$(config) write_net_rc; ) .PHONY: correlate_platform_rc correlate_platform_rc: for config in designs/$(PLATFORM)/*/config.mk; do \ design=$$(basename $$(dirname $$config)); \ - make DESIGN_CONFIG=./$$config results/$(PLATFORM)/$$design/base/6_net_rc.csv; \ + make DESIGN_CONFIG=./$$config \ + results/$(PLATFORM)/$$design/base/6_nets_rc.csv \ + results/$(PLATFORM)/$$design/base/6_segments_rc.csv; \ done - $(PYTHON_EXE) $(UTILS_DIR)/correlateRC.py $$(find results/$(PLATFORM)/*/base -name 6_net_rc.csv) + $(PYTHON_EXE) $(UTILS_DIR)/correlateRC.py \ + -nets_rc_file $$(find results/$(PLATFORM)/*/base -name 6_nets_rc.csv) \ + -segments_rc_file $$(find results/$(PLATFORM)/*/base -name 6_segments_rc.csv) # Run test using gnu parallel #------------------------------------------------------------------------------- diff --git a/flow/util/write_net_rc.tcl b/flow/util/write_net_rc.tcl deleted file mode 100644 index d468122d0b..0000000000 --- a/flow/util/write_net_rc.tcl +++ /dev/null @@ -1,84 +0,0 @@ -proc write_nets_rc_csv { filename } { - upvar 1 grt grt_net_name_to_rc - upvar 1 rcx rcx_net_name_to_rc - - set tech [ord::get_db_tech] - set stream [open $filename "w"] - - puts -nonewline $stream "# stack:" - foreach layer [[ord::get_db_tech] getLayers] { - set routing [expr [$layer getRoutingLevel] != 0] - set is_routing([$layer getNumber]) $routing - set is_routing([$layer getNumber]) $routing - puts -nonewline $stream " [$layer getName]" - if { $routing } { - puts -nonewline $stream "(routing)" - } else { - # insert via resistance information - set via_resist [$layer getResistance] - if { $via_resist != 0.0 } { - puts -nonewline $stream "([format %.4e $via_resist])" - } - } - } - puts $stream "" - - set use_drt_data [env_var_exists_and_non_empty CORRELATE_DRT_WIRELENGTH] - - foreach net [get_nets *] { - set db_net [sta::sta_to_db_net $net] - set type [$db_net getSigType] - if { - ([string equal $type "CLOCK"] || [string equal $type "SIGNAL"]) && - (!$use_drt_data || [$db_net getWire] ne "NULL") - } { - set net_name [get_full_name $net] - lassign $grt_net_name_to_rc($net_name) grt_net_res grt_net_cap - lassign $rcx_net_name_to_rc($net_name) rcx_net_res rcx_net_cap - set net_type [expr { [string equal $type "CLOCK"] ? "clock" : "signal" }] - puts -nonewline $stream "[get_full_name $net],$net_type," - puts -nonewline $stream [concat \ - [format "%.3e" $grt_net_res] "," [format "%.3e" $grt_net_cap] "," \ - [format "%.3e" $rcx_net_res] "," [format "%.3e" $rcx_net_cap]] - set db_net [sta::sta_to_db_net $net] - - if { $use_drt_data } { - set layer_lengths [drt::route_layer_lengths [$db_net getWire]] - } else { - set layer_lengths [grt::route_layer_lengths $db_net] - } - - for { set layer 0 } { $layer < [$tech getLayerCount] } { incr layer } { - set length [lindex $layer_lengths $layer] - if { $is_routing($layer) } { - puts -nonewline $stream ",[ord::dbu_to_microns $length]" - } else { - puts -nonewline $stream ",$length" - } - } - - puts $stream "" - } - } - close $stream -} - -proc fetch_nets_rc { var_name } { - upvar 1 $var_name var - - foreach net [get_nets *] { - set net_name [get_full_name $net] - set wire_res [net_wire_res $net] - set wire_cap [net_wire_cap $net] - set var($net_name) [list $wire_res $wire_cap] - } -} - -# Only works or makes sense for 2 pin nets. -proc net_wire_res { net } { - return [rsz::sum_parasitic_network_resist $net] -} - -proc net_wire_cap { net } { - return [$net wire_capacitance [sta::cmd_scene] max] -} diff --git a/flow/util/write_net_rc_script.tcl b/flow/util/write_net_rc_script.tcl deleted file mode 100644 index 278c844d6d..0000000000 --- a/flow/util/write_net_rc_script.tcl +++ /dev/null @@ -1,13 +0,0 @@ -source $::env(SCRIPTS_DIR)/load.tcl -load_design 6_final.odb 6_final.sdc - -source $::env(UTILS_DIR)/write_net_rc.tcl - -estimate_parasitics -global_routing -fetch_nets_rc grt - -read_spef $::env(RESULTS_DIR)/6_final.spef -fetch_nets_rc rcx - -# write grt/rcx rc file for correlateRC.py -write_nets_rc_csv $::env(RESULTS_DIR)/6_net_rc.csv diff --git a/flow/util/write_rc.tcl b/flow/util/write_rc.tcl new file mode 100644 index 0000000000..9d93865282 --- /dev/null +++ b/flow/util/write_rc.tcl @@ -0,0 +1,20 @@ +source $::env(SCRIPTS_DIR)/load.tcl +load_design 6_final.odb 6_final.sdc + +source $::env(UTILS_DIR)/write_rc_helper.tcl + +estimate_parasitics -global_routing +fetch_nets_rc grt_nets_rc + +# Use STA to load and fetch nets' parasitics. +read_spef $::env(RESULTS_DIR)/6_final.spef +fetch_nets_rc rcx_nets_rc + +write_nets_rc_csv $::env(RESULTS_DIR)/6_nets_rc.csv grt_nets_rc rcx_nets_rc + +# Use RCX to compute and ODB API's to fetch segments' parasitics. +# We set up RCX parameters to avoid any parasitics segment merging. +extract_parasitics -ext_model_file $::env(RCX_RULES) -max_res 0 -no_merge_via_res +fetch_segments_rc segments_rc + +write_segments_rc_csv $::env(RESULTS_DIR)/6_segments_rc.csv segments_rc diff --git a/flow/util/write_rc_helper.tcl b/flow/util/write_rc_helper.tcl new file mode 100644 index 0000000000..85157760c1 --- /dev/null +++ b/flow/util/write_rc_helper.tcl @@ -0,0 +1,179 @@ +# Helpers for Nets Data +#=============================================================================== + +proc fetch_nets_rc { var_name } { + upvar 1 $var_name var + + foreach net [get_nets *] { + set net_name [get_full_name $net] + set wire_res [net_wire_res $net] + set wire_cap [net_wire_cap $net] + set var($net_name) [list $wire_res $wire_cap] + } +} + +# Only works or makes sense for 2 pin nets. +proc net_wire_res { net } { + return [rsz::sum_parasitic_network_resist $net] +} + +proc net_wire_cap { net } { + return [$net wire_capacitance [sta::cmd_scene] max] +} + +proc write_nets_rc_csv { filename grt_var rcx_var } { + upvar 1 $grt_var grt_net_name_to_rc + upvar 1 $rcx_var rcx_net_name_to_rc + + set tech [ord::get_db_tech] + set stream [open $filename "w"] + + puts -nonewline $stream "# stack:" + foreach layer [$tech getLayers] { + set routing [expr [$layer getRoutingLevel] != 0] + set is_routing([$layer getNumber]) $routing + puts -nonewline $stream " [$layer getName]" + if { $routing } { + puts -nonewline $stream "(routing)" + } else { + # insert via resistance information + set via_resist [$layer getResistance] + if { $via_resist != 0.0 } { + puts -nonewline $stream "([format %.4e $via_resist])" + } + } + } + puts $stream "" + + set use_drt_data [env_var_exists_and_non_empty CORRELATE_DRT_WIRELENGTH] + + foreach net [get_nets *] { + set db_net [sta::sta_to_db_net $net] + set type [$db_net getSigType] + if { + ([string equal $type "CLOCK"] || [string equal $type "SIGNAL"]) && + (!$use_drt_data || [$db_net getWire] ne "NULL") + } { + set net_name [get_full_name $net] + lassign $grt_net_name_to_rc($net_name) grt_net_res grt_net_cap + lassign $rcx_net_name_to_rc($net_name) rcx_net_res rcx_net_cap + set net_type [expr { [string equal $type "CLOCK"] ? "clock" : "signal" }] + puts -nonewline $stream "$net_name,$net_type," + puts -nonewline $stream [concat \ + [format "%.3e" $grt_net_res] "," [format "%.3e" $grt_net_cap] "," \ + [format "%.3e" $rcx_net_res] "," [format "%.3e" $rcx_net_cap]] + + if { $use_drt_data } { + set layer_lengths [drt::route_layer_lengths [$db_net getWire]] + } else { + set layer_lengths [grt::route_layer_lengths $db_net] + } + + for { set layer 0 } { $layer < [$tech getLayerCount] } { incr layer } { + set length [lindex $layer_lengths $layer] + if { $is_routing($layer) } { + puts -nonewline $stream ",[ord::dbu_to_microns $length]" + } else { + puts -nonewline $stream ",$length" + } + } + + puts $stream "" + } + } + close $stream +} + +# Helpers for Segments Data +#=============================================================================== + +# This function only works if each routing wire shape corresponds +# to one parasitic resistive model. +proc fetch_segments_rc { net_to_segments_var } { + upvar 1 $net_to_segments_var net_to_segments + + foreach sta_net [get_nets -hierarchical *] { + set db_net [sta::sta_to_db_net $sta_net] + set type [$db_net getSigType] + + if { !([string equal $type "CLOCK"] || [string equal $type "SIGNAL"]) } { + continue + } + + set wire [$db_net getWire] + + if { $wire eq "NULL" } { + continue + } + + set segments {} + set seen_shape_ids {} + foreach rseg [$db_net getRSegs] { + set shape [$wire getShape [$rseg getShapeId]] + + # We skip vias as they have no capacitance in RCX. + if { ![$shape isSegment] } { + continue + } + + set shape_id [$rseg getShapeId] + + if { $shape_id in $seen_shape_ids } { + error "Could not fetch segment parasitics data: shape\ + $shape_id on net [$db_net getName] has multiple rsegs." + } + + set layer [[$shape getTechLayer] getName] + + set width [$shape getDX] + set height [$shape getDY] + set length_um [ord::dbu_to_microns [expr { max($width, $height) }]] + + # Default corner + set corner 0 + set resistance [$rseg getResistance $corner] + set capacitance [$rseg getTotalCapacitance $corner] + + lappend segments $layer $length_um $resistance $capacitance + lappend seen_shape_ids $shape_id + } + + set net_to_segments([get_full_name $sta_net]) $segments + } +} + +proc write_segments_rc_csv { filename net_to_segments_var } { + upvar 1 $net_to_segments_var net_to_segments + + set stream [open $filename "w"] + + # First, write a header listing the routing layers in stack order. + puts -nonewline $stream "# routing layers:" + foreach layer [[ord::get_db_tech] getLayers] { + if { [$layer getRoutingLevel] != 0 } { + puts -nonewline $stream " [$layer getName]" + } + } + + puts $stream "" + + # Then, write the parasitics data of each wire segment. + foreach sta_net [get_nets -hierarchical *] { + set net_name [get_full_name $sta_net] + + if { ![info exists net_to_segments($net_name)] } { + continue + } + + set db_net [sta::sta_to_db_net $sta_net] + set type [$db_net getSigType] + set net_type [expr { $type eq "CLOCK" ? "clock" : "signal" }] + + foreach {layer length_um resistance capacitance} $net_to_segments($net_name) { + puts $stream [format "%s,%s,%s,%.3e,%.3e,%.3e" \ + $net_name $net_type $layer $length_um $resistance $capacitance] + } + } + + close $stream +} diff --git a/flow/util/write_segment_rc.tcl b/flow/util/write_segment_rc.tcl deleted file mode 100644 index 05ce8b30a7..0000000000 --- a/flow/util/write_segment_rc.tcl +++ /dev/null @@ -1,90 +0,0 @@ -# This function only works if each routing wire shape corresponds -# to one parasitic resistive model. -proc fetch_segments_rc { net_to_segments_var } { - upvar 1 $net_to_segments_var net_to_segments - - foreach sta_net [get_nets -hierarchical *] { - set db_net [sta::sta_to_db_net $sta_net] - set type [$db_net getSigType] - - if { !([string equal $type "CLOCK"] || [string equal $type "SIGNAL"]) } { - continue - } - - set wire [$db_net getWire] - - if { $wire eq "NULL" } { - continue - } - - set segments {} - set seen_shape_ids {} - foreach rseg [$db_net getRSegs] { - set shape [$wire getShape [$rseg getShapeId]] - - # We skip vias as they have no capacitance in RCX. - if { ![$shape isSegment] } { - continue - } - - set shape_id [$rseg getShapeId] - - if { $shape_id in $seen_shape_ids } { - error "Could not fetch segment parasitics data: shape\ - $shape_id on net [$db_net getName] has multiple rsegs." - } - - set layer [[$shape getTechLayer] getName] - - set width [$shape getDX] - set height [$shape getDY] - set length_um [ord::dbu_to_microns [expr { max($width, $height) }]] - - # Default corner - set corner 0 - set resistance [$rseg getResistance $corner] - set capacitance [$rseg getTotalCapacitance $corner] - - lappend segments $layer $length_um $resistance $capacitance - lappend seen_shape_ids $shape_id - } - - set net_to_segments([get_full_name $sta_net]) $segments - } -} - -proc write_segment_rc_csv { filename net_to_segments_var } { - upvar 1 $net_to_segments_var net_to_segments - - set stream [open $filename "w"] - - # First, write a header listing the routing layers in stack order. - puts -nonewline $stream "# routing layers:" - foreach layer [[ord::get_db_tech] getLayers] { - if { [$layer getRoutingLevel] != 0 } { - puts -nonewline $stream " [$layer getName]" - } - } - - puts $stream "" - - # Then, write the parasitics data of each wire segment. - foreach sta_net [get_nets -hierarchical *] { - set net_name [get_full_name $sta_net] - - if { ![info exists net_to_segments($net_name)] } { - continue - } - - set db_net [sta::sta_to_db_net $sta_net] - set type [$db_net getSigType] - set net_type [expr { $type eq "CLOCK" ? "clock" : "signal" }] - - foreach {layer length_um resistance capacitance} $net_to_segments($net_name) { - puts $stream [format "%s,%s,%s,%.3e,%.3e,%.3e" \ - $net_name $net_type $layer $length_um $resistance $capacitance] - } - } - - close $stream -} diff --git a/flow/util/write_segment_rc_script.tcl b/flow/util/write_segment_rc_script.tcl deleted file mode 100644 index 7953deceb9..0000000000 --- a/flow/util/write_segment_rc_script.tcl +++ /dev/null @@ -1,10 +0,0 @@ -source $::env(SCRIPTS_DIR)/load.tcl -load_design 6_final.odb 6_final.sdc - -source $::env(UTILS_DIR)/write_segment_rc.tcl - -# Set up RCX parameters to avoid any parasitics segment merging. -extract_parasitics -ext_model_file $::env(RCX_RULES) -max_res 0 -no_merge_via_res -fetch_segments_rc rcx - -write_segment_rc_csv $::env(RESULTS_DIR)/6_segment_rc.csv rcx From 20ef272984038aba82bb8596f4a03b419d99e9df Mon Sep 17 00:00:00 2001 From: Arthur Koucher Date: Fri, 31 Jul 2026 15:58:02 -0300 Subject: [PATCH 2/6] add log to inform zero parasitics and ensure plot errors don't stop the fit Signed-off-by: Arthur Koucher --- flow/util/correlateRC.py | 44 ++++++++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/flow/util/correlateRC.py b/flow/util/correlateRC.py index c20c1bee68..1f4e618c97 100755 --- a/flow/util/correlateRC.py +++ b/flow/util/correlateRC.py @@ -126,6 +126,17 @@ def read_nets_rc(file_names): print("No net RC data found.", file=stderr) exit(1) + for key, name in ( + ("grt_res", "GRT resistance"), + ("grt_cap", "GRT capacitance"), + ("rcx_res", "RCX resistance"), + ("rcx_cap", "RCX capacitance"), + ): + count = sum(1 for net in nets if net[key] == 0.0) + + if count > 0: + print(f"Found {count} nets with zero {name}.") + return nets @@ -180,6 +191,16 @@ def read_segments_rc(file_names): print("No segment RC data found.", file=stderr) exit(1) + for key, name in (("resistances", "resistance"), ("capacitances", "capacitance")): + count = sum( + 1 + for segments in layer_segments.values() + for value in segments[key] + if value == 0.0 + ) + if count > 0: + print(f"Found {count} segments with zero {name}.") + return routing_layers, layer_segments, layer_net_type_length @@ -265,15 +286,6 @@ def plot_grt_rcx_diff(nets, quantity, name, unit, scale, discrepancy_threshold): args.segments_rc_file ) -if args.nets_rc_file: - nets = read_nets_rc(args.nets_rc_file) - - if args.plot_cap: - plot_grt_rcx_diff(nets, "cap", "Capacitance", cap_unit, cap_scale, 1e-12) - - if args.plot_res: - plot_grt_rcx_diff(nets, "res", "Resistance", res_unit, res_scale, 1e3) - ################################################################ # Use linear regression to find the layer resistances and capacitances. @@ -387,3 +399,17 @@ def wire_rc_fit(target_net_type=None): ) ) print("") + +################################################################ + +# The plots come after the commands so that a plot with no data does not +# withhold them. + +if args.nets_rc_file: + nets = read_nets_rc(args.nets_rc_file) + + if args.plot_cap: + plot_grt_rcx_diff(nets, "cap", "Capacitance", cap_unit, cap_scale, 1e-12) + + if args.plot_res: + plot_grt_rcx_diff(nets, "res", "Resistance", res_unit, res_scale, 1e3) From 045539be487624dc95cfd5fee076154c8c577769 Mon Sep 17 00:00:00 2001 From: Arthur Koucher Date: Fri, 31 Jul 2026 16:16:20 -0300 Subject: [PATCH 3/6] move correlateRC functions into a helper file Signed-off-by: Arthur Koucher --- flow/util/correlateRC.py | 401 ++------------------------------- flow/util/correlateRCHelper.py | 389 ++++++++++++++++++++++++++++++++ 2 files changed, 405 insertions(+), 385 deletions(-) create mode 100644 flow/util/correlateRCHelper.py diff --git a/flow/util/correlateRC.py b/flow/util/correlateRC.py index 1f4e618c97..1a1bf49592 100755 --- a/flow/util/correlateRC.py +++ b/flow/util/correlateRC.py @@ -8,403 +8,34 @@ # set_wire_rc values are fitted from the segments data, while the plots # compare the GRT estimates against the RCX values of the nets. -from sys import exit, stderr -from collections import defaultdict - -import argparse -import numpy as np -from sklearn.linear_model import LinearRegression -import matplotlib.pyplot as plt - -# Auxiliary variables to catch swapped input .csv files. -SEGMENTS_COLUMNS = 6 -NETS_MIN_COLUMNS = 7 - -# Helper functions -# ============================================================================= - - -# sklearn's default baseline model for scoring the fit i.e., measuring R² is -# "predict the mean" which is not the proper model for our regressions since -# both R and C are through-origin fits - the R² computation doesn't behave -# well for var(y) ≈ 0 - so we compute R² manually with a "predict zero" -# baseline model. -def compute_through_origin_fit_score(model, inputs, observed): - sum_squared_observed = (observed**2).sum() - if sum_squared_observed == 0: - return "No data" - score = 1.0 - ((observed - model.predict(inputs)) ** 2).sum() / sum_squared_observed - return f"{score:.4f}" - - -# Parse and validate arguments -# ============================================================================= - - -def parse_args(): - parser = argparse.ArgumentParser( - description="Determines layer capacitance and resistance values for OpenROAD flow designs" - ) - parser.add_argument( - "-cap_unit", required=False, default="pf", help="capacitance unit ff|pf" - ) - parser.add_argument( - "-res_unit", required=False, default="kohm", help="resistance unit ohm|kohm" - ) - parser.add_argument( - "-plot_cap", - required=False, - action="store_true", - default=False, - help="Plot grt/rcx capacitance differences", - ) - parser.add_argument( - "-plot_res", - required=False, - action="store_true", - default=False, - help="Plot grt/rcx resistance differences", - ) - parser.add_argument( - "-nets_rc_file", - required=False, - nargs="+", - default=[], - metavar="FILE", - help="Net RC csv file(s) written by make write_rc, required for the plots", - ) - parser.add_argument( - "-segments_rc_file", - required=True, - nargs="+", - metavar="FILE", - help="Segment RC csv file(s) written by make write_rc, used to fit the layer RC values", - ) - args = parser.parse_args() - - if (args.plot_cap or args.plot_res) and not args.nets_rc_file: - parser.error("-nets_rc_file is required to plot the grt/rcx differences") - - return args - - -# Parser Helpers -# ============================================================================= - - -def read_nets_rc(file_names): - nets = [] - - for file_name in file_names: - print(f"Reading {file_name}.") - with open(file_name) as file: - for line in file: - line = line.strip() - - if not line or line.startswith("#"): - continue - - tokens = line.split(",") - - if len(tokens) < NETS_MIN_COLUMNS: - print(f"Malformed net RC line: {line}", file=stderr) - exit(1) - - nets.append( - { - "file_name": file_name, - "name": tokens[0], - "type": tokens[1], - "grt_res": float(tokens[2]), - "grt_cap": float(tokens[3]), - "rcx_res": float(tokens[4]), - "rcx_cap": float(tokens[5]), - } - ) - - if not nets: - print("No net RC data found.", file=stderr) - exit(1) - - for key, name in ( - ("grt_res", "GRT resistance"), - ("grt_cap", "GRT capacitance"), - ("rcx_res", "RCX resistance"), - ("rcx_cap", "RCX capacitance"), - ): - count = sum(1 for net in nets if net[key] == 0.0) - - if count > 0: - print(f"Found {count} nets with zero {name}.") - - return nets - - -def read_segments_rc(file_names): - layer_segments = defaultdict( - lambda: {"lengths": [], "resistances": [], "capacitances": []} - ) - layer_net_type_length = defaultdict(lambda: defaultdict(float)) - routing_layers = [] - routing_layers_line = None - - for file_name in file_names: - print(f"Reading {file_name}.") - with open(file_name) as file: - for line in file: - if line.startswith("# routing layers: "): - if routing_layers_line is None: - routing_layers = ( - line.removeprefix("# routing layers: ").strip().split(" ") - ) - routing_layers_line = line - elif routing_layers_line != line: - print("Layer stack inconsistent.", file=stderr) - exit(1) - continue - - line = line.strip() - - if not line or line.startswith("#"): - continue - - tokens = line.split(",") - - if len(tokens) != SEGMENTS_COLUMNS: - print(f"Malformed segment RC line: {line}", file=stderr) - exit(1) - - net_type = tokens[1] - layer = tokens[2] - length = float(tokens[3]) - - layer_segments[layer]["lengths"].append(length) - layer_segments[layer]["resistances"].append(float(tokens[4])) - layer_segments[layer]["capacitances"].append(float(tokens[5])) - layer_net_type_length[layer][net_type] += length - - if not routing_layers: - print("No routing layers header found in the segment RC data.", file=stderr) - exit(1) - - if not layer_segments: - print("No segment RC data found.", file=stderr) - exit(1) - - for key, name in (("resistances", "resistance"), ("capacitances", "capacitance")): - count = sum( - 1 - for segments in layer_segments.values() - for value in segments[key] - if value == 0.0 - ) - if count > 0: - print(f"Found {count} segments with zero {name}.") - - return routing_layers, layer_segments, layer_net_type_length - - -# Plot Helpers -# ============================================================================= - - -def plot_grt_rcx_diff(nets, quantity, name, unit, scale, discrepancy_threshold): - differences = [] - differences_percent = [] - - for net in nets: - grt_value = net[f"grt_{quantity}"] - rcx_value = net[f"rcx_{quantity}"] - - if grt_value <= 0.0 or rcx_value <= 0.0: - continue - - difference = grt_value - rcx_value - - if abs(difference) > discrepancy_threshold: - print(f"Large discrepancy: {net['file_name']} {net['name']} {difference}") - - differences.append(difference / scale) - differences_percent.append(difference / rcx_value * 100) - - if not differences: - print(f"No net {name.lower()} data to plot.", file=stderr) - exit(1) - - # Generate histograms - num_bins = 200 - fig = plt.figure() - fig.suptitle(f"Difference between GRT est. and RCX {name}") - plt.subplot(2, 2, 1) - plt.hist(differences, num_bins, facecolor="blue", alpha=0.5) - plt.ylabel("# Nets") - plt.xlabel( - "{} ({})\n\nMean: {:.3f}{}\nStd. dev: {:.3f}{}".format( - name, unit, np.mean(differences), unit, np.std(differences), unit - ) - ) - - plt.subplot(2, 2, 2) - plt.hist( - differences_percent, num_bins, range=(-1000, 1000), facecolor="blue", alpha=0.5 - ) - plt.ylabel("# Nets") - plt.xlabel( - "%\n\nMean: {:.3f}%\nStd. dev: {:.3f}%".format( - np.mean(differences_percent), np.std(differences_percent) - ) - ) - plt.show() - - -################################################################ +from correlateRCHelper import ( + fit_layer_models, + parse_args, + plot_grt_rcx_diff, + print_fit_scores, + print_layer_rc, + print_wire_rc, + read_nets_rc, + read_segments_rc, + resolve_units, +) args = parse_args() - -# kohm/ff nangate45, asap7 -# kohm/pf sky130hd, sky130hs - -res_unit = args.res_unit -if res_unit == "ohm": - res_scale = 1 -elif res_unit == "kohm": - res_scale = 1e3 -else: - print("Unknown resistance unit.") - exit(1) - -cap_unit = args.cap_unit -if cap_unit == "ff": - cap_scale = 1e-15 -elif cap_unit == "pf": - cap_scale = 1e-12 -else: - print("Unknown capacitance unit.") - exit(1) +res_unit, res_scale, cap_unit, cap_scale = resolve_units(args) routing_layers, layer_segments, layer_net_type_length = read_segments_rc( args.segments_rc_file ) -################################################################ - # Use linear regression to find the layer resistances and capacitances. +layer_models = fit_layer_models(routing_layers, layer_segments) -print("\nUnits: resistance [{}/um], capacitance [{}/um]".format(res_unit, cap_unit)) - -# Note that the .csv data comes from ODB which stores capacitance in fF. -cap_ff_to_f = 1e-15 - -layer_models = {} -for layer_name in routing_layers: - # There may be routing layers with no segments, so we check if the - # layer exists in the dict. - if layer_name not in layer_segments: - continue - - # sklearn requires the input to be 2D, so we reshape to add a dimension - # to the list. - lengths = np.array(layer_segments[layer_name]["lengths"]).reshape(-1, 1) - resistances = np.array(layer_segments[layer_name]["resistances"]) - capacitances_ff = np.array(layer_segments[layer_name]["capacitances"]) - - res_model = LinearRegression(fit_intercept=False).fit(lengths, resistances) - cap_model = LinearRegression(fit_intercept=False).fit(lengths, capacitances_ff) - layer_models[layer_name] = ( - res_model, - cap_model, - lengths, - resistances, - capacitances_ff, - ) - -# Print R² table -print("{:<13s} | {:>8s} | {:>8s}".format("\nLayer", "Res R²", "Cap R²")) -print("-" * 34) -for layer_name, ( - res_model, - cap_model, - lengths, - resistances, - capacitances_ff, -) in layer_models.items(): - r_sq_res = compute_through_origin_fit_score(res_model, lengths, resistances) - r_sq_cap = compute_through_origin_fit_score(cap_model, lengths, capacitances_ff) - print("{:<12s} | {:>8s} | {:>8s}".format(layer_name, r_sq_res, r_sq_cap)) -print("-" * 34) -print("") - -for layer_name, ( - res_model, - cap_model, - lengths, - resistances, - capacitances_ff, -) in layer_models.items(): - print( - "set_layer_rc -layer {} -resistance {:.5E} -capacitance {:.5E}".format( - layer_name, - res_model.coef_[0] / res_scale, - cap_model.coef_[0] * cap_ff_to_f / cap_scale, - ) - ) -print("") - - -def wire_rc_fit(target_net_type=None): - total_length = 0.0 - total_resistance = 0.0 - total_capacitance = 0.0 - - for layer_name, (res_model, cap_model, lengths, _, _) in layer_models.items(): - if target_net_type is not None: - layer_length = sum( - layer_net_type_length[layer_name][net_type] - for net_type in target_net_type - ) - else: - layer_length = float(lengths.sum()) - - total_resistance += res_model.coef_[0] * layer_length - total_capacitance += cap_model.coef_[0] * layer_length - total_length += layer_length - - if total_length == 0.0: - return None - - return ( - total_resistance / total_length / res_scale, - total_capacitance / total_length * cap_ff_to_f / cap_scale, - ) - - -resistance, capacitance = wire_rc_fit() - -print( - "set_wire_rc -resistance {:.5E} -capacitance {:.5E}".format(resistance, capacitance) -) - -for net_type in ["signal", "clock"]: - result = wire_rc_fit([net_type]) - - if result is None: - print("[Warning] No {} nets were found.".format(net_type)) - continue - - resistance, capacitance = result - - print( - "set_wire_rc -{} -resistance {:.5E} -capacitance {:.5E}".format( - net_type, resistance, capacitance - ) - ) -print("") - -################################################################ +print_fit_scores(layer_models, res_unit, cap_unit) +print_layer_rc(layer_models, res_scale, cap_scale) +print_wire_rc(layer_models, layer_net_type_length, res_scale, cap_scale) # The plots come after the commands so that a plot with no data does not # withhold them. - if args.nets_rc_file: nets = read_nets_rc(args.nets_rc_file) diff --git a/flow/util/correlateRCHelper.py b/flow/util/correlateRCHelper.py new file mode 100644 index 0000000000..cdbeb5dc18 --- /dev/null +++ b/flow/util/correlateRCHelper.py @@ -0,0 +1,389 @@ +from sys import exit, stderr +from collections import defaultdict + +import argparse +import numpy as np +from sklearn.linear_model import LinearRegression +import matplotlib.pyplot as plt + +# Auxiliary variables to catch swapped input .csv files. +SEGMENTS_COLUMNS = 6 +NETS_MIN_COLUMNS = 7 + +# The .csv data comes from ODB which stores capacitance in fF. +CAP_FF_TO_F = 1e-15 + +# Parsing +# ============================================================================= + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Determines layer capacitance and resistance values for OpenROAD flow designs" + ) + parser.add_argument( + "-cap_unit", required=False, default="pf", help="capacitance unit ff|pf" + ) + parser.add_argument( + "-res_unit", required=False, default="kohm", help="resistance unit ohm|kohm" + ) + parser.add_argument( + "-plot_cap", + required=False, + action="store_true", + default=False, + help="Plot grt/rcx capacitance differences", + ) + parser.add_argument( + "-plot_res", + required=False, + action="store_true", + default=False, + help="Plot grt/rcx resistance differences", + ) + parser.add_argument( + "-nets_rc_file", + required=False, + nargs="+", + default=[], + metavar="FILE", + help="Net RC csv file(s) written by make write_rc, required for the plots", + ) + parser.add_argument( + "-segments_rc_file", + required=True, + nargs="+", + metavar="FILE", + help="Segment RC csv file(s) written by make write_rc, used to fit the layer RC values", + ) + args = parser.parse_args() + + if (args.plot_cap or args.plot_res) and not args.nets_rc_file: + parser.error("-nets_rc_file is required to plot the grt/rcx differences") + + return args + + +def resolve_units(args): + res_unit = args.res_unit + if res_unit == "ohm": + res_scale = 1 + elif res_unit == "kohm": + res_scale = 1e3 + else: + print("Unknown resistance unit.") + exit(1) + + cap_unit = args.cap_unit + if cap_unit == "ff": + cap_scale = 1e-15 + elif cap_unit == "pf": + cap_scale = 1e-12 + else: + print("Unknown capacitance unit.") + exit(1) + + return res_unit, res_scale, cap_unit, cap_scale + + +def read_nets_rc(file_names): + nets = [] + + for file_name in file_names: + print(f"Reading {file_name}.") + with open(file_name) as file: + for line in file: + line = line.strip() + + if not line or line.startswith("#"): + continue + + tokens = line.split(",") + + if len(tokens) < NETS_MIN_COLUMNS: + print(f"Malformed net RC line: {line}", file=stderr) + exit(1) + + nets.append( + { + "file_name": file_name, + "name": tokens[0], + "type": tokens[1], + "grt_res": float(tokens[2]), + "grt_cap": float(tokens[3]), + "rcx_res": float(tokens[4]), + "rcx_cap": float(tokens[5]), + } + ) + + if not nets: + print("No net RC data found.", file=stderr) + exit(1) + + for key, name in ( + ("grt_res", "GRT resistance"), + ("grt_cap", "GRT capacitance"), + ("rcx_res", "RCX resistance"), + ("rcx_cap", "RCX capacitance"), + ): + count = sum(1 for net in nets if net[key] == 0.0) + + if count > 0: + print(f"Found {count} nets with zero {name}.") + + return nets + + +def read_segments_rc(file_names): + layer_segments = defaultdict( + lambda: {"lengths": [], "resistances": [], "capacitances": []} + ) + layer_net_type_length = defaultdict(lambda: defaultdict(float)) + routing_layers = [] + routing_layers_line = None + + for file_name in file_names: + print(f"Reading {file_name}.") + with open(file_name) as file: + for line in file: + if line.startswith("# routing layers: "): + if routing_layers_line is None: + routing_layers = ( + line.removeprefix("# routing layers: ").strip().split(" ") + ) + routing_layers_line = line + elif routing_layers_line != line: + print("Layer stack inconsistent.", file=stderr) + exit(1) + continue + + line = line.strip() + + if not line or line.startswith("#"): + continue + + tokens = line.split(",") + + if len(tokens) != SEGMENTS_COLUMNS: + print(f"Malformed segment RC line: {line}", file=stderr) + exit(1) + + net_type = tokens[1] + layer = tokens[2] + length = float(tokens[3]) + + layer_segments[layer]["lengths"].append(length) + layer_segments[layer]["resistances"].append(float(tokens[4])) + layer_segments[layer]["capacitances"].append(float(tokens[5])) + layer_net_type_length[layer][net_type] += length + + if not routing_layers: + print("No routing layers header found in the segment RC data.", file=stderr) + exit(1) + + if not layer_segments: + print("No segment RC data found.", file=stderr) + exit(1) + + for key, name in (("resistances", "resistance"), ("capacitances", "capacitance")): + count = sum( + 1 + for segments in layer_segments.values() + for value in segments[key] + if value == 0.0 + ) + print(f"Found {count} segments with zero {name}.") + + return routing_layers, layer_segments, layer_net_type_length + + +# Fitting +# ============================================================================= + + +def fit_layer_models(routing_layers, layer_segments): + layer_models = {} + + for layer_name in routing_layers: + # There may be routing layers with no segments, so we check if the + # layer exists in the dict. + if layer_name not in layer_segments: + continue + + # sklearn requires the input to be 2D, so we reshape to add a dimension + # to the list. + lengths = np.array(layer_segments[layer_name]["lengths"]).reshape(-1, 1) + resistances = np.array(layer_segments[layer_name]["resistances"]) + capacitances_ff = np.array(layer_segments[layer_name]["capacitances"]) + + res_model = LinearRegression(fit_intercept=False).fit(lengths, resistances) + cap_model = LinearRegression(fit_intercept=False).fit(lengths, capacitances_ff) + layer_models[layer_name] = ( + res_model, + cap_model, + lengths, + resistances, + capacitances_ff, + ) + + return layer_models + + +# sklearn's default baseline model for scoring the fit i.e., measuring R² is +# "predict the mean" which is not the proper model for our regressions since +# both R and C are through-origin fits - the R² computation doesn't behave +# well for var(y) ≈ 0 - so we compute R² manually with a "predict zero" +# baseline model. +def compute_through_origin_fit_score(model, inputs, observed): + sum_squared_observed = (observed**2).sum() + if sum_squared_observed == 0: + return "No data" + score = 1.0 - ((observed - model.predict(inputs)) ** 2).sum() / sum_squared_observed + return f"{score:.4f}" + + +def wire_rc_fit( + layer_models, layer_net_type_length, res_scale, cap_scale, target_net_type=None +): + total_length = 0.0 + total_resistance = 0.0 + total_capacitance = 0.0 + + for layer_name, (res_model, cap_model, lengths, _, _) in layer_models.items(): + if target_net_type is not None: + layer_length = sum( + layer_net_type_length[layer_name][net_type] + for net_type in target_net_type + ) + else: + layer_length = float(lengths.sum()) + + total_resistance += res_model.coef_[0] * layer_length + total_capacitance += cap_model.coef_[0] * layer_length + total_length += layer_length + + if total_length == 0.0: + return None + + return ( + total_resistance / total_length / res_scale, + total_capacitance / total_length * CAP_FF_TO_F / cap_scale, + ) + + +# Report +# ============================================================================= + + +def print_fit_scores(layer_models, res_unit, cap_unit): + print("\nUnits: resistance [{}/um], capacitance [{}/um]".format(res_unit, cap_unit)) + + print("{:<13s} | {:>8s} | {:>8s}".format("\nLayer", "Res R²", "Cap R²")) + print("-" * 34) + for layer_name, ( + res_model, + cap_model, + lengths, + resistances, + capacitances_ff, + ) in layer_models.items(): + r_sq_res = compute_through_origin_fit_score(res_model, lengths, resistances) + r_sq_cap = compute_through_origin_fit_score(cap_model, lengths, capacitances_ff) + print("{:<12s} | {:>8s} | {:>8s}".format(layer_name, r_sq_res, r_sq_cap)) + print("-" * 34) + print("") + + +def print_layer_rc(layer_models, res_scale, cap_scale): + for layer_name, (res_model, cap_model, _, _, _) in layer_models.items(): + print( + "set_layer_rc -layer {} -resistance {:.5E} -capacitance {:.5E}".format( + layer_name, + res_model.coef_[0] / res_scale, + cap_model.coef_[0] * CAP_FF_TO_F / cap_scale, + ) + ) + print("") + + +def print_wire_rc(layer_models, layer_net_type_length, res_scale, cap_scale): + resistance, capacitance = wire_rc_fit( + layer_models, layer_net_type_length, res_scale, cap_scale + ) + + print( + "set_wire_rc -resistance {:.5E} -capacitance {:.5E}".format( + resistance, capacitance + ) + ) + + for net_type in ["signal", "clock"]: + result = wire_rc_fit( + layer_models, layer_net_type_length, res_scale, cap_scale, [net_type] + ) + + if result is None: + print("[Warning] No {} nets were found.".format(net_type)) + continue + + resistance, capacitance = result + + print( + "set_wire_rc -{} -resistance {:.5E} -capacitance {:.5E}".format( + net_type, resistance, capacitance + ) + ) + print("") + + +# Plot +# ============================================================================= + + +def plot_grt_rcx_diff(nets, quantity, name, unit, scale, discrepancy_threshold): + differences = [] + differences_percent = [] + + for net in nets: + grt_value = net[f"grt_{quantity}"] + rcx_value = net[f"rcx_{quantity}"] + + if grt_value <= 0.0 or rcx_value <= 0.0: + continue + + difference = grt_value - rcx_value + + if abs(difference) > discrepancy_threshold: + print(f"Large discrepancy: {net['file_name']} {net['name']} {difference}") + + differences.append(difference / scale) + differences_percent.append(difference / rcx_value * 100) + + if not differences: + print(f"No net {name.lower()} data to plot.", file=stderr) + exit(1) + + # Generate histograms + num_bins = 200 + fig = plt.figure() + fig.suptitle(f"Difference between GRT est. and RCX {name}") + plt.subplot(2, 2, 1) + plt.hist(differences, num_bins, facecolor="blue", alpha=0.5) + plt.ylabel("# Nets") + plt.xlabel( + "{} ({})\n\nMean: {:.3f}{}\nStd. dev: {:.3f}{}".format( + name, unit, np.mean(differences), unit, np.std(differences), unit + ) + ) + + plt.subplot(2, 2, 2) + plt.hist( + differences_percent, num_bins, range=(-1000, 1000), facecolor="blue", alpha=0.5 + ) + plt.ylabel("# Nets") + plt.xlabel( + "%\n\nMean: {:.3f}%\nStd. dev: {:.3f}%".format( + np.mean(differences_percent), np.std(differences_percent) + ) + ) + plt.show() From 9306f6d4cccf7479c998a3847bf05033f538d16b Mon Sep 17 00:00:00 2001 From: Arthur Koucher Date: Fri, 31 Jul 2026 16:50:30 -0300 Subject: [PATCH 4/6] fix some issues of the new correlationRC structure: 1) Drop the wirelength columns of the nets .csv along with the CORRELATE_DRT_WIRELENGTH handling, as nothing consumes them. 2) Name the data in the header of each .csv and check it, so that swapped and mismatched input files are caught for both of them. 3) Only report zero parasitics when there are any and only read the nets file when a plot was requested. 4) Document that the .csv files are not regenerated on their own. Signed-off-by: Arthur Koucher --- docs/tutorials/SetRC.md | 3 ++ flow/util/correlateRC.py | 2 +- flow/util/correlateRCHelper.py | 51 ++++++++++++++++++++----------- flow/util/utils.mk | 6 ++-- flow/util/write_rc.tcl | 2 +- flow/util/write_rc_helper.tcl | 56 ++++++++++++---------------------- 6 files changed, 61 insertions(+), 59 deletions(-) diff --git a/docs/tutorials/SetRC.md b/docs/tutorials/SetRC.md index 46995600fa..9b7ca16a6e 100644 --- a/docs/tutorials/SetRC.md +++ b/docs/tutorials/SetRC.md @@ -38,6 +38,9 @@ directory. For example, ./results/asap7/ibex/base/6_segments_rc.csv and RC values, while the nets data is used to plot the difference between the global route estimates and the extracted parasitics. +Note that the CSV files are not regenerated on their own after the design is +run again, so delete them to write the RC data of the new run. + ``` % make DESIGN_CONFIG=./designs/asap7/ibex/config.mk correlate_rc ``` diff --git a/flow/util/correlateRC.py b/flow/util/correlateRC.py index 1a1bf49592..bb1b3a6a28 100755 --- a/flow/util/correlateRC.py +++ b/flow/util/correlateRC.py @@ -36,7 +36,7 @@ # The plots come after the commands so that a plot with no data does not # withhold them. -if args.nets_rc_file: +if args.plot_cap or args.plot_res: nets = read_nets_rc(args.nets_rc_file) if args.plot_cap: diff --git a/flow/util/correlateRCHelper.py b/flow/util/correlateRCHelper.py index cdbeb5dc18..cb7cd5e649 100644 --- a/flow/util/correlateRCHelper.py +++ b/flow/util/correlateRCHelper.py @@ -6,9 +6,12 @@ from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt -# Auxiliary variables to catch swapped input .csv files. -SEGMENTS_COLUMNS = 6 -NETS_MIN_COLUMNS = 7 +# The header of each .csv names its data and lists the layer stack it was +# written for, so it catches both swapped and mismatched input files. +NETS_HEADER = "# Net RC: " +SEGMENTS_HEADER = "# Segment RC: " + +ROW_COLUMNS = 6 # The .csv data comes from ODB which stores capacitance in fF. CAP_FF_TO_F = 1e-15 @@ -88,19 +91,31 @@ def resolve_units(args): def read_nets_rc(file_names): nets = [] + header_line = None for file_name in file_names: print(f"Reading {file_name}.") with open(file_name) as file: for line in file: + if line.startswith(NETS_HEADER): + if header_line is not None and header_line != line: + print("Layer stack inconsistent.", file=stderr) + exit(1) + header_line = line + continue + line = line.strip() if not line or line.startswith("#"): continue + if header_line is None: + print("No net RC header found in the data.", file=stderr) + exit(1) + tokens = line.split(",") - if len(tokens) < NETS_MIN_COLUMNS: + if len(tokens) != ROW_COLUMNS: print(f"Malformed net RC line: {line}", file=stderr) exit(1) @@ -140,21 +155,20 @@ def read_segments_rc(file_names): ) layer_net_type_length = defaultdict(lambda: defaultdict(float)) routing_layers = [] - routing_layers_line = None + header_line = None for file_name in file_names: print(f"Reading {file_name}.") with open(file_name) as file: for line in file: - if line.startswith("# routing layers: "): - if routing_layers_line is None: - routing_layers = ( - line.removeprefix("# routing layers: ").strip().split(" ") - ) - routing_layers_line = line - elif routing_layers_line != line: + if line.startswith(SEGMENTS_HEADER): + if header_line is not None and header_line != line: print("Layer stack inconsistent.", file=stderr) exit(1) + header_line = line + routing_layers = ( + line.removeprefix(SEGMENTS_HEADER).strip().split(" ") + ) continue line = line.strip() @@ -162,9 +176,13 @@ def read_segments_rc(file_names): if not line or line.startswith("#"): continue + if header_line is None: + print("No segment RC header found in the data.", file=stderr) + exit(1) + tokens = line.split(",") - if len(tokens) != SEGMENTS_COLUMNS: + if len(tokens) != ROW_COLUMNS: print(f"Malformed segment RC line: {line}", file=stderr) exit(1) @@ -177,10 +195,6 @@ def read_segments_rc(file_names): layer_segments[layer]["capacitances"].append(float(tokens[5])) layer_net_type_length[layer][net_type] += length - if not routing_layers: - print("No routing layers header found in the segment RC data.", file=stderr) - exit(1) - if not layer_segments: print("No segment RC data found.", file=stderr) exit(1) @@ -192,7 +206,8 @@ def read_segments_rc(file_names): for value in segments[key] if value == 0.0 ) - print(f"Found {count} segments with zero {name}.") + if count > 0: + print(f"Found {count} segments with zero {name}.") return routing_layers, layer_segments, layer_net_type_length diff --git a/flow/util/utils.mk b/flow/util/utils.mk index d1359cece3..145b2682e5 100644 --- a/flow/util/utils.mk +++ b/flow/util/utils.mk @@ -91,12 +91,13 @@ $(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv &: $(RUN_CMD) --log $(LOG_DIR)/6_write_rc.log --tee -- $(OPENROAD_CMD) $(UTILS_DIR)/write_rc.tcl .PHONY: correlate_rc -correlate_rc: $(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv +correlate_rc: $(RESULTS_DIR)/6_segments_rc.csv $(PYTHON_EXE) $(UTILS_DIR)/correlateRC.py \ - -nets_rc_file $(RESULTS_DIR)/6_nets_rc.csv \ -segments_rc_file $(RESULTS_DIR)/6_segments_rc.csv # TODO Make always wants to redo designs with this rule, regardless of which variations are tried. +# $(MAKE) DESIGN_CONFIG=$$config write_rc; \ +#$(foreach config,$(wildcard designs/$(PLATFORM)/*/config.mk),$(MAKE) DESIGN_CONFIG=$(config) write_rc; ) .PHONY: correlate_platform_rc correlate_platform_rc: for config in designs/$(PLATFORM)/*/config.mk; do \ @@ -106,7 +107,6 @@ correlate_platform_rc: results/$(PLATFORM)/$$design/base/6_segments_rc.csv; \ done $(PYTHON_EXE) $(UTILS_DIR)/correlateRC.py \ - -nets_rc_file $$(find results/$(PLATFORM)/*/base -name 6_nets_rc.csv) \ -segments_rc_file $$(find results/$(PLATFORM)/*/base -name 6_segments_rc.csv) # Run test using gnu parallel diff --git a/flow/util/write_rc.tcl b/flow/util/write_rc.tcl index 9d93865282..62922b2b39 100644 --- a/flow/util/write_rc.tcl +++ b/flow/util/write_rc.tcl @@ -12,7 +12,7 @@ fetch_nets_rc rcx_nets_rc write_nets_rc_csv $::env(RESULTS_DIR)/6_nets_rc.csv grt_nets_rc rcx_nets_rc -# Use RCX to compute and ODB API's to fetch segments' parasitics. +# Use RCX to compute and ODB APIs to fetch segments' parasitics. # We set up RCX parameters to avoid any parasitics segment merging. extract_parasitics -ext_model_file $::env(RCX_RULES) -max_res 0 -no_merge_via_res fetch_segments_rc segments_rc diff --git a/flow/util/write_rc_helper.tcl b/flow/util/write_rc_helper.tcl index 85157760c1..41ef5f8719 100644 --- a/flow/util/write_rc_helper.tcl +++ b/flow/util/write_rc_helper.tcl @@ -28,12 +28,11 @@ proc write_nets_rc_csv { filename grt_var rcx_var } { set tech [ord::get_db_tech] set stream [open $filename "w"] - puts -nonewline $stream "# stack:" + # First, write a header naming the data and listing the layer stack. + puts -nonewline $stream "# Net RC:" foreach layer [$tech getLayers] { - set routing [expr [$layer getRoutingLevel] != 0] - set is_routing([$layer getNumber]) $routing puts -nonewline $stream " [$layer getName]" - if { $routing } { + if { [$layer getRoutingLevel] != 0 } { puts -nonewline $stream "(routing)" } else { # insert via resistance information @@ -43,44 +42,28 @@ proc write_nets_rc_csv { filename grt_var rcx_var } { } } } - puts $stream "" - set use_drt_data [env_var_exists_and_non_empty CORRELATE_DRT_WIRELENGTH] + puts $stream "" + # Then, write the parasitics data of each net. foreach net [get_nets *] { set db_net [sta::sta_to_db_net $net] set type [$db_net getSigType] - if { - ([string equal $type "CLOCK"] || [string equal $type "SIGNAL"]) && - (!$use_drt_data || [$db_net getWire] ne "NULL") - } { - set net_name [get_full_name $net] - lassign $grt_net_name_to_rc($net_name) grt_net_res grt_net_cap - lassign $rcx_net_name_to_rc($net_name) rcx_net_res rcx_net_cap - set net_type [expr { [string equal $type "CLOCK"] ? "clock" : "signal" }] - puts -nonewline $stream "$net_name,$net_type," - puts -nonewline $stream [concat \ - [format "%.3e" $grt_net_res] "," [format "%.3e" $grt_net_cap] "," \ - [format "%.3e" $rcx_net_res] "," [format "%.3e" $rcx_net_cap]] - - if { $use_drt_data } { - set layer_lengths [drt::route_layer_lengths [$db_net getWire]] - } else { - set layer_lengths [grt::route_layer_lengths $db_net] - } - for { set layer 0 } { $layer < [$tech getLayerCount] } { incr layer } { - set length [lindex $layer_lengths $layer] - if { $is_routing($layer) } { - puts -nonewline $stream ",[ord::dbu_to_microns $length]" - } else { - puts -nonewline $stream ",$length" - } - } - - puts $stream "" + if { !([string equal $type "CLOCK"] || [string equal $type "SIGNAL"]) } { + continue } + + set net_name [get_full_name $net] + set net_type [expr { $type eq "CLOCK" ? "clock" : "signal" }] + + lassign $grt_net_name_to_rc($net_name) grt_net_res grt_net_cap + lassign $rcx_net_name_to_rc($net_name) rcx_net_res rcx_net_cap + + puts $stream [format "%s,%s,%.3e,%.3e,%.3e,%.3e" \ + $net_name $net_type $grt_net_res $grt_net_cap $rcx_net_res $rcx_net_cap] } + close $stream } @@ -147,8 +130,9 @@ proc write_segments_rc_csv { filename net_to_segments_var } { set stream [open $filename "w"] - # First, write a header listing the routing layers in stack order. - puts -nonewline $stream "# routing layers:" + # First, write a header naming the data and listing the routing layers in + # stack order. + puts -nonewline $stream "# Segment RC:" foreach layer [[ord::get_db_tech] getLayers] { if { [$layer getRoutingLevel] != 0 } { puts -nonewline $stream " [$layer getName]" From b95b2b8d9246aab2bdebe8fc5434ad4f54f11bf2 Mon Sep 17 00:00:00 2001 From: Arthur Koucher Date: Mon, 3 Aug 2026 10:51:38 -0300 Subject: [PATCH 5/6] handle hierarchical nets and mismatched RC data: 1) Fetch and write the nets data of hierarchical designs, which now also blocked the segments data as a single script writes both. 2) Error out on a segment whose layer is not in the header instead of dropping it silently, and inform when the nets and the segments data list different routing layers. 3) Warn instead of failing when no layer was fitted, inform that the nets file is only read to plot and report unknown units on stderr. Signed-off-by: Arthur Koucher --- flow/util/correlateRC.py | 8 ++++++- flow/util/correlateRCHelper.py | 38 ++++++++++++++++++++++------------ flow/util/write_rc_helper.tcl | 7 ++++--- 3 files changed, 36 insertions(+), 17 deletions(-) diff --git a/flow/util/correlateRC.py b/flow/util/correlateRC.py index bb1b3a6a28..6fedb89dd5 100755 --- a/flow/util/correlateRC.py +++ b/flow/util/correlateRC.py @@ -37,10 +37,16 @@ # The plots come after the commands so that a plot with no data does not # withhold them. if args.plot_cap or args.plot_res: - nets = read_nets_rc(args.nets_rc_file) + nets, nets_routing_layers = read_nets_rc(args.nets_rc_file) + + if nets_routing_layers != routing_layers: + print("[Warning] The nets and the segments data have different routing") + print("layers, are the files from different platforms?") if args.plot_cap: plot_grt_rcx_diff(nets, "cap", "Capacitance", cap_unit, cap_scale, 1e-12) if args.plot_res: plot_grt_rcx_diff(nets, "res", "Resistance", res_unit, res_scale, 1e3) +elif args.nets_rc_file: + print("The nets RC data is only read to plot, so it was skipped.") diff --git a/flow/util/correlateRCHelper.py b/flow/util/correlateRCHelper.py index cb7cd5e649..a08319b7d1 100644 --- a/flow/util/correlateRCHelper.py +++ b/flow/util/correlateRCHelper.py @@ -74,7 +74,7 @@ def resolve_units(args): elif res_unit == "kohm": res_scale = 1e3 else: - print("Unknown resistance unit.") + print("Unknown resistance unit.", file=stderr) exit(1) cap_unit = args.cap_unit @@ -83,7 +83,7 @@ def resolve_units(args): elif cap_unit == "pf": cap_scale = 1e-12 else: - print("Unknown capacitance unit.") + print("Unknown capacitance unit.", file=stderr) exit(1) return res_unit, res_scale, cap_unit, cap_scale @@ -91,21 +91,27 @@ def resolve_units(args): def read_nets_rc(file_names): nets = [] + routing_layers = [] header_line = None for file_name in file_names: print(f"Reading {file_name}.") with open(file_name) as file: for line in file: + line = line.strip() + if line.startswith(NETS_HEADER): if header_line is not None and header_line != line: print("Layer stack inconsistent.", file=stderr) exit(1) header_line = line + routing_layers = [ + layer.removesuffix("(routing)") + for layer in line.removeprefix(NETS_HEADER).split() + if layer.endswith("(routing)") + ] continue - line = line.strip() - if not line or line.startswith("#"): continue @@ -146,7 +152,7 @@ def read_nets_rc(file_names): if count > 0: print(f"Found {count} nets with zero {name}.") - return nets + return nets, routing_layers def read_segments_rc(file_names): @@ -161,18 +167,16 @@ def read_segments_rc(file_names): print(f"Reading {file_name}.") with open(file_name) as file: for line in file: + line = line.strip() + if line.startswith(SEGMENTS_HEADER): if header_line is not None and header_line != line: print("Layer stack inconsistent.", file=stderr) exit(1) header_line = line - routing_layers = ( - line.removeprefix(SEGMENTS_HEADER).strip().split(" ") - ) + routing_layers = line.removeprefix(SEGMENTS_HEADER).split() continue - line = line.strip() - if not line or line.startswith("#"): continue @@ -190,6 +194,10 @@ def read_segments_rc(file_names): layer = tokens[2] length = float(tokens[3]) + if layer not in routing_layers: + print(f"Layer {layer} is not in the header.", file=stderr) + exit(1) + layer_segments[layer]["lengths"].append(length) layer_segments[layer]["resistances"].append(float(tokens[4])) layer_segments[layer]["capacitances"].append(float(tokens[5])) @@ -322,9 +330,13 @@ def print_layer_rc(layer_models, res_scale, cap_scale): def print_wire_rc(layer_models, layer_net_type_length, res_scale, cap_scale): - resistance, capacitance = wire_rc_fit( - layer_models, layer_net_type_length, res_scale, cap_scale - ) + result = wire_rc_fit(layer_models, layer_net_type_length, res_scale, cap_scale) + + if result is None: + print("[Warning] No layer was fitted.") + return + + resistance, capacitance = result print( "set_wire_rc -resistance {:.5E} -capacitance {:.5E}".format( diff --git a/flow/util/write_rc_helper.tcl b/flow/util/write_rc_helper.tcl index 41ef5f8719..537d67e3c1 100644 --- a/flow/util/write_rc_helper.tcl +++ b/flow/util/write_rc_helper.tcl @@ -4,7 +4,7 @@ proc fetch_nets_rc { var_name } { upvar 1 $var_name var - foreach net [get_nets *] { + foreach net [get_nets -hierarchical *] { set net_name [get_full_name $net] set wire_res [net_wire_res $net] set wire_cap [net_wire_cap $net] @@ -28,7 +28,8 @@ proc write_nets_rc_csv { filename grt_var rcx_var } { set tech [ord::get_db_tech] set stream [open $filename "w"] - # First, write a header naming the data and listing the layer stack. + # First, write a header naming the data and listing the layer stack, which + # is only read back as a fingerprint of the stack. puts -nonewline $stream "# Net RC:" foreach layer [$tech getLayers] { puts -nonewline $stream " [$layer getName]" @@ -46,7 +47,7 @@ proc write_nets_rc_csv { filename grt_var rcx_var } { puts $stream "" # Then, write the parasitics data of each net. - foreach net [get_nets *] { + foreach net [get_nets -hierarchical *] { set db_net [sta::sta_to_db_net $net] set type [$db_net getSigType] From bb38c3d775494bcf496dda82615c9f8fa0108f6b Mon Sep 17 00:00:00 2001 From: Arthur Koucher Date: Mon, 3 Aug 2026 11:59:25 -0300 Subject: [PATCH 6/6] address review comments of the RC data readers and rule: 1) Require a header on each input file, so that a file of another kind is not read against the header of the previous one, and name the file that is missing it. 2) Write both .csv files with a pattern rule, as the grouped target syntax requires GNU Make 4.3 while we support older releases. Signed-off-by: Arthur Koucher --- flow/util/correlateRCHelper.py | 18 ++++++++++++++---- flow/util/utils.mk | 4 +++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/flow/util/correlateRCHelper.py b/flow/util/correlateRCHelper.py index a08319b7d1..8880d9299f 100644 --- a/flow/util/correlateRCHelper.py +++ b/flow/util/correlateRCHelper.py @@ -96,6 +96,10 @@ def read_nets_rc(file_names): for file_name in file_names: print(f"Reading {file_name}.") + # Each file has to bring its own header, so that a file of another kind + # is not read against the header of the previous one. + file_header_line = None + with open(file_name) as file: for line in file: line = line.strip() @@ -105,6 +109,7 @@ def read_nets_rc(file_names): print("Layer stack inconsistent.", file=stderr) exit(1) header_line = line + file_header_line = line routing_layers = [ layer.removesuffix("(routing)") for layer in line.removeprefix(NETS_HEADER).split() @@ -115,8 +120,8 @@ def read_nets_rc(file_names): if not line or line.startswith("#"): continue - if header_line is None: - print("No net RC header found in the data.", file=stderr) + if file_header_line is None: + print(f"No net RC header found in {file_name}.", file=stderr) exit(1) tokens = line.split(",") @@ -165,6 +170,10 @@ def read_segments_rc(file_names): for file_name in file_names: print(f"Reading {file_name}.") + # Each file has to bring its own header, so that a file of another kind + # is not read against the header of the previous one. + file_header_line = None + with open(file_name) as file: for line in file: line = line.strip() @@ -174,14 +183,15 @@ def read_segments_rc(file_names): print("Layer stack inconsistent.", file=stderr) exit(1) header_line = line + file_header_line = line routing_layers = line.removeprefix(SEGMENTS_HEADER).split() continue if not line or line.startswith("#"): continue - if header_line is None: - print("No segment RC header found in the data.", file=stderr) + if file_header_line is None: + print(f"No segment RC header found in {file_name}.", file=stderr) exit(1) tokens = line.split(",") diff --git a/flow/util/utils.mk b/flow/util/utils.mk index 145b2682e5..e6b35c79e4 100644 --- a/flow/util/utils.mk +++ b/flow/util/utils.mk @@ -87,7 +87,9 @@ update_metadata_autotuner: .PHONY: write_rc write_rc: $(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv -$(RESULTS_DIR)/6_nets_rc.csv $(RESULTS_DIR)/6_segments_rc.csv &: +# A pattern rule to write both files with a single run, as the grouped target +# syntax requires GNU Make 4.3. +%_nets_rc.csv %_segments_rc.csv: $(RUN_CMD) --log $(LOG_DIR)/6_write_rc.log --tee -- $(OPENROAD_CMD) $(UTILS_DIR)/write_rc.tcl .PHONY: correlate_rc