Python读取LTspice plot exp

2024-10-16 20:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python和matplotlib来绘制LTspice中的一些数据,我正在寻找一种解决方案来将从LTspice导出的绘图数据导入Python。在

我发现使用Pandas无法做到这一点,因为数据格式如下:

5.00000000000000e+006\t(2.84545891331278e+001dB,8.85405282381414e+001°)

有没有可能用Pandas导入(例如用自己的方言),或者有人知道一个简单的解决方法(比如逐行读取文件并提取值)?在

更糟糕的是,当导出多个步骤的绘图时,数据由以下行分隔:

^{pr2}$

在Java中,我可能使用了一个Scanner对象来读取数据。在Python中是否有类似的函数,或者甚至有更简单的方法将绘图数据导入Python?在


Tags: 文件数据方法绘图pandasmatplotlib绘制步骤
2条回答

我为LTSpice模拟输出文件编写了一个Python阅读器,您可以在这里找到:LTSPy。这里还有一些关于如何使用阅读器的示例文件:exltspy.zip。希望有用。(我提前为我草率的编码实践道歉)。在

我不熟悉从LTspice导出的打印数据,所以我假设您提供的示例行的格式在任何时候都是有效的。在

查看pandas-0.18文档(here)的IO工具部分,我没有看到任何现成的解析器实用程序可用于您的数据格式。首先想到的是在填充pandas数据帧之前自己进行解析和准备。在

我假设你的问题的关键部分是解析数据文件,我已经有一段时间没有玩pandas和matplotlib了,所以应该会出现与这些相关的错误。在

示例

下面是一个快速的&dirtypython3脚本,用于将数据解析到字典列表中,用它构建pandas数据帧,并使用dataframe的plot方法绘制它。我试图解释评论中的步骤:

# ltspice.py
""" Use it as: 
    > python3 ltspice.py /path/to/datafile """

import pandas
import sys

data_header = "Time Gain Degree".split()

# Valid line example:
# 5.00000000000000e+006\t(2.84545891331278e+001dB,8.85405282381414e+001°) 

def parse_line(linestr):
    # ValueError and IndexError exceptions are used to mark the failure of
    # the parse.
    try:
        # First we split at the '\t' character. This will raise ValueError if
        # there is no \t character or there is more than 1 \t
        timestr, rest = linestr.split('\t')

        # Then we find the indexes of the '(' and ')' in the rest string.
        parenst, parenend = (rest.find('(')+1,  rest.find(')'))
        if (parenst == -1) or (parenend == -1):
            # find() method returns -1 if nothing is found, I raise ValueError
            # to mark it as a parsing failure
            raise ValueError

        # rest[parenst:parenend] returns the string inside parens. split method
        # splits the string into words separated by the given character (i.e.
        # ',')
        powstr, degstr = rest[parenst:parenend].split(',')

        # converting strings into floats. Replacing units as necessary.
        time = float(timestr)
        power = float(powstr.replace('dB', ''))

        # this will fail with python 2.x
        deg = float(degstr.replace('°', ''))

        # You can use dict() instead of tuple()
        return tuple(zip(data_header, (time, power, deg)))

    except (ValueError,IndexError) as e:
        return None


def fileparser(fname):
    """ A generator function to return a parsed line on each iteration """
    with open(fname, mode='r') as fin:
        for line in fin:
            res = parse_line(line)
            if res is not None:
                yield res

def create_dataframe(fname):
    p = fileparser(fname)
    # rec is a tuple of 2-tuples that can be used to directly build a python
    # dictionary
    recs = [dict(rec) for rec in p]
    return pandas.DataFrame.from_records(recs)

if __name__ == '__main__':
    data_fname = sys.argv[1]
    df = create_dataframe(data_fname)

    ax = df.plot(x='Time', y='Gain')
    fig = ax.get_figure()
    fig.savefig('df.png')

您可以将此代码复制到文本编辑器,并将其另存为ltspice.py,然后从终端使用python3 ltspice.py yourdata.dat运行它。在

注意,parse_line函数实际上以('key',value)的形式返回一个由2个元组组成的元组,其中'key'代表列名。然后使用这个值在create_dataframe函数中构建字典列表。在

额外的

我写了另一个脚本来测试这种行为:

^{pr2}$

相关问题 更多 >