-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsvtoepsgraphV7.py
More file actions
141 lines (100 loc) · 3.99 KB
/
csvtoepsgraphV7.py
File metadata and controls
141 lines (100 loc) · 3.99 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
import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import warnings
warnings.filterwarnings('ignore')
# ================= IEEE STYLE =================
def setup_plot_style():
plt.rcdefaults()
plt.close('all')
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
"font.serif": ["Latin Modern Roman"],
"font.size": 10,
"axes.labelsize": 10,
"xtick.labelsize": 10,
"ytick.labelsize": 10,
"axes.linewidth": 0.8,
"axes.edgecolor": "black",
})
# ============================================
parent_folder = r"C:\Users\deepe\Documents\MB MRF trailer pbn cbn processed_shivam\MRF tyre\All_Bias"
colors = ['mediumblue', 'red', 'magenta', 'green', 'purple']
print("\n🔎 Searching for CSV files recursively...\n")
# Walk through ALL folders
for root, dirs, files in os.walk(parent_folder):
csv_files = [f for f in files if f.lower().endswith(".csv")]
for csv_file in csv_files:
csv_path = os.path.join(root, csv_file)
print(f"📁 Processing: {csv_path}")
setup_plot_style()
try:
df = pd.read_csv(csv_path)
except Exception as e:
print(f"⚠️ Error reading {csv_file}: {e}")
continue
if df.shape[1] < 2:
print("⚠️ Not enough columns to plot")
continue
# FIXED LABELS
x_label = "Time (s)"
y_label = "SPL (dB)"
time = pd.to_numeric(df.iloc[:, 0], errors="coerce")
fig, ax = plt.subplots(figsize=(3.5, 2.5))
max_time = 0
# Plot all SPL columns dynamically (from column 2 onwards)
# Store maxima values
max_values = []
# Plot all SPL columns dynamically
for i in range(1, df.shape[1]):
spl = pd.to_numeric(df.iloc[:, i], errors="coerce")
valid = ~(time.isna() | spl.isna())
t = time[valid]
s = spl[valid]
if len(t) == 0:
continue
color = colors[(i-1) % len(colors)]
# ===== Calculate Maximum =====
max_value = s.max()
max_values.append(max_value)
# =============================
ax.plot(t, s,
color=color,
linewidth=1.5,
label=f"Run {i}, Max = {max_value:.2f} dB")
max_time = max(max_time, t.max())
# ===== Add Average of Maxima =====
if len(max_values) > 0:
avg_max = sum(max_values) / len(max_values)
# Add invisible plot only for legend entry
ax.plot([], [],
linestyle="",
label=f"Avg = {avg_max:.2f} dB")
# =================================
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.legend(fontsize=8)
ax.xaxis.set_major_locator(ticker.MultipleLocator(2.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.5))
ax.yaxis.set_major_locator(ticker.MultipleLocator(2.0))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.5))
ax.minorticks_on()
ax.set_xlim(left=0, right=max_time)
ax.grid(True, which='major', linestyle='--', linewidth=0.4, alpha=0.5)
ax.grid(True, which='minor', linestyle='-.', linewidth=0.3, alpha=0.3)
plt.tight_layout(pad=0.2)
# Output file name based on CSV name
base_name = os.path.splitext(csv_file)[0]
eps_file = os.path.join(root, base_name + ".eps")
pdf_file = os.path.join(root, base_name + ".pdf")
if os.path.exists(eps_file):
os.remove(eps_file)
if os.path.exists(pdf_file):
os.remove(pdf_file)
plt.savefig(eps_file, format="eps", bbox_inches="tight", dpi=300)
plt.savefig(pdf_file, format="pdf", bbox_inches="tight", dpi=300)
plt.close(fig)
print(f"✅ Graph saved in: {root}\n")
print("\n🎯 All CSV files processed successfully!")