Share

API example: Reading pressure data

Time-series data are available through the API as the independent values of a plot. This is how animations are represented.

This example performs the following tasks:

  • Extracts the pressure result and computes the average pressure of each set of five time steps
  • Reconstructs a custom pressure plot

You can use this example when you want to read a specific result set, or put the data into a new result set.

# %RunPerInstance
"""
DESCRIPTION:
Split Pressure Time Series Result into Individual Results.
Recreate the Pressure Time Series Result

SYNTAX:
python filename.py
eg.
python split_pressure_time_series_to_individual.py
python split_pressure_time_series_to_individual.py -silent True 

PARAMETERS:
-silent: Info Prompts, if set to True, no info will pop up [default: False].

DEPENDENCIES/LIMITATIONS:
Requires Moldflow Synergy and active project with pressure results
"""

from moldflow import Synergy
from moldflow.common import SystemUnits
import tkinter as tk
from tkinter import messagebox
import argparse

def parse_arguments():
    """
    Parses command-line arguments using argparse.

    Returns:
        argparse.Namespace: Parsed arguments.
    """
    parser = argparse.ArgumentParser(
        description="Loop through entities",
        add_help=False  # Disable default -h/--help behavior
    )
    parser.add_argument(
        "-silent", "--silent",
        type=bool,        
        help="Silent mode [default: False]."
    )
    return parser.parse_args()

def main():
    """Main function to process pressure time series data."""

    args = parse_arguments()
    silent = args.silent
    # Output string
    output = ""

    # Initialize Synergy with METRIC units
    synergy = Synergy(units=SystemUnits.METRIC)

    # Get PlotManager
    plot_manager = synergy.plot_manager

    # Result ID for pressure time series
    result_id = 1180

    # Find and select the Pressure plot
    pressure_plot = plot_manager.find_plot_by_name("Pressure")
    if not pressure_plot:
        print("Warning: Could not find pressure plot")
        quit()

    synergy.viewer.show_plot_by_name("Pressure")

    # Get independent values (time steps)
    indp_values = synergy.create_double_array()
    plot_manager.get_indp_values(result_id, indp_values)

    # Display average pressure at intervals (every 5th step)
    result_string = ""

    for i in range(0, indp_values.size, 5):
        # Create arrays for this time step
        indp = synergy.create_double_array()
        indp.add_double(indp_values.val(i))

        node_id = synergy.create_integer_array()
        values = synergy.create_double_array()

        # Get scalar data for this time step
        if plot_manager.get_scalar_data(result_id, indp, node_id, values):
            # Calculate average pressure
            total_pressure = 0.0
            count = 0

            for j in range(node_id.size):
                count += 1
                total_pressure += values.val(j)

            if count > 0:
                average_pressure = total_pressure / count
                time_value = indp_values.val(i)
                result_line = f"Time={time_value:.15f} Average P={average_pressure:.15f} MPa\n"
                result_string += result_line

    # Display results
    if result_string:
        print("\nPressure Analysis Results:")
        print("=" * 40)
        print(result_string)


    if not silent:
        # Initialize tkinter for message box
        root = tk.Tk()
        root.withdraw()
        messagebox.showinfo("Pressure Analysis Results", result_string)
        root.destroy()

    # Recreate pressure time series as new user plot
    user_plot = plot_manager.create_user_plot()
    header = "New Pressure Time Series"
    plot_manager.delete_plot_by_name(header)

    user_plot.set_name(header)
    user_plot.set_data_type("NDDT")  # Node-dependent, time-dependent
    user_plot.set_dept_unit_name("MPa")
    user_plot.set_dept_name("Time")
    user_plot.set_vector_as_displacement(False)


    # Add all time steps to the user plot
    for i in range(indp_values.size):
        indp = synergy.create_double_array()
        indp.add_double(indp_values.val(i))

        node_id = synergy.create_integer_array()
        values = synergy.create_double_array()
        # Get scalar data for this time step
        if plot_manager.get_scalar_data(result_id, indp, node_id, values):
            user_plot.add_scalar_data(indp_values.val(i), node_id, values)
        else:
            print(f"Warning: Could not get data for time step {i}")

    # Build the user plot
    user_plot.build()

    print("Script Complete!")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Error: {e}")

Was this information helpful?