barotropy.fluent_automation.fluent_automation module#

exception barotropy.fluent_automation.fluent_automation.TranscriptFileMissingError(message=None)[source]#

Bases: ValueError

Raised when plotting residuals is requested but no transcript file is provided.

barotropy.fluent_automation.fluent_automation.add_solution_strategy(journal, strategy)[source]#

Insert the solution strategy into a Fluent journal after the designated comment.

This function takes a Fluent journal list of commands and adds the solution strategy provided in the strategy dictionary right after the comment: “; Run the simulation according to solution strategy”.

Parameters:
journallist of str

List of strings, where each string corresponds to a command or comment in the initial Fluent journal content.

strategydict

A dictionary containing the solution strategy. It should have the following keys:

  • time_scale_factorslist of float

    List of time scale factors.

  • density_relaxation_factorslist of float

    List of density relaxation factors.

  • number_of_iterationslist of int

    List of number of iterations.

Returns:
list of str

List of strings with the modified Fluent journal commands.

Raises:
ValueError

If the “; Run the simulation according to solution strategy” comment is not found in the initial journal.

Examples

>>> journal_content = ["... [journal commands] ...", "; Run the simulation according to solution strategy", "... other commands ..."]
>>> strategy = {
    "time_scale_factors": [0.25, 0.50],
    "density_relaxation_factors": [1.0, 1e-3],
    "number_of_iterations": [200, 300]
}
>>> new_journal = add_solution_strategy_to_journal(journal_content, strategy)
barotropy.fluent_automation.fluent_automation.compare_dicts(d1, d2, keys_to_skip=None, nested_skips={'barotropy_options': ['save_fig', 'ODE_tolerance'], 'fluent_options': ['processor_count', 'show_gui', 'plot_realtime_residuals', 'res_settings', 'relaxation', 'solution_strategy', 'stop_simulation']})[source]#

Compare two dictionaries for equality, with options to skip specific keys.

This function checks if two dictionaries are equal, allowing for the exclusion of specified top-level and nested keys during the comparison.

Parameters:
d1dict

The first dictionary to compare.

d2dict

The second dictionary to compare.

keys_to_skiplist

A list of top-level keys to ignore during comparison.

nested_skipsdict

A dictionary specifying nested keys to skip for certain top-level keys (e.g., {‘barotropy_options’: [‘save_fig’]}).

Returns:
bool

True if the dictionaries are equal after applying the skip rules; False otherwise.

barotropy.fluent_automation.fluent_automation.kill_fluent(transcript_file, fluent_pid)[source]#

Check if the simulation has converged; if not, terminate the Fluent process.

This function examines the transcript file to determine whether the simulation has successfully converged. If convergence has not been reached, the associated Fluent process is forcefully terminated using its process ID.

Parameters:
transcript_filestr

Path to the transcript file containing simulation output.

fluent_pidint

Process ID of the running Fluent simulation to be terminated if not converged.

Returns:
None
barotropy.fluent_automation.fluent_automation.parse_fluent_out(filename)[source]#

Parse an out-formatted datafile from Fluent and return a DataFrame.

Parameters:
filenamestr

The path to the Fluent output file.

Returns:
pd.DataFrame

A DataFrame containing the parsed data from the Fluent output file.

Raises:
ValueError

If the file format is not as expected.

FileNotFoundError

If the provided filename does not exist.

Examples

>>> df = parse_fluent_out("path_to_file.out")
>>> print(df.head())
barotropy.fluent_automation.fluent_automation.parse_fluent_xy(filename)[source]#

Parse a Fluent .xy file and return its contents as a dictionary of DataFrames.

Fluent’s .xy files contain datasets, each representing XY plot data for some solution data (like pressure or velocity) across a specific domain or region (like wall, axis, etc.). This function reads such files and outputs a structured dictionary where the keys are dataset labels (like “wall”, “axis”) and values are corresponding pandas DataFrames.

Parameters:
filenamestr

Path to the Fluent .xy file to be parsed.

Returns:
data_outdict

A dictionary where: - The keys are dataset labels from the .xy file, e.g., “wall”, “axis”. - The values are pandas DataFrames containing the XY data. Each DataFrame has two columns representing the X and Y axis data, labeled as per the .xy file’s axis labels.

Examples

For a Fluent .xy file containing datasets “wall” and “axis”, the output dictionary keys might be [‘wall’, ‘axis’].

barotropy.fluent_automation.fluent_automation.plot_residuals(transcript_file, fig=None, ax=None, savefig=False, fullpath=None)[source]#

Plot the residual history from the given transcript file.

Parameters:
transcript_filestr

Path to the transcript file containing residuals.

figmatplotlib.figure.Figure, optional

Existing figure to plot on, if provided. Defaults to None.

axmatplotlib.axes.Axes, optional

Existing axis to plot on, if provided. Defaults to None.

savefigbool, optional

Flag to save the figure to a file. Defaults to False.

fullpathstr, optional

If savefig is True, path to save the figure to (excluding file extension). Defaults to None.

Returns:
figmatplotlib.figure.Figure

Figure containing the plotted residuals.

axmatplotlib.axes.Axes

Axes containing the plotted residuals.

Notes

The function reads the residuals from the given transcript file using read_residual_file and then plots them on a semi-log scale. If fig and ax are not provided, it creates a new figure and axis. The residuals are mapped to readable labels using a predefined name_map.

barotropy.fluent_automation.fluent_automation.plot_residuals_real_time(transcript_file)[source]#

Plot the residual history contained in the transcript_file.trn in real time.

This function launches the stream_residuals.py script as a subprocess to plot the residual history of the given transcript file in real time.

Parameters:
transcript_filestr

Path to the transcript file whose residuals are to be plotted.

Returns:
subprocess.Popen

The subprocess object representing the background process.

barotropy.fluent_automation.fluent_automation.print_transcript_real_time(transcript_file)[source]#

Print the content of transcript_file.trn in real time.

This function launches the stream_transcript.py script as a subprocess to print the content of the given transcript file in real time.

Parameters:
transcript_filestr

Path to the transcript file to be printed.

Returns:
subprocess.Popen

The subprocess object representing the background process.

barotropy.fluent_automation.fluent_automation.read_expression_file(filename)[source]#

Read expressions from the output file of the barotropic model.

This function parses the output expression file from the barotropic model and stores each expression in a dictionary. Each variable is stored with a key formatted as “barotropic_{variable_name}”.

Parameters:
filenamestr

Path to the expression file generated by the barotropic model.

Returns:
dict

A dictionary containing the parsed expressions named as “barotropic_{variable_name}”.

barotropy.fluent_automation.fluent_automation.read_residual_file(filename, line_start=0, error_messages=['Error object: #f', 'Error Object: #f', 'Error Object: ()', 'ERROR: floating point exception'])[source]#

Reads a transcript file to extract the residual history and returns it as a Pandas DataFrame.

Parameters:
filenamestr

Path to the transcript file.

line_startint, optional

Line number to start reading from. Useful for files with non-relevant introductory lines. Defaults to 0.

Returns:
pd.DataFrame

DataFrame containing the extracted residuals with appropriate column headers.

Notes

It is assumed that the residual headers in the transcript file start with ‘iter’ end with ‘time/iter’.

barotropy.fluent_automation.fluent_automation.run_cleanup_script(max_retries=5, wait_interval=5)[source]#

Execute the cleanup script found in the current working directory.

This function repeatedly attempts to find and execute files with a prefix of “cleanup-fluent” in the current directory. If the script isn’t found immediately, the function will wait for a short interval and try again, up to a specified maximum number of retries.

Parameters:
max_retries (int): Maximum number of times the function will attempt

to find and execute the cleanup script.

wait_interval (int): Time in seconds to wait between consecutive

retries.

Note:

The function is used to ensure that necessary cleanup operations are performed after the simulation, especially when the creation of the cleanup script might be delayed.

barotropy.fluent_automation.fluent_automation.run_fluent_simulation(journal, n_proc=1, timeout=3600, plot_residuals=False, print_transcript=False, transcript_file=None)[source]#

Orchestrates the execution of a Fluent simulation using the commands from the provided journal file.

The function manages the entire simulation process from initiating Fluent, sending it the right commands, visualizing output, to cleaning up post-simulation resources. It offers functionalities to both visualize the Fluent console output in Python and plot the residual history in real time.

Parameters:
journalstr

The sequence of Fluent commands to be executed.

n_procint, optional

Number of processor cores Fluent should use. Default is 1.

timeoutint, optional

Maximum allowable time for the Fluent process to run, in seconds. Default is 3600 (1 hour).

plot_residualsbool, optional

If True, plots residuals in real time. Requires transcript_file to be provided. Default is False.

print_transcriptbool, optional

If True, the Fluent console output will be displayed in Python. Requires transcript_file to be provided. Default is False.

transcript_filestr, optional

Path to the transcript file which contains the residuals and other output data from Fluent. Mandatory if either plot_residuals or print_transcript are set to True.

Returns:
None
Raises:
TranscriptFileMissingError

If either plot_residuals or print_transcript is True and transcript_file is not provided.

Notes

After the simulation, the function automatically invokes the Fluent cleanup script to close open processes.