-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotCSVs.py
More file actions
226 lines (188 loc) · 8.47 KB
/
plotCSVs.py
File metadata and controls
226 lines (188 loc) · 8.47 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""CSV Plot Comparator — pick CSVs from a folder and overlay them on one figure.
Revision history
----------------
2026-04 : Initial release. Originally created by Andak Consulting.
License
-------
MIT License
Copyright (c) 2026 Andak Consulting
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import csv
import os
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("CSV Plot Comparator")
self.geometry("820x500")
self._folder = tk.StringVar(value=os.getcwd())
self._legend_text = tk.StringVar(value="")
self._build_ui()
self._refresh_files()
# ------------------------------------------------------------------ UI --
def _build_ui(self):
# Folder picker
folder_frame = ttk.Frame(self, padding=(6, 6, 6, 2))
folder_frame.pack(fill="x")
ttk.Label(folder_frame, text="Folder:").pack(side="left")
ttk.Entry(folder_frame, textvariable=self._folder).pack(
side="left", fill="x", expand=True, padx=4
)
ttk.Button(folder_frame, text="Browse", command=self._browse).pack(side="left")
ttk.Button(folder_frame, text="Refresh", command=self._refresh_files).pack(
side="left", padx=4
)
# Two listboxes + move buttons
lists_frame = ttk.Frame(self, padding=(6, 2))
lists_frame.pack(fill="both", expand=True)
left = ttk.LabelFrame(lists_frame, text="Available", padding=4)
left.pack(side="left", fill="both", expand=True)
self._available = tk.Listbox(left, selectmode="extended", exportselection=False)
sb1 = ttk.Scrollbar(left, command=self._available.yview)
self._available.configure(yscrollcommand=sb1.set)
sb1.pack(side="right", fill="y")
self._available.pack(fill="both", expand=True)
self._available.bind("<Double-Button-1>", lambda _e: self._move_right())
btn_mid = ttk.Frame(lists_frame, padding=(6, 4))
btn_mid.pack(side="left", fill="y")
ttk.Button(btn_mid, text=">>", width=4, command=self._move_right).pack(pady=4)
ttk.Button(btn_mid, text="<<", width=4, command=self._move_left).pack(pady=4)
right = ttk.LabelFrame(lists_frame, text="Selected", padding=4)
right.pack(side="left", fill="both", expand=True)
self._selected = tk.Listbox(right, selectmode="extended", exportselection=False)
sb2 = ttk.Scrollbar(right, command=self._selected.yview)
self._selected.configure(yscrollcommand=sb2.set)
sb2.pack(side="right", fill="y")
self._selected.pack(fill="both", expand=True)
self._selected.bind("<Double-Button-1>", lambda _e: self._move_left())
# Legend + Execute
bottom = ttk.Frame(self, padding=(6, 4, 6, 6))
bottom.pack(fill="x")
ttk.Label(bottom, text="Legend (comma-separated, one per file):").pack(
side="left"
)
ttk.Entry(bottom, textvariable=self._legend_text).pack(
side="left", fill="x", expand=True, padx=4
)
ttk.Button(bottom, text="Execute", command=self._execute).pack(side="left")
# ------------------------------------------------------------ Files ---
def _browse(self):
folder = filedialog.askdirectory(initialdir=self._folder.get() or os.getcwd())
if folder:
self._folder.set(folder)
self._refresh_files()
def _refresh_files(self):
self._available.delete(0, "end")
self._selected.delete(0, "end")
folder = self._folder.get()
if not folder or not os.path.isdir(folder):
return
for f in sorted(f for f in os.listdir(folder) if f.lower().endswith(".csv")):
self._available.insert("end", f)
# --------------------------------------------------------- Move items ---
def _move_right(self):
sel = self._available.curselection()
if not sel:
return
items = [self._available.get(i) for i in sel]
for i in reversed(sel):
self._available.delete(i)
for item in items:
self._selected.insert("end", item)
def _move_left(self):
sel = self._selected.curselection()
if not sel:
return
items = [self._selected.get(i) for i in sel]
for i in reversed(sel):
self._selected.delete(i)
# Merge back into available and re-sort so it matches folder order.
merged = sorted(list(self._available.get(0, "end")) + items)
self._available.delete(0, "end")
for item in merged:
self._available.insert("end", item)
# ------------------------------------------------------------- Plot ---
def _execute(self):
files = list(self._selected.get(0, "end"))
if not files:
messagebox.showinfo("No files", "Move some files to 'Selected' first.")
return
folder = self._folder.get()
raw_labels = self._legend_text.get().strip()
labels = [s.strip() for s in raw_labels.split(",")] if raw_labels else []
# First pass: read all files and find the max absolute time across them.
loaded: list[tuple[str, np.ndarray, list[np.ndarray], list[str]]] = []
max_abs_t = 0.0
for idx, fname in enumerate(files):
path = os.path.join(folder, fname)
try:
t, signals, headers = _read_csv(path)
except Exception as e:
messagebox.showerror("Read failed", f"{fname}: {e}")
continue
base = labels[idx] if idx < len(labels) and labels[idx] else Path(fname).stem
loaded.append((base, t, signals, headers))
if len(t):
max_abs_t = max(max_abs_t, float(np.max(np.abs(t))))
if not loaded:
return
scale, unit = _pick_time_unit(max_abs_t)
fig, ax = plt.subplots(figsize=(10, 6))
for base, t, signals, headers in loaded:
for sig, header in zip(signals, headers):
label = f"{base} — {header}" if len(signals) > 1 else base
ax.plot(t * scale, sig, linewidth=1.5, label=label)
ax.set_xlabel(f"Time ({unit})")
ax.set_ylabel("Voltage (V)")
ax.grid(True)
ax.legend(fontsize="small")
fig.tight_layout()
plt.show()
def _pick_time_unit(max_abs_t: float) -> tuple[float, str]:
"""Pick a human-friendly time unit based on the largest absolute time value.
Returns (scale, unit_label) such that plotted values = t * scale.
"""
if max_abs_t >= 1.0 or max_abs_t == 0.0:
return 1.0, "s"
if max_abs_t >= 1e-3:
return 1e3, "ms"
if max_abs_t >= 1e-6:
return 1e6, "µs"
return 1e9, "ns"
def _read_csv(path: str) -> tuple[np.ndarray, list[np.ndarray], list[str]]:
"""Return (time_array, [signal_array, ...], [column_header, ...]).
Accepts any CSV whose first column is time and remaining columns are values.
"""
with open(path, newline="") as f:
reader = csv.reader(f)
header = next(reader)
rows = [row for row in reader if row]
if len(header) < 2 or not rows:
raise ValueError("no data columns")
arr = np.array([[float(x) for x in row] for row in rows])
t = arr[:, 0]
signals = [arr[:, i] for i in range(1, arr.shape[1])]
return t, signals, header[1:]
if __name__ == "__main__":
App().mainloop()