import numpy as np
def load_data(filename):
freqs = []
values = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or "freq" in line.lower(): # Skip empty lines and headers
continue
if ";" in line:
parts = line.split(";")
if len(parts) == 2:
freq_str = parts[0].strip().replace(",", ".")
val_str = parts[1].strip().replace(",", ".")
try:
freqs.append(float(freq_str))
values.append(float(val_str))
except ValueError:
continue # skip bad data
return np.array(freqs), np.array(values)
# Load data from either .csv or .txt
imp_freq, imp_vals = load_data("impedance.csv") # or "impedance.txt"
pha_freq, pha_vals = load_data("phase.csv") # or "phase.txt"
# Interpolate phase to match impedance frequencies
interp_phase_vals = np.interp(imp_freq, pha_freq, pha_vals)
# Merge all into one array
merged_data = np.column_stack((imp_freq, imp_vals, interp_phase_vals))
# Write to neatly aligned text file with 5 decimals
col_width = 18
with open("merged_output.txt", "w", encoding="utf-8") as f:
f.write(f"{'freq (Hz)':<{col_width}}{'imp (ohm)':<{col_width}}{'phase (deg)':<{col_width}}\n")
for row in merged_data:
f.write("{:<18.5f}{:<18.5f}{:<18.5f}\n".format(row[0], row[1], row[2]))
print("✅ Merged output saved as 'merged_output.txt' with 5 decimal places.")