Repository navigation
Expand file tree
/
Copy pathPlotting_for_1st_code.py
More file actions
269 lines (227 loc) · 11.5 KB
/
Copy pathPlotting_for_1st_code.py
File metadata and controls
269 lines (227 loc) · 11.5 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
"""
plot_presentation.py
====================
Generates a publication-quality figure for scientific papers showing
SFRA (Sweep Frequency Response Analysis) phase unwrapping results.
Figure content:
6 subplots (a–f), each showing one transformer measurement:
• Blue solid line — original wrapped phase ±180° (Col E)
• Red dashed line — corrected unwrapped phase (Col F)
• Red shaded region — frequency range where correction was applied
• Red dot — exact phase-jump correction point
Output files:
phase_unwrapping_publication.png — 300 DPI raster (slides / Word)
phase_unwrapping_publication.pdf — vector (LaTeX / journals)
Usage:
python plot_presentation.py
Requirements:
matplotlib, openpyxl (auto-installed if missing)
"""
# ── Auto-install missing packages ────────────────────────────────────────────
import subprocess, sys
def install_if_missing(package):
try:
__import__(package)
except ImportError:
print(f"Installing {package}...")
subprocess.check_call([sys.executable, "-m", "pip", "install", package],
stdout=subprocess.DEVNULL)
install_if_missing("matplotlib")
install_if_missing("openpyxl")
# ─────────────────────────────────────────────────────────────────────────────
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.lines import Line2D
from openpyxl import load_workbook
# ── File paths ────────────────────────────────────────────────────────────────
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
INPUT_FILE = os.path.join(SCRIPT_DIR, "Referenzmessungen_NEU_unwrapped.xlsx")
OUTPUT_PNG = os.path.join(SCRIPT_DIR, "phase_unwrapping.png")
OUTPUT_PDF = os.path.join(SCRIPT_DIR, "phase_unwrapping.pdf")
# ── Excel structure ───────────────────────────────────────────────────────────
SHEETS_TO_SKIP = 3 # first 3 sheets are metadata, not measurements
# 6 representative measurements to display.
# Format: (sheet name, block name in Col B, subplot title)
PICKS = [
("SFRA-Prüfung (manuell)", "III_U1U2_0_open circuit", "Open Circuit — III U1U2, tap 0"),
("SFRA-Prüfung (manuell)", "Y_W1N_0_open circuit", "Open Circuit — Y W1N, tap 0"),
("Dreieck_open circuit", "D_U1U2_0", "Dreieck Open Circuit — D U1U2, tap 0"),
("Dreieck_short circuit", "D_U1U2_0", "Dreieck Short Circuit — D U1U2, tap 0"),
("Erreger Einzelphase", "III_F1F2_0", "Excitation Single-Phase — F1F2, tap 0"),
("Erreger Sternschaltung", "Y_F1F2_0", "Excitation Star Config. — Y F1F2, tap 0"),
]
# ── Colour palette (IEEE / Nature compatible) ─────────────────────────────────
C_ORIG = "#1A56A0" # deep blue — original phase
C_CORR = "#C0392B" # crimson — corrected phase
C_SHADE = "#F5B7B1" # light red — correction region fill
C_VLINE = "#922B21" # dark red — jump marker
C_GRID = "#CCCCCC"
C_TITLE = "#1A1A2E"
C_LABEL = "#2C3E50"
C_TICK = "#555555"
# ── Global matplotlib style (serif / Times, journal-ready) ───────────────────
plt.rcParams.update({
"font.family": "serif",
"font.serif": ["Times New Roman", "DejaVu Serif", "serif"],
"mathtext.fontset": "stix",
"axes.linewidth": 0.8,
"xtick.direction": "in",
"ytick.direction": "in",
"xtick.major.size": 4,
"ytick.major.size": 4,
"xtick.minor.size": 2,
"ytick.minor.size": 2,
"xtick.minor.visible": True,
"ytick.minor.visible": True,
"figure.dpi": 300,
"savefig.dpi": 300,
})
# ── Data loading ──────────────────────────────────────────────────────────────
def load_all_blocks(wb):
"""
Read every measurement sheet (index >= SHEETS_TO_SKIP) and collect
phase data grouped by block name (Col B).
Returns:
dict {(sheet_name, block_name): {"e": [floats], "f": [float|None]}}
"e" = original phase (Col E)
"f" = corrected phase (Col F), None where not yet corrected
"""
all_blocks = {}
for i, sheet_name in enumerate(wb.sheetnames):
if i < SHEETS_TO_SKIP:
continue
ws = wb.worksheets[i]
blocks = {}
for row in ws.iter_rows(values_only=True):
b, e, f = row[1], row[4], row[5]
if isinstance(b, str) and isinstance(e, (int, float)):
if b not in blocks:
blocks[b] = {"e": [], "f": []}
blocks[b]["e"].append(float(e))
blocks[b]["f"].append(float(f) if isinstance(f, (int, float)) else None)
for name, data in blocks.items():
all_blocks[(sheet_name, name)] = data
return all_blocks
# ── Subplot drawing ───────────────────────────────────────────────────────────
def draw_subplot(ax, e_vals, f_vals, title, panel_letter):
"""
Draw one measurement panel.
Args:
ax : matplotlib Axes
e_vals : list of floats — original phase (Col E)
f_vals : list of float|None — corrected phase (Col F)
title : str — subplot title
panel_letter : str — panel label, e.g. "a", "b", ...
"""
x = list(range(len(e_vals)))
full_fixed = [f if f is not None else e for e, f in zip(e_vals, f_vals)]
# Index where the correction starts (first non-None in Col F)
jump_start = next((i for i, f in enumerate(f_vals) if f is not None), None)
ax.set_facecolor("white")
# Shaded region where phase correction was applied
if jump_start is not None:
ax.axvspan(jump_start, len(x) - 1,
alpha=0.15, color=C_SHADE, linewidth=0, zorder=1)
# Original phase — solid blue
ax.plot(x, e_vals,
color=C_ORIG, linewidth=1.1, alpha=1.0, zorder=3)
# Corrected phase and markers
if jump_start is not None:
ax.plot(x[jump_start:], full_fixed[jump_start:],
color=C_CORR, linewidth=1.3, linestyle="--", zorder=4)
ax.axvline(x=jump_start, color=C_VLINE,
linewidth=0.9, linestyle=":", alpha=0.85, zorder=2)
ax.scatter([jump_start], [full_fixed[jump_start]],
color=C_CORR, s=28, zorder=6,
edgecolors="white", linewidths=0.5)
# Panel label (a), (b), ...
ax.text(0.03, 0.96, f"({panel_letter})",
transform=ax.transAxes, fontsize=10, fontweight="bold",
va="top", ha="left", color=C_TITLE,
bbox=dict(facecolor="white", edgecolor="none",
alpha=0.75, pad=1.5))
ax.set_title(title, fontsize=8.5, color=C_TITLE, pad=5, fontstyle="italic")
ax.set_xlabel("Measurement Point Index", fontsize=8, color=C_LABEL, labelpad=3)
ax.set_ylabel("Phase (°)", fontsize=8, color=C_LABEL, labelpad=3)
ax.tick_params(labelsize=7.5, colors=C_TICK, which="both")
ax.grid(True, alpha=0.35, linestyle="--",
linewidth=0.5, color=C_GRID, zorder=0)
for spine in ax.spines.values():
spine.set_edgecolor("#AAAAAA")
spine.set_linewidth(0.7)
# ── Main ──────────────────────────────────────────────────────────────────────
def main():
if not os.path.exists(INPUT_FILE):
print(f"\nERROR: Input file not found:\n {INPUT_FILE}")
print("Place 'Referenzmessungen_NEU_unwrapped.xlsx' in the same folder.")
return
print(f"Loading: {INPUT_FILE}")
wb = load_workbook(INPUT_FILE, read_only=True)
all_blocks = load_all_blocks(wb)
print(f"Blocks loaded: {len(all_blocks)}")
# ── Figure — IEEE two-column width (7.16 in = 182 mm) ────────────────────
fig = plt.figure(figsize=(7.16, 8.0))
fig.patch.set_facecolor("white")
gs = gridspec.GridSpec(
3, 2, figure=fig,
hspace=0.52, wspace=0.32,
top=0.91, bottom=0.10,
left=0.09, right=0.97,
)
# Figure title and subtitle
fig.text(
0.5, 0.965,
"Phase Unwrapping Analysis of SFRA Transformer Measurements",
ha="center", va="top",
fontsize=10, fontweight="bold", color=C_TITLE,
)
fig.text(
0.5, 0.945,
"Comparison of original wrapped phase (Col E) "
"and unwrapped corrected phase (Col F)",
ha="center", va="top",
fontsize=7.5, color="#555555", fontstyle="italic",
)
# Draw each panel
panel_letters = list("abcdef")
for idx, (sheet, block, label) in enumerate(PICKS):
ax = fig.add_subplot(gs[idx // 2, idx % 2])
data = all_blocks.get((sheet, block))
if data is None:
ax.text(0.5, 0.5, f"Block not found:\n'{block}'",
ha="center", va="center", transform=ax.transAxes,
fontsize=8, color="gray")
ax.set_title(label, fontsize=8.5)
print(f" [WARN] Block not found: '{block}' in '{sheet}'")
continue
draw_subplot(ax, data["e"], data["f"], label, panel_letters[idx])
# ── Shared legend ─────────────────────────────────────────────────────────
legend_handles = [
Line2D([0], [0], color=C_ORIG, linewidth=1.5,
label="Original phase — Col E (wrapped, ±180°)"),
Line2D([0], [0], color=C_CORR, linewidth=1.5, linestyle="--",
label="Corrected phase — Col F (unwrapped)"),
Line2D([0], [0], color=C_VLINE, linewidth=1.0, linestyle=":",
label="Phase-jump correction point"),
plt.Rectangle((0, 0), 1, 1, fc=C_SHADE, ec="none", alpha=0.6,
label="Phase correction region"),
]
fig.legend(
handles=legend_handles,
loc="lower center", ncol=2,
fontsize=7.5, framealpha=1.0, edgecolor="#AAAAAA",
bbox_to_anchor=(0.5, 0.005),
handlelength=2.2, handletextpad=0.5,
columnspacing=1.2, borderpad=0.7,
)
# ── Save ──────────────────────────────────────────────────────────────────
fig.savefig(OUTPUT_PNG, dpi=300, bbox_inches="tight", facecolor="white")
fig.savefig(OUTPUT_PDF, bbox_inches="tight", facecolor="white")
plt.close()
print(f"\nSaved (PNG, 300 DPI): {OUTPUT_PNG}")
print(f"Saved (PDF, vector) : {OUTPUT_PDF}")
if __name__ == "__main__":
main()