【问题标题】:Continuously reading and plotting a CSV file using Python使用 Python 连续读取和绘制 CSV 文件
【发布时间】:2021-02-10 16:19:54
【问题描述】:

这是我第一次在这里问问题,所以我希望我以“正确的方式”问以下问题。如果没有,请告诉我,我会提供更多信息。

我正在使用一个 Python 脚本来读取 4000Hz 的串行数据并将其写入 CSV 文件。

CSV文件的结构如下:(本例显示文件的开头)

Time of mSure Calibration: 24.10.2020 20:03:14.462654
Calibration Data - AICC: 833.95; AICERT: 2109; AVCC: 0.00; AVCERT: 0 
Sampling Frequency: 4000Hz
timestamp,instantaneousCurrentValue,instantaneousVoltageValue,activePowerValueCalculated,activePowerValue
24.10.2020 20:03:16.495828,-0.00032,7e-05,-0.0,0.0
24.10.2020 20:03:16.496078,0.001424,7e-05,0.0,0.0
24.10.2020 20:03:16.496328,9.6e-05,7e-05,0.0,0.0
24.10.2020 20:03:16.496578,-0.000912,7e-05,-0.0,0.0

只要读取串行数据的脚本处于活动状态,数据就会写入此 CSV。因此,有时这可能会成为一个巨大的文件。 (数据以 8000 行的块写入 = 每两秒)

这是我的问题:我想实时绘制这些数据。例如,每次将数据写入 CSV 文件时更新绘图。绘图应从另一个脚本完成,而不是读取和写入串行数据的脚本。

工作原理: 1. 创建 CSV 文件。 2. 使用另一个脚本绘制完成的 CSV 文件 - 实际上非常好 :-)

我有这个绘图脚本:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""Data Computation Software for TeensyDAQ - Reads and computes CSV-File"""

# region imports
import getopt
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pathlib
from scipy.signal import argrelextrema
import sys
# endregion

# region globals
inputfile = ''
outputfile = ''
# endregion

# region functions
def main(argv):
    """Main application"""

    # region define variables
    global inputfile
    global outputfile
    inputfile = str(pathlib.Path(__file__).parent.absolute(
    ).resolve())+"\\noFilenameProvided.csv"
    outputfile = str(pathlib.Path(__file__).parent.absolute(
    ).resolve())+"\\noFilenameProvidedOut.csv"
    # endregion

    # region read system arguments
    try:
        opts, args = getopt.getopt(
            argv, "hi:o:", ["infile=", "outfile="])
    except getopt.GetoptError:
        print('dataComputation.py -i <inputfile> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('dataComputation.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--infile"):
            inputfile = str(pathlib.Path(
                __file__).parent.absolute().resolve())+"\\"+arg
        elif opt in ("-o", "--outfile"):
            outputfile = str(pathlib.Path(
                __file__).parent.absolute().resolve())+"\\"+arg
    # endregion

    # region read csv
    colTypes = {'timestamp': 'str',
                'instantaneousCurrent': 'float',
                'instantaneousVoltage': 'float',
                'activePowerCalculated': 'float',
                'activePower': 'float',
                'apparentPower': 'float',
                'fundReactivePower': 'float'
                }
    cols = list(colTypes.keys())
    df = pd.read_csv(inputfile, usecols=cols, dtype=colTypes,
                     parse_dates=True, dayfirst=True, skiprows=3)
    df['timestamp'] = pd.to_datetime(
        df['timestamp'], utc=True, format='%d.%m.%Y %H:%M:%S.%f')
    df.insert(loc=0, column='tick', value=np.arange(len(df)))
    # endregion

    # region plot data
    fig, axes = plt.subplots(nrows=6, ncols=1,  sharex=True, figsize=(16,8))
    fig.canvas.set_window_title(df['timestamp'].iloc[0]) 
    fig.align_ylabels(axes[0:5])

    df['instantaneousCurrent'].plot(ax=axes[0], color='red'); axes[0].set_title('Momentanstrom'); axes[0].set_ylabel('A',rotation=0)
    df['instantaneousVoltage'].plot(ax=axes[1], color='blue'); axes[1].set_title('Momentanspannung'); axes[1].set_ylabel('V',rotation=0)
    df['activePowerCalculated'].plot(ax=axes[2], color='green'); axes[2].set_title('Momentanleistung ungefiltert'); axes[2].set_ylabel('W',rotation=0)
    df['activePower'].plot(ax=axes[3], color='brown'); axes[3].set_title('Momentanleistung'); axes[3].set_ylabel('W',rotation=0)
    df['apparentPower'].plot(ax=axes[4], color='brown'); axes[4].set_title('Scheinleistung'); axes[4].set_ylabel('VA',rotation=0)
    df['fundReactivePower'].plot(ax=axes[5], color='brown'); axes[5].set_title('Blindleitsung'); axes[5].set_ylabel('VAr',rotation=0); axes[5].set_xlabel('microseconds since start')
    
    plt.tight_layout()    
    plt.show()
    # endregion

# endregion


if __name__ == "__main__":
    main(sys.argv[1:])

我对如何解决我的问题的想法:

  1. 修改我的绘图脚本以连续读取 CSV 文件并使用 matplotlib 的动画功能进行绘图。
  2. 使用某种流功能读取流中的 CSV。我已阅读有关 streamz 库的信息,但不知道如何使用它。

非常感谢任何帮助!

亲切的问候, 萨沙

编辑 31.10.2020:

由于我不知道平均持续时间,等待帮助的时间,我尝试添加更多输入,这可能会导致有用的 cmets。

我编写这个脚本是为了将数据连续写入一个 CSV 文件,它可以模拟我的真实脚本,而不需要外部硬件:(使用计时器生成随机数据并进行 CSV 格式化。每次有 50 个新行时,数据写入 CSV 文件)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
from random import randrange
import time
import threading
import pathlib
from datetime import datetime, timedelta

datarows = list()
datarowsToWrite = list()
outputfile = str(pathlib.Path(__file__).parent.absolute().resolve()) + "\\noFilenameProvided.csv"
sampleCount = 0

def startBatchWriteThread():
    global outputfile
    global datarows
    global datarowsToWrite
    datarowsToWrite.clear()
    datarowsToWrite = datarows[:]
    datarows.clear()
    thread = threading.Thread(target=batchWriteData,args=(outputfile, datarowsToWrite))
    thread.start()

def batchWriteData(file, data):
    print("Items to write: " + str(len(data)))
    with open(file, 'a+') as f:
        for item in data:
            f.write("%s\n" % item)

def generateDatarows():
    global sampleCount
    timer1 = threading.Timer(0.001, generateDatarows)
    timer1.daemon = True
    timer1.start()
    datarow = datetime.now().strftime("%d.%m.%Y %H:%M:%S.%f")[:] + "," + str(randrange(10)) + "," + str(randrange(10)) + "," + str(randrange(10)) + "," + str(randrange(10)) + "," + str(randrange(10)) + "," + str(randrange(10))
    datarows.append(datarow)
    sampleCount += 1

try:
    datarows.append("row 1")
    datarows.append("row 2")
    datarows.append("row 3")
    datarows.append("timestamp,instantaneousCurrent,instantaneousVoltage,activePowerCalculated,activePower,apparentPower,fundReactivePower")
    startBatchWriteThread()
    generateDatarows()
    while True:
        if len(datarows) == 50:
            startBatchWriteThread()
except KeyboardInterrupt:
    print("Shutting down, writing the rest of the buffer.")
    batchWriteData(outputfile, datarows)
    print("Done, writing " + outputfile)

我最初帖子中的脚本可以绘制 CSV 文件中的数据。

我需要在数据写入 CSV 文件时绘制数据,以便或多或少地实时查看数据。

希望这能让我的问题更容易理解。

【问题讨论】:

    标签: python pandas csv matplotlib


    【解决方案1】:

    对于 Google 员工:我找不到实现问题中描述的目标的方法。

    但是,如果您尝试绘制实时数据,并通过串行通信(在我的情况下为 4000Hz)提供高速,我建议您将应用程序设计为具有多个进程的单个程序。

    在我的特殊情况下的问题是,当我尝试在同一个线程/任务/进程/其他任何东西中同时绘制和计算传入数据时,我的串行接收速率下降到 100Hz 而不是 4kHz。在进程之间使用 quick_queue 模块进行多处理和传递数据的解决方案我可以解决问题。

    我最终得到了一个程序,它通过 4kHz 的串行通信从 Teensy 接收数据,这些传入的数据被缓冲到 4000 个样本的块中,然后数据被推送到绘图过程,此外,块被写入到单独线程中的 CSV 文件。

    最好, S

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 2015-07-21
      • 2012-03-17
      • 2015-01-30
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 2011-08-12
      • 2016-01-18
      相关资源
      最近更新 更多