-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_results.py
More file actions
426 lines (339 loc) · 13.4 KB
/
plot_results.py
File metadata and controls
426 lines (339 loc) · 13.4 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env python3
"""
plot_results.py — Interaktywny kreator wykresów z plików wyników symulacji.
Użycie:
python plot_results.py
Przepływ:
1. Wybierz plik wyników z katalogu results/
2. Wybierz kolumnę osi X (domyślnie: x_m → wyświetlana w mm)
3. Wybierz kolumny osi Y (jedna lub kilka, np. "7,8,9" lub "7-9")
4. Wykres wyświetla się w oknie
5. Po zamknięciu okna: opcja zapisu → opcja kolejnego wykresu
"""
import os
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
RESULTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'results')
# ---------------------------------------------------------------------------
# Kolumny [m] do automatycznej konwersji → mm na wykresie
# (tylko jednostkowe długości, nie powierzchnie _m2 ani prędkości _m_s)
# ---------------------------------------------------------------------------
_MM_COLUMNS = {'x_m', 'r_m'}
# ---------------------------------------------------------------------------
# Czytelne etykiety osi dla każdej kolumny
# ---------------------------------------------------------------------------
_LABELS = {
'x_m': 'x [mm]',
'r_m': 'r [mm]',
'A_m2': 'A [m²]',
'gamma': 'Wykładnik adiabaty γ [-]',
'Cpcg_J_kgK': 'Cp gazu [J/(kg·K)]',
'Prcg_gas': 'Pr gazu [-]',
'molar_mass_kg_mol':'Masa molarna gazu [kg/mol]',
'Rs_J_kgK': 'Stała gazowa właściwa Rs [J/(kg·K)]',
'M': 'Liczba Macha M [-]',
'N_M2': 'N = M² [-]',
'P_Pa': 'Ciśnienie gazu p [Pa]',
'T_K': 'Temperatura gazu T [K]',
'T_aw_K': 'T adiabatyczna ścianki T_aw [K]',
'eta_Pa_s': 'Lepkość dynamiczna η [Pa·s]',
}
# ---------------------------------------------------------------------------
# Grupy kolumn do czytelnego wyświetlania w menu
# ---------------------------------------------------------------------------
_GROUPS = [
('Geometria', ['x_m', 'r_m', 'A_m2']),
('Właściwości gazu', ['gamma', 'Cpcg_J_kgK', 'Prcg_gas',
'molar_mass_kg_mol', 'Rs_J_kgK']),
('Przepływ gazowy', ['M', 'N_M2', 'P_Pa', 'T_K', 'T_aw_K']),
('Inne', ['eta_Pa_s']),
]
# ===========================================================================
# Pomocnicze
# ===========================================================================
def _label(col):
"""Zwróć czytelną etykietę osi dla kolumny."""
return _LABELS.get(col, col.replace('_', ' '))
def _get_values(df, col):
"""Zwróć wartości kolumny z konwersją m → mm tam gdzie potrzeba."""
vals = df[col].values.astype(float)
if col in _MM_COLUMNS:
vals = vals * 1000.0
return vals
# ===========================================================================
# Wczytywanie pliku
# ===========================================================================
def _read_metadata(filepath):
"""Parsuj blok metadanych ('# klucz: wartość') z pliku CSV."""
meta = {}
with open(filepath, 'r', encoding='utf-8') as fh:
for line in fh:
if not line.startswith('#'):
break
line = line[1:].strip()
if ':' in line:
key, _, val = line.partition(':')
meta[key.strip()] = val.strip()
return meta
def _list_result_files():
"""Zwróć posortowaną listę plików CSV z katalogu results/."""
if not os.path.isdir(RESULTS_DIR):
return []
return sorted(
os.path.join(RESULTS_DIR, f)
for f in os.listdir(RESULTS_DIR)
if f.endswith('.csv')
)
# ===========================================================================
# Interaktywne wybory
# ===========================================================================
def select_result_file():
"""Wyświetl listę plików i pozwól użytkownikowi wybrać jeden."""
files = _list_result_files()
if not files:
print(f"\n Brak plików wyników w: {RESULTS_DIR}")
print(" Uruchom najpierw symulację (python main.py).")
return None
print("\n" + "=" * 65)
print(" WYBÓR PLIKU WYNIKÓW")
print("=" * 65)
for i, fp in enumerate(files, 1):
meta = _read_metadata(fp)
fname = os.path.basename(fp)
date = meta.get('date', '?')
conv = meta.get('converged', '?')
iters = meta.get('iterations', '?')
params = meta.get('params_name', '?')
print(f" [{i:2d}] {fname}")
print(f" parametry: {params} | data: {date}")
print(f" zbieżność: {conv} | iteracje: {iters}")
print("-" * 65)
while True:
try:
raw = input(f"Wybierz plik (1–{len(files)}): ").strip()
idx = int(raw) - 1
if 0 <= idx < len(files):
return files[idx]
print(f" Podaj liczbę od 1 do {len(files)}.")
except ValueError:
print(" Podaj numer pliku.")
except (EOFError, KeyboardInterrupt):
return None
def _build_index_map(df):
"""
Przypisz numery do kolumn zgodnie z grupami.
Zwraca dict {numer: nazwa_kolumny}.
"""
cols_available = set(df.columns)
index_map = {}
idx = 1
for _, group_cols in _GROUPS:
for col in group_cols:
if col in cols_available:
index_map[idx] = col
idx += 1
# Kolumny spoza znanych grup (przyszłościowe rozszerzenia)
assigned = {c for _, gc in _GROUPS for c in gc}
for col in df.columns:
if col not in assigned:
index_map[idx] = col
idx += 1
return index_map
def display_columns(df, index_map):
"""Wyświetl dostępne kolumny w pogrupowanej tabeli."""
cols_available = set(df.columns)
reverse = {v: k for k, v in index_map.items()}
print()
print(" Dostępne parametry:")
print(" " + "-" * 61)
for group_name, group_cols in _GROUPS:
present = [c for c in group_cols if c in cols_available]
if not present:
continue
print(f" {group_name}:")
for col in present:
num = reverse[col]
note = ' (→ mm)' if col in _MM_COLUMNS else ''
print(f" [{num:2d}] {col:22s} {_label(col)}{note}")
# Nieprzypisane
assigned = {c for _, gc in _GROUPS for c in gc}
extra = [c for c in df.columns if c not in assigned]
if extra:
print(" Inne:")
for col in extra:
num = reverse[col]
print(f" [{num:2d}] {col:22s} {_label(col)}")
print(" " + "-" * 61)
def _parse_selection(raw, index_map, multi=True):
"""
Parsuj ciąg numerów: "7,8,9" lub "7-9" lub "7, 9-12, 15".
Zwraca listę nazw kolumn w kolejności wyboru.
"""
selected = []
for token in raw.replace(' ', '').split(','):
if '-' in token and multi:
parts = token.split('-', 1)
try:
a, b = int(parts[0]), int(parts[1])
for n in range(a, b + 1):
if n in index_map and index_map[n] not in selected:
selected.append(index_map[n])
except ValueError:
pass
else:
try:
n = int(token)
if n in index_map and index_map[n] not in selected:
selected.append(index_map[n])
except ValueError:
pass
return selected
def select_x_axis(df, index_map):
"""
Wybór kolumny osi X.
Domyślnie: x_m (wyświetlana w mm).
"""
default_col = 'x_m' if 'x_m' in df.columns else list(index_map.values())[0]
default_num = next((k for k, v in index_map.items() if v == default_col), 1)
print(f"\n Oś X — wybierz numer (domyślnie [{default_num}] = {_label(default_col)}):")
try:
raw = input(f" X [{default_num}]: ").strip()
except (EOFError, KeyboardInterrupt):
return default_col
if not raw:
return default_col
result = _parse_selection(raw, index_map, multi=False)
if result:
return result[0]
print(f" Nieprawidłowy wybór — użyto domyślnego: {default_col}")
return default_col
def select_y_axes(df, index_map):
"""
Wybór kolumn osi Y (jedna lub więcej).
Wpisz numery oddzielone przecinkami lub zakresy, np. "7,8,9" / "7-9".
"""
print(" Oś Y — wybierz numery kolumn (przecinki lub zakresy, np. 7,8 lub 7-9):")
while True:
try:
raw = input(" Y: ").strip()
except (EOFError, KeyboardInterrupt):
return []
if not raw:
print(" Podaj co najmniej jeden numer kolumny.")
continue
result = _parse_selection(raw, index_map, multi=True)
if result:
return result
print(" Nie rozpoznano żadnej kolumny. Spróbuj ponownie.")
# ===========================================================================
# Tworzenie wykresu
# ===========================================================================
def make_chart(df, x_col, y_cols, meta):
"""
Wygeneruj wykres matplotlib i zwróć obiekt fig.
Jeśli wybrano tylko jedną serię Y, etykieta osi Y jest pełna.
Jeśli wybrano wiele serii, etykieta osi Y to 'Wartość' i używana jest legenda.
"""
x_vals = _get_values(df, x_col)
x_label = _label(x_col)
fig, ax = plt.subplots(figsize=(11, 6))
for col in y_cols:
y_vals = _get_values(df, col)
ax.plot(x_vals, y_vals, linewidth=1.8, label=_label(col))
ax.set_xlabel(x_label, fontsize=12)
if len(y_cols) == 1:
ax.set_ylabel(_label(y_cols[0]), fontsize=12)
else:
ax.set_ylabel('Wartość', fontsize=12)
ax.legend(fontsize=10, loc='best')
# Tytuł z metadanych pliku
params_name = meta.get('params_name', '')
date = meta.get('date', '?')
conv = meta.get('converged', '?')
iters = meta.get('iterations', '?')
title = f"OpenEngine — {params_name}"
subtitle = f"data analizy: {date} | zbieżność: {conv} | iteracje: {iters}"
ax.set_title(f"{title}\n{subtitle}", fontsize=11)
ax.grid(True, alpha=0.35)
fig.tight_layout()
return fig
# ===========================================================================
# Zapis wykresu
# ===========================================================================
def ask_save_chart(fig, params_name):
"""Zapytaj użytkownika czy zapisać wykres i w jakim formacie."""
try:
ans = input("\n Zapisać wykres do pliku? (t/n, domyślnie: n): ").strip().lower()
except (EOFError, KeyboardInterrupt):
return
if ans != 't':
return
default_name = f"{params_name}_plot"
try:
name = input(f" Nazwa pliku bez rozszerzenia (domyślnie '{default_name}'): ").strip()
except (EOFError, KeyboardInterrupt):
name = ''
if not name:
name = default_name
safe_name = "".join(c for c in name if c.isalnum() or c in ('_', '-', '.'))
if not safe_name:
safe_name = default_name
print(" Format zapisu: [1] PNG [2] PDF [3] SVG")
try:
fmt = input(" Format [1]: ").strip()
except (EOFError, KeyboardInterrupt):
fmt = '1'
ext = {' ': '.png', '': '.png', '1': '.png', '2': '.pdf', '3': '.svg'}.get(fmt, '.png')
os.makedirs(RESULTS_DIR, exist_ok=True)
out_path = os.path.join(RESULTS_DIR, safe_name + ext)
fig.savefig(out_path, dpi=150, bbox_inches='tight')
print(f" Zapisano: {out_path}")
# ===========================================================================
# Główna pętla programu
# ===========================================================================
def main():
print("\n" + "=" * 65)
print(" OPENENGINE — KREATOR WYKRESÓW")
print("=" * 65)
# --- Wybór pliku ---
filepath = select_result_file()
if filepath is None:
print("\n Anulowano.")
return
df, meta = pd.read_csv(filepath, comment='#'), _read_metadata(filepath)
# (ponowne wczytanie przez pandas — upewnia się że typy są numeryczne)
df = pd.read_csv(filepath, comment='#')
index_map = _build_index_map(df)
fname = os.path.basename(filepath)
print(f"\n Plik: {fname}")
print(f" Parametry: {meta.get('params_name', '?')}")
print(f" Data: {meta.get('date', '?')}")
print(f" Siatka: {len(df)} punktów | Kolumny: {len(df.columns)}")
params_name = meta.get('params_name', 'results')
# --- Pętla wykresów ---
while True:
display_columns(df, index_map)
x_col = select_x_axis(df, index_map)
y_cols = select_y_axes(df, index_map)
if not y_cols:
print(" Brak wybranych kolumn Y — pomijam.")
else:
print(f"\n Rysuję: X = {_label(x_col)}")
print(f" Y = {', '.join(_label(c) for c in y_cols)}")
fig = make_chart(df, x_col, y_cols, meta)
plt.show(block=True) # czeka na zamknięcie okna
ask_save_chart(fig, params_name)
plt.close(fig)
# --- Kolejny wykres? ---
print()
try:
again = input(" Zrobić kolejny wykres? (t/n, domyślnie: n): ").strip().lower()
except (EOFError, KeyboardInterrupt):
again = 'n'
if again != 't':
print("\n Do widzenia!\n")
break
if __name__ == '__main__':
main()