如何从Ngspice的SVG或RAW文件导出仿真数据至Excel?
从Ngspice仿真结果提取频率-电压数据并导出至Excel
方法一:直接从Ngspice导出原始数据(推荐)
解析SVG容易因格式变动出错,优先让Ngspice直接输出仿真原始数据:
修改你的Ngspice网表,在仿真命令(比如AC扫描)后添加数据导出指令:
.ac dec 10 1Hz 1GHz ; 示例AC扫描命令,根据你的需求调整频率范围和点数 wrdata freq_voltage.dat v(out) ; 导出out节点的电压数据到freq_voltage.dat执行仿真后,
freq_voltage.dat会包含两列:第一列是频率,第二列是对应电压值。用Python读取并处理数据,采样1000组后导出到Excel:
import pandas as pd import numpy as np # 读取dat文件,空格分隔,自定义列名 df = pd.read_csv('freq_voltage.dat', sep=r'\s+', header=None, names=['Frequency', 'Voltage']) # 均匀采样1000组数据 sample_indices = np.linspace(0, len(df)-1, 1000, dtype=int) sampled_df = df.iloc[sample_indices] # 导出到Excel sampled_df.to_excel('freq_voltage_sampled.xlsx', index=False)
方法二:解析已生成的SVG文件
如果只能通过SVG提取数据,可按以下步骤处理:
安装依赖库:
pip install beautifulsoup4 pandas openpyxlPython解析SVG代码示例:
from bs4 import BeautifulSoup import pandas as pd import numpy as np # 读取SVG文件 with open('simulation_curve.svg', 'r') as f: soup = BeautifulSoup(f, 'xml') # 找到曲线数据(Ngspice生成的SVG通常用<polyline>存储坐标点,需根据实际SVG调整) polyline = soup.find('polyline') points = polyline['points'].split(' ') # 提取坐标点并转换为数值 coords = [] for point in points: if point.strip(): x, y = map(float, point.split(',')) coords.append((x, y)) # 将SVG坐标映射为实际频率和电压(需根据SVG的坐标轴刻度调整映射关系) # 示例:假设SVG x轴对应1Hz-1GHz,y轴对应0V-5V,画布宽800高600,SVG y轴向下为正 svg_x_min, svg_x_max = 0, 800 svg_y_min, svg_y_max = 0, 600 freq_min, freq_max = 1, 1e9 volt_min, volt_max = 5, 0 # 反转y轴对应实际电压方向 # 计算实际物理量 freq_list = [] volt_list = [] for x, y in coords: freq = freq_min + (x - svg_x_min) * (freq_max - freq_min) / (svg_x_max - svg_x_min) volt = volt_min + (y - svg_y_min) * (volt_max - volt_min) / (svg_y_max - svg_y_min) freq_list.append(freq) volt_list.append(volt) # 转换为DataFrame并采样1000组 df = pd.DataFrame({'Frequency': freq_list, 'Voltage': volt_list}) sample_indices = np.linspace(0, len(df)-1, 1000, dtype=int) sampled_df = df.iloc[sample_indices] # 导出到Excel sampled_df.to_excel('freq_voltage_from_svg.xlsx', index=False)
注意事项
- 方法一中,
wrdata命令可指定多个节点电压,比如wrdata data.dat v(out1) v(out2),后续Python处理时只需调整列名即可。 - 方法二中,SVG的坐标轴映射关系需要你根据实际SVG的刻度标签确认,可查看SVG中的
<text>元素找到频率和电压的刻度值,再对应到SVG的坐标位置。 - 若仿真生成的原始数据点不足1000,可在Ngspice的AC命令中增加数据点密度,比如将
dec 10改为dec 100,生成更多数据点后再采样。
内容的提问来源于stack exchange,提问作者Fo Oc
相关产品推荐
相关产品推荐

