-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsvtoepsgraphV4.py
More file actions
131 lines (99 loc) · 4.32 KB
/
csvtoepsgraphV4.py
File metadata and controls
131 lines (99 loc) · 4.32 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
# This script processes subfolders, reads all CSV files from each subfolder,
# combines them into a single IEEE-style plot, and saves the output in the same subfolder.
import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# ================= IEEE STYLE (No LaTeX) =================
plt.rcParams.update({
"text.usetex": False,
"font.family": "serif",
"font.serif": ["Latin Modern Roman", "Times New Roman"],
"font.size": 8,
"axes.labelsize": 8,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"axes.linewidth": 0.8,
"axes.edgecolor": "black",
"axes.labelcolor": "black",
"xtick.color": "black",
"ytick.color": "black",
})
# ==========================================================
parent_folder = r"D:\Project\IITDelhi\onosokki\till\log10\testinput"
# Get all subfolders
subfolders = [f for f in os.listdir(parent_folder)
if os.path.isdir(os.path.join(parent_folder, f))]
colors = ['blue', 'red', 'magenta', 'green', 'purple', 'brown']
for subfolder_name in subfolders:
subfolder_path = os.path.join(parent_folder, subfolder_name)
# Get all CSV files in this subfolder
csv_files = [f for f in os.listdir(subfolder_path)
if f.lower().endswith(".csv")]
if len(csv_files) == 0:
print(f"⏭️ Skipping {subfolder_name} (No CSV files found)")
continue
print(f"📁 Processing {subfolder_name} ({len(csv_files)} files)...")
# ============== IEEE FIGURE ==================
fig, ax = plt.subplots(figsize=(3.5, 2.5))
max_final_time = 0
plot_count = 0
for idx, fname in enumerate(csv_files):
csv_path = os.path.join(subfolder_path, fname)
try:
df = pd.read_csv(csv_path)
except Exception as e:
print(f" ⚠️ Error reading {fname}: {e}")
continue
# Check if required columns exist
if "Time" not in df.columns or "dB(A)" not in df.columns:
print(f" ⚠️ {fname} - Missing 'Time' or 'dB(A)' columns")
continue
time = pd.to_numeric(df["Time"], errors="coerce")
spl = pd.to_numeric(df["dB(A)"], errors="coerce")
# Remove rows with NaN values
valid = ~(time.isna() | spl.isna())
time = time[valid].reset_index(drop=True)
spl = spl[valid].reset_index(drop=True)
if len(time) == 0:
print(f" ⚠️ {fname} - No numeric data")
continue
# Use color cycling if more than 6 files
color = colors[idx % len(colors)]
ax.plot(time, spl, color=color, linewidth=1.2,
label=f"Run {plot_count + 1}")
max_final_time = max(max_final_time, time.max())
plot_count += 1
if plot_count == 0:
print(f" ❌ {subfolder_name} - No valid CSV files to plot")
plt.close()
continue
ax.set_xlabel("Time (s)")
ax.set_ylabel("SPL dB(A)")
ax.legend(loc='best', fontsize=6)
# Set X-axis to show fewer, readable labels (every 2 seconds)
ax.xaxis.set_major_locator(ticker.MultipleLocator(2.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.5))
ax.minorticks_on()
# Force the end value to appear on x-axis
ax.set_xlim(left=0, right=max_final_time)
# Create custom ticks
max_tick = int(max_final_time / 2.0) * 2.0
custom_ticks = list(range(0, int(max_tick) + 1, 2))
if max_final_time not in custom_ticks and max_final_time != max_tick:
custom_ticks.append(max_final_time)
custom_ticks.sort()
ax.set_xticks(custom_ticks)
# Grid
ax.grid(True, which='major', linestyle='-', linewidth=0.4, alpha=0.5, color='gray')
ax.grid(True, which='minor', linestyle=':', linewidth=0.4, alpha=0.5, color='gray')
plt.tight_layout(pad=0.2)
# Save in the same subfolder
output_name = f"{subfolder_name}_combined"
plt.savefig(os.path.join(subfolder_path, output_name + ".eps"),
format="eps", bbox_inches="tight", dpi=1200)
plt.savefig(os.path.join(subfolder_path, output_name + ".pdf"),
format="pdf", bbox_inches="tight", dpi=1200)
plt.close()
print(f" ✅ Combined plot created: {output_name}")
print("\n✅ All subfolders processed!")