|
| 1 | +""" |
| 2 | +Plot hand position (scan depth) and retention ratio for CLOCK and SIEVE. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + python3 scripts/plot_hand_position.py tracking_*.csv |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import numpy as np |
| 11 | +import matplotlib.pyplot as plt |
| 12 | + |
| 13 | +sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
| 14 | +from utils.plot_utils import * |
| 15 | + |
| 16 | + |
| 17 | +def plot_tracking(csv_files, output_name="hand_position", trace_name=None): |
| 18 | + has_hand_pos = False |
| 19 | + |
| 20 | + # load data |
| 21 | + data = {} |
| 22 | + for f in csv_files: |
| 23 | + # extract algo name from filename: tracking_[trace_]algo_size.csv |
| 24 | + base = os.path.basename(f) |
| 25 | + # strip extensions like .csv, .csv.plot |
| 26 | + for ext in [".csv.plot", ".plot", ".csv"]: |
| 27 | + if base.endswith(ext): |
| 28 | + base = base[:-len(ext)] |
| 29 | + break |
| 30 | + if base.startswith("tracking_"): |
| 31 | + base = base[len("tracking_"):] |
| 32 | + # split off the trailing cache size (last _number segment) |
| 33 | + parts = base.rsplit("_", 1) |
| 34 | + label = parts[0] if len(parts) == 2 and parts[1].isdigit() else base |
| 35 | + with open(f) as fh: |
| 36 | + header = fh.readline().strip().split(",") |
| 37 | + cols = np.genfromtxt(f, delimiter=",", skip_header=1) |
| 38 | + if cols.ndim == 1: |
| 39 | + continue |
| 40 | + data[label] = (header, cols) |
| 41 | + if "hand_pos" in header: |
| 42 | + has_hand_pos = True |
| 43 | + |
| 44 | + if not data: |
| 45 | + print("No valid data found") |
| 46 | + return |
| 47 | + |
| 48 | + n_plots = 3 if has_hand_pos else 2 |
| 49 | + fig, axes = plt.subplots(n_plots, 1, figsize=(10, 4 * n_plots), sharex=True) |
| 50 | + |
| 51 | + colors = ["navy", "darkorange", "tab:green", "cornflowerblue", "tab:red", "tab:purple"] |
| 52 | + linestyles = ["-", "--", "-.", ":"] |
| 53 | + |
| 54 | + for i, (label, (header, cols)) in enumerate(data.items()): |
| 55 | + color = colors[i % len(colors)] |
| 56 | + ls = linestyles[i % len(linestyles)] |
| 57 | + vtime = cols[:, 0] |
| 58 | + |
| 59 | + # scan depth |
| 60 | + scan_idx = header.index("avg_scan_depth") |
| 61 | + axes[0].plot(vtime, cols[:, scan_idx], label=label, color=color, |
| 62 | + linestyle=ls, linewidth=1.5) |
| 63 | + |
| 64 | + # retention ratio |
| 65 | + ret_idx = header.index("retention_ratio") |
| 66 | + axes[1].plot(vtime, cols[:, ret_idx], label=label, color=color, |
| 67 | + linestyle=ls, linewidth=1.5) |
| 68 | + |
| 69 | + # hand position (SIEVE only) |
| 70 | + if has_hand_pos and "hand_pos" in header: |
| 71 | + hp_idx = header.index("hand_pos") |
| 72 | + axes[2].plot(vtime, cols[:, hp_idx], label=label, color=color, |
| 73 | + linestyle=ls, linewidth=1.5) |
| 74 | + |
| 75 | + axes[0].set_ylabel("Avg Scan Depth\n(objects per eviction)") |
| 76 | + axes[0].legend(frameon=False) |
| 77 | + axes[0].grid(axis="y", linestyle="--", alpha=0.5) |
| 78 | + |
| 79 | + axes[1].set_ylabel("Retention Ratio") |
| 80 | + axes[1].legend(frameon=False) |
| 81 | + axes[1].grid(axis="y", linestyle="--", alpha=0.5) |
| 82 | + axes[1].set_ylim(-0.05, 1.05) |
| 83 | + |
| 84 | + if has_hand_pos: |
| 85 | + axes[2].set_ylabel("Hand Position\n(0=tail, 1=head)") |
| 86 | + axes[2].legend(frameon=False) |
| 87 | + axes[2].grid(axis="y", linestyle="--", alpha=0.5) |
| 88 | + axes[2].set_ylim(-0.05, 1.05) |
| 89 | + |
| 90 | + axes[-1].set_xlabel("Virtual Time (requests)") |
| 91 | + |
| 92 | + if trace_name: |
| 93 | + fig.suptitle(trace_name, fontsize=14, y=1.02) |
| 94 | + |
| 95 | + plt.tight_layout() |
| 96 | + os.makedirs("figure", exist_ok=True) |
| 97 | + plt.savefig("figure/{}.pdf".format(output_name), bbox_inches="tight") |
| 98 | + plt.savefig("figure/{}.png".format(output_name), bbox_inches="tight", dpi=150) |
| 99 | + plt.close() |
| 100 | + print("Plots saved to figure/{}.pdf and figure/{}.png".format(output_name, output_name)) |
| 101 | + |
| 102 | + |
| 103 | +def plot_binned_retention(csv_files, output_name="retention_by_position", trace_name=None): |
| 104 | + """Box plot of retention ratio at different hand positions in SIEVE.""" |
| 105 | + fig, ax = plt.subplots(1, 1, figsize=(10, 5)) |
| 106 | + plt.rcParams.update({'font.size': 16}) |
| 107 | + |
| 108 | + colors = ["navy", "darkorange", "tab:green", "cornflowerblue"] |
| 109 | + |
| 110 | + # load all valid files first |
| 111 | + all_data = [] |
| 112 | + for f in csv_files: |
| 113 | + label = os.path.basename(f) |
| 114 | + for ext in [".csv.plot", ".plot", ".csv"]: |
| 115 | + if label.endswith(ext): |
| 116 | + label = label[:-len(ext)] |
| 117 | + break |
| 118 | + # strip any single-char temp prefixes like "a_" or "b_" |
| 119 | + if len(label) > 2 and label[1] == '_' and label[0].isalpha(): |
| 120 | + label = label[2:] |
| 121 | + if label.startswith("tracking_"): |
| 122 | + label = label[len("tracking_"):] |
| 123 | + label = label.replace("_binned", "") |
| 124 | + # remove duplicate trace prefix (e.g. "w100_tracking_w100_Sieve" -> "Sieve") |
| 125 | + if "_tracking_" in label: |
| 126 | + label = label.split("_tracking_")[-1] |
| 127 | + parts = label.rsplit("_", 1) |
| 128 | + label = parts[0] if len(parts) == 2 and parts[1].isdigit() else label |
| 129 | + |
| 130 | + with open(f) as fh: |
| 131 | + header = fh.readline().strip().split(",") |
| 132 | + cols = np.genfromtxt(f, delimiter=",", skip_header=1) |
| 133 | + if cols.ndim == 1 or cols.shape[0] < 2: |
| 134 | + continue |
| 135 | + all_data.append((label, header, cols)) |
| 136 | + |
| 137 | + if not all_data: |
| 138 | + print("No valid data found") |
| 139 | + return |
| 140 | + |
| 141 | + n_files = len(all_data) |
| 142 | + n_bins = len(all_data[0][1]) - 1 |
| 143 | + width = 0.7 / n_files |
| 144 | + bin_labels = [] |
| 145 | + |
| 146 | + for fi, (label, header, cols) in enumerate(all_data): |
| 147 | + bin_data = [] |
| 148 | + bin_labels = [] |
| 149 | + for b in range(n_bins): |
| 150 | + vals = cols[:, b + 1] |
| 151 | + vals = vals[vals >= 0] |
| 152 | + bin_data.append(vals) |
| 153 | + bin_labels.append(header[b + 1].replace("ret_", "") + "%") |
| 154 | + |
| 155 | + offset = (fi - (n_files - 1) / 2) * width |
| 156 | + positions = np.arange(n_bins) + offset |
| 157 | + bp = ax.boxplot(bin_data, positions=positions, widths=width * 0.9, |
| 158 | + patch_artist=True, showfliers=False, |
| 159 | + medianprops=dict(color="black", linewidth=1.5)) |
| 160 | + color = colors[fi % len(colors)] |
| 161 | + for patch in bp['boxes']: |
| 162 | + patch.set_facecolor(color) |
| 163 | + patch.set_alpha(0.7) |
| 164 | + # legend entry |
| 165 | + ax.plot([], [], color=color, linewidth=8, alpha=0.7, label=label) |
| 166 | + |
| 167 | + ax.set_xticks(range(n_bins)) |
| 168 | + ax.set_xticklabels(bin_labels, rotation=45, ha="right", fontsize=12) |
| 169 | + ax.legend(frameon=False) |
| 170 | + ax.set_xlabel("Hand Position (% from tail toward head)") |
| 171 | + ax.set_ylabel("Retention Ratio") |
| 172 | + ax.set_ylim(-0.05, 1.05) |
| 173 | + ax.grid(axis="y", linestyle="--", alpha=0.5) |
| 174 | + |
| 175 | + if trace_name: |
| 176 | + ax.set_title(trace_name) |
| 177 | + |
| 178 | + plt.tight_layout() |
| 179 | + os.makedirs("figure", exist_ok=True) |
| 180 | + plt.savefig("figure/{}.pdf".format(output_name), bbox_inches="tight") |
| 181 | + plt.savefig("figure/{}.png".format(output_name), bbox_inches="tight", dpi=150) |
| 182 | + plt.close() |
| 183 | + print("Plots saved to figure/{}.pdf and figure/{}.png".format(output_name, output_name)) |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == "__main__": |
| 187 | + import argparse |
| 188 | + p = argparse.ArgumentParser(description="Plot hand position and retention ratio") |
| 189 | + p.add_argument("files", nargs="+", help="tracking CSV files") |
| 190 | + p.add_argument("--name", type=str, default="hand_position", help="output file name") |
| 191 | + p.add_argument("--trace", type=str, default=None, help="trace name for plot title") |
| 192 | + p.add_argument("--binned", action="store_true", help="plot binned retention box plot") |
| 193 | + args = p.parse_args() |
| 194 | + |
| 195 | + if args.binned: |
| 196 | + plot_binned_retention(args.files, args.name, args.trace) |
| 197 | + else: |
| 198 | + plot_tracking(args.files, args.name, args.trace) |
0 commit comments