Repository navigation
Expand file tree
/
Copy pathTask5.py
More file actions
144 lines (118 loc) · 4.56 KB
/
Copy pathTask5.py
File metadata and controls
144 lines (118 loc) · 4.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import os
import json
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
# Load dataset
try:
df = pd.read_csv("output/nodes.csv")
except FileNotFoundError:
print("Error: output/nodes.csv not found")
exit(1)
# Make sure t_days and depth are numeric
df = df.copy()
df["t_days"] = pd.to_numeric(df["t_days"], errors="coerce")
df["depth"] = pd.to_numeric(df["depth"], errors="coerce")
valid = df.dropna(subset=["t_days", "depth"])
valid = valid[(valid["depth"] >= 0) & (valid["depth"] <= 5)]
print(f"Total edges with valid t_days and depth: {len(valid)} (out of {len(df)} total edges)")
# Optional Category Check
if "category" in valid.columns:
print("\nAuto-fix share by depth (from category column):")
print(f"{'Depth':<6} | {'N':<6} | {'Auto-fix %':<10}")
for d in sorted(valid["depth"].dropna().astype(int).unique()):
subset = valid[valid["depth"] == d]
n = len(subset)
auto = (subset["category"] == "auto_fix").sum()
share = (auto / n * 100.0) if n > 0 else 0.0
print(f"{d:<6} | {n:<6} | {share:<10.1f}")
else:
print("\nNo 'category' column found; skipping auto-fix structural check.")
pos = valid[valid["t_days"] > 0].copy()
print("\nPositive t_days count per depth (<= 5):")
for d in sorted(pos["depth"].dropna().astype(int).unique()):
n_d = len(pos[pos["depth"] == d])
print(f" depth {d}: {n_d} positive values")
depths = sorted(pos["depth"].dropna().astype(int).unique())
if len(depths) == 0:
print("\nNo positive t_days; skipping violin plot.")
else:
# Data per depth
data_by_depth = [pos[pos["depth"] == d]["t_days"].values for d in depths]
plt.figure(figsize=(8, 5))
vp = plt.violinplot(
data_by_depth,
positions=depths,
showmeans=True,
showmedians=False,
showextrema=False,
)
plt.xticks(depths, [str(d) for d in depths])
plt.xlabel("Dependency depth d(u)")
plt.ylabel("Repair time t_days (positive tail)")
plt.title("Empirical repair times by depth (npm, Task 5)")
# Plot depth means clearly without forced lines
means = [np.mean(arr) if len(arr) > 0 else np.nan for arr in data_by_depth]
x_vals = np.array(depths, dtype=float)
y_vals = np.array(means, dtype=float)
plt.scatter(x_vals, y_vals, color="black", zorder=3, label="Depth means")
plt.ylim(bottom=0)
plt.legend(loc="best")
plt.tight_layout()
os.makedirs("output", exist_ok=True)
out_violin = "output/mean_violin_regression_plot_npm.png"
plt.savefig(out_violin, dpi=200)
plt.close()
print(f"\nSaved {out_violin}")
# Gamma Fitting Part
gamma_min = 2
fit_results = []
for d in range(0, 6): # depths 0..5
tail = pos[pos["depth"] == d]["t_days"].values
if len(tail) < gamma_min:
continue
alpha_val, loc, scale = stats.gamma.fit(tail, floc=0)
rate_val = 1.0 / scale if scale > 0 else np.nan
fit_results.append({
"depth": d,
"alpha": alpha_val,
"rate": rate_val,
"n": len(tail),
})
used_levels = [r["depth"] for r in fit_results]
print("\nGamma fits used depths:", used_levels)
if len(fit_results) > 0:
fit_df = pd.DataFrame(fit_results)
plt.figure(figsize=(9, 4))
# Left: alpha vs depth with linear pilot fit
plt.subplot(1, 2, 1)
plt.scatter(fit_df["depth"], fit_df["alpha"], color="blue", label="Gamma α(d)")
plt.xlabel("Depth d(u)")
plt.ylabel("Gamma shape α")
plt.title("Pilot Gamma shape vs depth")
if len(fit_df) >= 2:
x = fit_df["depth"].values.astype(float)
y = fit_df["alpha"].values.astype(float)
a_slope, a_intercept = np.polyfit(x, y, 1)
plt.plot(x, a_slope * x + a_intercept, color="red", linestyle="--", label="Linear pilot fit")
plt.legend(loc="best")
# Right: beta (rate) vs depth with pilot linear fit
plt.subplot(1, 2, 2)
plt.scatter(fit_df["depth"], fit_df["rate"], color="green", label="Gamma β(d)")
plt.xlabel("Depth d(u)")
plt.ylabel("Gamma rate β")
plt.title("Pilot Gamma rate vs depth")
if len(fit_df) >= 2:
x = fit_df["depth"].values.astype(float)
y = fit_df["rate"].values.astype(float)
r_slope, r_intercept = np.polyfit(x, y, 1)
plt.plot(x, r_slope * x + r_intercept, color="red", linestyle="--", label="Linear pilot fit")
plt.legend(loc="best")
plt.tight_layout()
out_gamma = "output/gamma_trends_fit.png"
plt.savefig(out_gamma, dpi=200)
plt.close()
print(f"Saved {out_gamma}")
else:
print("No depths had enough data for pilot Gamma fitting; skipped gamma_trends_fit.png")