The script does the following (for each coupling ID):
import os import pandas as pd import matplotlib.pyplot as plt import re import argparse import sys # Create a parser object parser = argparse.ArgumentParser( description="Parse ISPG coupling file and plot data.") # Required filepath argument parser.add_argument("filepath", type=str, help="ISPG coupling file path.") # Optional --add argument for coupling IDs to sum parser.add_argument("--add", nargs='+', type=int, help="List of coupling IDs to sum and plot (only for forces).") # Parse arguments args = parser.parse_args() file_path = args.filepath coupling_ids_to_add = args.add if args.add else [] # Open the file and parse the content data = [] current_time = None with open(file_path, 'r') as file: for line in file: line = line.strip() time_match = re.match(r'time = +(.+E[+\-]\d{2})', line) if time_match: current_time = float(time_match.group(1).replace('E', 'e')) if current_time is not None and re.match(r'^\s*\d', line): parts = line.split() if len(parts) >= 5: row_data = [ current_time, int(parts[0]), float(parts[1]), float(parts[2]), float(parts[3]), float(parts[4]) ] data.append(row_data) # Create a DataFrame columns = ['time', 'ID', 'area', 'fx', 'fy', 'fz'] df = pd.DataFrame(data, columns=columns) # Validate coupling IDs if coupling_ids_to_add: existing_ids = set(df['ID'].unique()) invalid_ids = [ cid for cid in coupling_ids_to_add if cid not in existing_ids] if invalid_ids: print( f"Error: The following coupling IDs were not found in the data: {invalid_ids}") sys.exit(1) # Plotting function def plot_data(df, y_col, title, filename, coupling_ids_to_add): fig, ax = plt.subplots(figsize=(10, 6)) # Plot each individual ID for ID in df['ID'].unique(): id_data = df[df['ID'] == ID] ax.plot(id_data['time'], id_data[y_col], label=f'ID {ID}') # Plot summed line only for force columns if coupling_ids_to_add and y_col in ['fx', 'fy', 'fz']: summed_data = df[df['ID'].isin(coupling_ids_to_add)] summed_group = summed_data.groupby('time')[y_col].sum().reset_index() ax.plot(summed_group['time'], summed_group[y_col], label=f'Sum of IDs {coupling_ids_to_add}', linewidth=2, linestyle='--', color='black') file_path_image = os.path.join(os.path.dirname(file_path), filename) ax.set_title(title) ax.set_xlabel('Time') ax.set_ylabel(y_col) ax.grid(True) ax.legend() plt.show() fig.savefig(file_path_image) plt.close(fig) # Create plots plot_data(df, 'fx', 'fx vs Time', 'fx_vs_time.png', coupling_ids_to_add) plot_data(df, 'fy', 'fy vs Time', 'fy_vs_time.png', coupling_ids_to_add) plot_data(df, 'fz', 'fz vs Time', 'fz_vs_time.png', coupling_ids_to_add) # No summed line for area plot_data(df, 'area', 'Area vs Time', 'area_vs_time.png', [])