1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenFOAMのprobeファイルのパース ~U~

1
Posted at

はじめに

OpenFOAMでは、指定位置のデータをprobeで出力することができる。
スカラー量は簡単にpandasで読み込むことができるが、ベクトル量は以下のように出力されるのでそのままではpandasで読み込むことができません。

# Probe 0 (0 0 0)
# Probe 1 (0.1 0.2 0.3)
# Probe 2 (1 1 1)
# Time         Probe0  Probe1 ...
0.000          (0 0 0)  (0 0 0) ...
0.005          (0.123 0.456 0.789)  (0.123 0.456 0.789)     ...
0.010          ...

作ったスクリプト

"""
OpenFOAM probe_u ファイルを読み込んでDataFrameに変換するスクリプト
"""

import pandas as pd
import re
import os
from pathlib import Path
from typing import Union

def parse_probe_file(file_path: Union[str, Path]):
    """
    probe_uファイルを読み込んでDataFrameに変換
    
    Parameters:
    -----------
    file_path : str or pathlib.Path
        probe_uファイルのパス
        
    Returns:
    --------
    pandas.DataFrame or None
        解析されたDataFrame、エラーの場合はNone
    """
    
    # 文字列またはPathオブジェクトをPathオブジェクトに統一
    file_path = Path(file_path)
    
    # ファイルの存在確認
    if not file_path.exists():
        print(f"エラー: ファイル '{file_path}' が見つかりません")
        return None
    
    # ファイル読み込み
    try:
        with open(file_path, "r") as f:
            lines = f.readlines()
    except Exception as e:
        print(f"ファイル読み込みエラー: {e}")
        return None
    
    # ヘッダー行を見つける
    header_line = None
    data_start_line = None
    
    for i, line in enumerate(lines):
        if line.startswith("# Time"):
            header_line = line
            data_start_line = i + 1
            break
    
    if header_line is None:
        print("エラー: ヘッダー行が見つかりません")
        return None
    
    # カラム名の作成
    raw_headers = header_line.strip().split()
    columns = ["Time"]
    
    # "U_0", "U_1", "U_2" などの各プローブに対してx, y, z成分を追加
    for header in raw_headers[2:]:  # "Time"と"#"をスキップ
        probe_name = header.strip()
        columns.extend([f"{probe_name}_x", f"{probe_name}_y", f"{probe_name}_z"])
    print(f"raw_headers: {raw_headers[2:]}")
    print(f"new_columns: {columns[1:]}")
    
    # データ行の抽出と解析
    parsed_data = []
    data_lines = lines[data_start_line:]
    
    for line_num, line in enumerate(data_lines, start=data_start_line + 1):
        line = line.strip()
        
        # 空行やコメント行をスキップ
        if not line or line.startswith("#"):
            continue
        
        try:
            # 時間値と残りの部分を分離
            parts = line.split(None, 1)  # 最初のスペースで分割(時間値のみ分離)
            if len(parts) < 2:
                continue
                
            time_val = float(parts[0])
            remaining_line = parts[1]
            
            row = [time_val]
            
            # 正規表現でベクトル全体を抽出 (x y z) 形式
            vector_pattern = r'\([^)]+\)'
            vectors = re.findall(vector_pattern, remaining_line)
            
            for vec_str in vectors:
                # 括弧を除去して x y z を取得
                inner_content = vec_str[1:-1]  # 最初と最後の括弧を除去
                try:
                    x, y, z = map(float, inner_content.split())
                    row.extend([x, y, z])
                except ValueError:
                    print(f"警告: 行 {line_num} でベクトル値の変換エラー: {vec_str}")
                    row.extend([None, None, None])
            
            parsed_data.append(row)
            
        except Exception as e:
            print(f"警告: 行 {line_num} でエラー: {e}")
            continue
    
    # DataFrameの作成
    try:
        df = pd.DataFrame(parsed_data, columns=columns)
        print(f"データ読み込み完了: {len(df)} 行, {len(df.columns)} 列")
        return df
    except Exception as e:
        print(f"DataFrame作成エラー: {e}")
        return None
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?