Reading OpenFOAM time series data and sets data

Overview

I made a function to read OpenFOAM time series data and sets data (spatial distribution data output by the sample command) in Python, and simplified the plotting with matplotlib.

As a premise, the time series data of OpenFOAM is saved in a new directory every time it is restarted, but it is assumed that they are attached with the cat command to form a single file.

Python code

Function for reading time series data

def readHistory(case, positions, variables):
    import numpy as np
    
    """
    case: case name (string data)
    positions: position name (list data)
    variables: physical quantities (list data)
    """
    
    data ={}

    for position in positions:
        for variable in variables:
            key = variable+"_"+position
            value = np.genfromtxt(case+"/"+position+"/"+variable, unpack=True)
            data[key] = value
        
    return data

functions for reading sets data

Argument description

def readSets(case, file, variables):
    import numpy as np
    import pandas as pd
    import glob
    import os
    
    """
    case: case name (string data)
    file: sets data file name (string data)
    variables: physical quantities (list data)
    """

    # list of timing
    list1 = glob.glob(case + "/sets/*")
    
    variable_names = file.split("_")
    # remove ".xy" 
    variable_names[-1] = variable_names[-1].split(".")[0]
    position, variable_names[0] = variable_names[0], "x"
    #print(variable_names)
        
    data = {}
    for variable in variables:
        key = variable+"_"+position
        data[key] = pd.DataFrame()
        
        for i in list1:
            path = i+"/" + file
            df = pd.read_table(path, header = None, names = variable_names)   
            data[key] = pd.concat([data[key], df[variable]], axis=1,)
    
        list_index=[]    
        for i in list1:
            list_index.append(str(float(os.path.basename(i))))
    
        data[key].columns = list_index
        data[key] = pd.concat([df[variable_names[0]], data[key].sort_index(axis=1)], axis=1)
    
    # return dictionary of dataframe
    return data

Plot with matplotlib

Plot the data with matplotlib.

Suppose the data layout is as follows. test01 is the case name.

test01/position-A/p test01/position-A/U test01/position-B/p test01/position-B/U test01/sets/0/center_p_k.xy test01/sets/10/center_p_k.xy

p and U are time series data of position-A and B center_p_k.xy is the distribution data at time 0 and 10. is.

There are multiple cases, and it is designed assuming that you can easily create a plot with only the case name changed.

import matplotlib.pyplot as plt
%matplotlib inline

case = "test01"
history_position = ["position-A", "position-B"]
history_variables = ["p", "U"]
sets_variables = ["p", "k"]
sets_position = "center"
dataSet_test01= [readHistory(case, history_position, history_variables), 
                  readSets(case, "center_p_k.xy", sets_variables)]

#Plot of a set of time series data
for i in history_position:
    for j in history_variables:
        fig = plt.figure(figsize=(8,8))
        ax = fig.add_subplot(111)

        ax.plot(dataSet_test01[0][j+"_"+i][0], dataSet_test01[0][j+"_"+i][1], label=j)
        ax.legend(bbox_to_anchor=(1.01, 1., 0., 0), loc='upper left', borderaxespad=0.,)

#Spatial distribution plot
for sets in sets_variables:
    for column in dataSet_test01[1][sets+"_"+sets_position]:
        fig = plt.figure(figsize=(8,8))
        ax = fig.add_subplot(111)
    
        ax.plot(dataSet_test01[1][sets+"_"+sets_position]["x"], 
            dataSet_test01[1][sets+"_"+sets_position][column], 
            label=sets+"_"+column)
        ax.legend(bbox_to_anchor=(1.01, 1., 0., 0), loc='upper left', borderaxespad=0.,)

Recommended Posts

Reading OpenFOAM time series data and sets data
[Python] Plot time series data
Reading, summarizing, visualizing, and exporting time series data to an Excel file with Python
Graph time series data in Python using pandas and matplotlib
Python: Time Series Analysis: Preprocessing Time Series Data
Differentiation of time series data (discrete)
Time series analysis 3 Preprocessing of time series data
Comparison of time series data predictions between SARIMA and Prophet models
When plotting time series data and getting a matplotlib Overflow Error
Forecasting time series data with Simplex Projection
Predict time series data with neural network
Time series data anomaly detection for beginners
How to handle time series data (implementation)
Time series analysis # 6 Spurious regression and cointegration
Format and display time series data with different scales and units with Python or Matplotlib
[Kaggle] From data reading to preprocessing and encoding
Kaggle Kernel Method Summary [Table Time Series Data]
Time Series Decomposition
Acquisition of time series data (daily) of stock prices
View details of time series data with Remotte
How to read time series data in PyTorch
[Latest method] Visualization of time series data and extraction of frequent patterns using Pan-Matrix Profile
Features that can be extracted from time series data
Visualize data and understand correlation at the same time
Time series data prediction by AutoML (automatic machine learning)
Python: Time Series Analysis
Reading data with TensorFlow
"Measurement Time Series Analysis of Economic and Finance Data" Solving Chapter End Problems with Python
Python time series question
RNN_LSTM1 Time series analysis
Time series analysis 1 Basics
Display TOPIX time series
Time series plot / Matplotlib
[Python] [Supplement] Chapter 04-08 Various data structures (creating and manipulating sets)
How to generate exponential pulse time series data in python
A story about clustering time series data of foreign exchange