PyFluent Documentation

repository·main·Indexed 19 days ago

https://github.com/ansys/pyfluent

PyFluent provides Pythonic access to Ansys Fluent, enabling users to launch Fluent, execute TUI commands for meshing and solving, and perform postprocessing within the Python ecosystem. It supports Python 3.10 through 3.14 on Windows, macOS, and Linux. The library includes the core package ansys-fluent-core, as well as specialized packages for parametric workflows (pyfluent-parametric) and visualization (pyfluent-visualization).

Tokens
56.9K
Snippets
153
Records
185
Agent score
65%

What's inside PyFluent

  1. Perform Fluent simulations using Python

    main

    PyFluent allows you to automate and control the entire Ansys Fluent simulation workflow directly from Python. You can use the library to perform the following tasks:

    • Geometry Import: Programmatically bring geometry into the Fluent environment.
    • Meshing Workflows: Automate Fluent's meshing capabilities.
    • Solver Setup and Execution: Configure physics, boundary conditions, and solver settings, then run the simulation.
    • Postprocessing: Review and analyze simulation results using Fluent's built-in postprocessing tools.
  2. Welcome to PyFluent

    main
    PyFluent is a Python interface for Ansys Fluent that enables engineers and developers to automate, customize, and streamline Computational Fluid Dynamics (CFD) workflows. It allows for programmatic interaction with Fluent to handle simulation setup, execution, monitoring, and results extraction.
  3. Key features of PyFluent

    main

    PyFluent provides several core capabilities for CFD simulation automation:

    • Launching Fluent: Start sessions locally or remotely with various options, or connect to an existing session.
    • Session Management: Interact with Fluent through session objects returned by launch or connect methods.
    • Guided Meshing: Use intuitive guided workflows to create high-quality meshes.
    • Solution Control: Use settings objects to configure physics and execute simulations.
    • Field Data Extraction: Access and modify mesh and solution data arrays. You can use reduction functions or Fluent's expression language for analysis.
    • Offline Features: Use the ansys.fluent.core.file_session.FileSession class to access case, data, and project files without requiring a live Fluent session.
  4. What is PyFluent and how does it differ from UDFs?

    main

    PyFluent provides Python access to Ansys Fluent, enabling automation and integration with the Python ecosystem (ML, AI, Data Science).

    Key Distinctions:

    • Purpose: PyFluent is conceptually aligned with Fluent TUI (Text User Interface) commands and journaling. It is used for automation and workflow orchestration, whereas User Defined Functions (UDFs) are used for modifying solver behavior.
    • Language: UDFs are written in C. While you cannot write UDFs directly in Python, you can use PyFluent to execute commands that compile and load existing UDFs.
  5. Use FileSession for offline data access

    main

    The ansys.fluent.core.file_session.FileSession class allows you to access field data and mesh information without requiring a live Fluent session. It mimics the functionality of live session objects by reading case (.cas.h5) and data (.dat.h5) files directly.

    To use it, you can either pass the file names directly to the constructor or use the .read_case() and .read_data() methods after instantiation.

    from ansys.fluent.core.file_session import FileSession
    
    # Approach 1: Pass files to constructor
    file_session = FileSession(case_file_name, data_file_name)
    
    # Approach 2: Use read methods
    file_session = FileSession()
    file_session.read_case("elbow1.cas.h5")
    file_session.read_data("elbow1.dat.h5")
  6. Use wildcards for named objects and settings

    main

    When accessing named objects, list objects, or string list settings, you can use wildcards to target multiple entities at once.

    Common Wildcards:

    • *: Zero or more occurrences of the preceding element.
      • 'in*' matches in1, in2.
      • '*in*' matches any name containing in.
    • ?: A single unknown character (e.g., 'gr?y' matches grey or gray).
    • []: A range of numbers or characters at the start of a string (e.g., '[0-9]' or '[a-z]').
    • ^: Boolean NOT (negation). '^*in*' matches anything NOT containing in.
    • |: Boolean OR. '*part*|*solid*' matches names containing either part or solid.
    • &: Boolean AND. '*part*&*solid*' matches names containing both part and solid.
    # Target all fluid cell zones using a wildcard
    >>> from ansys.fluent.core.solver import FluidCellZone
    >>> fluid = FluidCellZone(settings_source=solver_session, name="*")
    
    # Target all velocity inlets with 'inlet' in the name
    >>> from ansys.fluent.core.solver import VelocityInlet
    >>> inlet = VelocityInlet(settings_source=solver_session, name="*inlet*")
    
    # Use wildcards in string list settings
    >>> solver_session.settings.results.graphics.contour['contour-1'].surfaces_list = 'in*'
    >>> solver_session.settings.results.graphics.contour['contour-1'].surfaces_list()
    ['in1', 'in2']
  7. Use reduction functions in PyFluent

    main

    Reduction functions allow you to perform operations like computing averages, integrals, and sums over specified data locations (such as areas or volumes) in Fluent. You can apply these functions to data from a single solver session or across multiple remote Fluent sessions.

    PyFluent supports two primary patterns:

    1. Functional Approach (Recommended): Access functions via the ansys.fluent.core.solver.function.reduction module. This is more flexible and concise, especially when working with multiple solver sessions or complex data sources.
    2. Object-Oriented Approach: Access functions via the solver_session.fields.reduction attribute. This is intuitive for single-solver workflows but less suited for multi-solver scenarios.
    from ansys.fluent.core.solver.function import reduction
    
    # Functional approach (preferred for multi-solver)
    reduction.minimum(expression=..., locations=...)
    
    # Object-oriented approach (single solver)
    solver_session.fields.reduction.area_average(expression=..., locations=...)
  8. Access Fluent case information offline with CaseFile

    main

    The CaseFile class allows you to inspect and extract information from Fluent case files without requiring a live Fluent session. You instantiate a CaseFile object with a case file path or a project path, and then use its methods to query metadata, parameters, and mesh data.

    Supported File Formats:

    • CAS
    • CAS.HF
    • CAS.GZ
    • Supports both text and binary formats.

    Key Capabilities:

    • Query precision and dimensions.
    • Access input and output parameters (including units).
    • Retrieve rp_vars and config_vars as Python data structures.
    • Extract mesh data (surface IDs, names, locations, connectivity, and vertices).
    from ansys.fluent.core.filereader.case_file import CaseFile
    
    # Initialize with a case file
    reader = CaseFile(case_file_name="path/to/file.cas.h5")
    
    # Or initialize with a Fluent project path (FLPRJ)
    reader = CaseFile(project_file_name="Dir1/Dir2/project.flprj")
  9. Choosing between field data and solution variable data APIs

    main

    PyFluent provides two distinct APIs for accessing field array data from Fluent, depending on whether you need surface-centric post-processing or zone-centric solver manipulation.

    Field Data API (field_data)

    • Focus: Surface-centric access (boundaries, face zones, etc.).
    • Capabilities: Supports scalar, vector, and pathlines data, as well as mesh geometry and connectivity.
    • Best For: Post-processing, visualization, mesh extraction, and real-time updates in meshing mode.
    • Limitations: Read-only access; data is organized by surface rather than zone; contains derived/post-processed fields rather than just raw solver variables.

    Solution Variable Data API (solution_variable_data)

    • Focus: Zone-centric access (cell or face zones).
    • Capabilities: Accesses Fluent's internal solution variable arrays (SVARs). Supports both reading and writing.
    • Best For: Direct extraction or modification of solver arrays, custom initialization, and advanced scripting involving zone-specific data.
    • Limitations: Does not provide mesh geometry or general field/derived data; requires knowledge of Fluent's SVAR naming conventions.

    Decision Matrix

    Requirementfield_datasolution_variable_data
    Data on a surfaceYesNo
    Data on a zoneNoYes
    Mesh geometry/connectivityYesNo
    PathlinesYesNo
    Read/write accessRead-onlyRead and write
    Derived/post-processed fieldsYesNo (SVARs only)
    Direct solver arraysNoYes
    Available in meshing modeYesNo
  10. How to observe Fluent events using callbacks

    main

    PyFluent provides an event-driven mechanism to monitor Fluent activities such as solver iterations, case loading, or meshing events. Each session object has an events attribute of type EventsManager. You can use the events.register_callback() method to attach a Python function that executes whenever a specific event occurs.

    Callback Signature: The callback function must follow the signature: cb(session, event_info, <additional arguments>).

    • session: The current session instance.
    • event_info: An instance containing metadata about the event (e.g., iteration index, file names).
    • <additional arguments>: Optional positional or keyword arguments passed during registration.

    Supported Events: Events are categorized into two main classes:

    • SolverEvent: For solver-related activities (e.g., ITERATION_ENDED, CASE_LOADED, SOLUTION_INITIALIZED).
    • MeshingEvent: For meshing-related activities.

    Best Practices:

    • Keep callbacks lightweight: Long-running or CPU-heavy logic in a callback can block event processing and interfere with gRPC communication with the Fluent server.
    • Thread Safety: Event callbacks may run on a worker thread. If you are performing UI updates (e.g., refreshing PyVista or Matplotlib windows), you must schedule that work onto your application's active event loop thread using a thread-safe mechanism like asyncio.call_soon_threadsafe.
    from ansys.fluent.core import SolverEvent, IterationEndedEventInfo
    
    # Define the callback
    def on_iteration_ended(session, event_info: IterationEndedEventInfo):
        print("Iteration ended. Index = ", event_info.index)
    
    # Register the callback
    callback_id = solver_session.events.register_callback(SolverEvent.ITERATION_ENDED, on_iteration_ended)
  11. Use uniform methods for settings and fields

    main

    PyFluent maintains a consistent interface across solver settings and field objects.

    For Settings objects:

    • get_state(): Retrieve the current value/state.
    • set_state(value): Update the value/state.
    • is_active(): Check if a model or setting is active.
    • allowed_values(): List valid options for a setting.
    • min() and max(): Get the valid range for numerical settings.
    • Action Methods: Some items in the settings tree are methods that trigger Fluent actions (e.g., run_calculation.iterate(iter_count=100)).

    For Fields objects:

    • Uses a transaction-based pattern to request and retrieve data. Use new_transaction() to start, add requests (like add_scalar_fields_request), and then call get_fields() to execute the transaction.
    # Settings example
    viscous_model = settings.setup.models.viscous.model
    print(viscous_model.get_state())
    viscous_model.set_state("laminar")
    
    # Fields transaction example
    field_data = fields.field_data
    transaction = field_data.new_transaction()
    add_scalar_fields = transaction.add_scalar_fields_request
    add_scalar_fields(field_name='absolute-pressure', surfaces=['outlet'])
    pressure_fields = transaction.get_fields()
  12. Use VariableCatalog for physical quantities

    main

    PyFluent uses the VariableCatalog from the ansys-units library to provide a shared, unit-aware catalog of physical quantities (e.g., temperature, pressure, velocity).

    Instead of using raw strings like "temperature" or "SV_T", you should use VariableDescriptor objects from the VariableCatalog. This approach:

    • Improves code portability and readability.
    • Reduces errors caused by typos or changing field names in Fluent.
    • Ensures dimensional consistency via ansys-units.
    • Enables autocompletion in supported IDEs.

    VariableCatalog is automatically installed as a dependency of PyFluent.