PyFluent (`ansys-fluent-core`) and NumPy / pandas: source audit
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
- Issue type
- Feature
- Clarity
- Mostly clear
- Activity status
- Active
- Domain
- backend, data, performance
Research direction
Start with the named source modules under src/ansys/fluent/core, especially fields/field_data/live_field_data.py, _grpc_services/_chunk_parser.py, fields/solution_variables/solution_variables.py, and services/streaming_services/monitor_streaming.py. Profile get_mesh, monitor streaming, and set_data on realistic cases as the audit recommends, then scope a focused improvement with tests; done means the chosen bottleneck or API gap is addressed and verified without changing behavior outside that scope.
Written by the indexing model from the issue text.
Description
PyFluent (ansys-fluent-core) and NumPy / pandas: source audit
Scope: this audit covers hand-written source under src/ansys/fluent/core (generated code is excluded). The modules read are:
fields/field_data/:live_field_data.py,_return_data.py,data_types.py,mesh.py,transport.py,_field_data_interfaces.py_grpc_services/:_chunk_parser.py,field_data_service.py,solution_variable_service.py,monitor_service.pyfields/solution_variables/solution_variables.pyservices/streaming_services/monitor_streaming.pyandfield_data_streaming.pyfields/reduction/functional.py
Not covered: the settings API (solver/flobject.py), the offline/file session readers, tests, docs and examples. Everything said about those areas below is unverified.
1. Summary
| Area | NumPy use | Verdict |
|---|---|---|
| Field data decode (gRPC → arrays) | np.frombuffer on byte chunks into preallocated np.empty |
Good, close to zero-copy |
| Surface data shapes | vertices, centroids and normals are reshape(-1, 3) |
Good |
| Vector fields | reshape(-1, 3) ndarray |
Good |
| Face/line connectivity | flat VTK-style [n, i0..in-1, ...]; legacy list-of-arrays deprecated |
OK, but no offsets/indices form |
Solver mesh (get_mesh) |
object ndarrays of Python dataclasses, built in per-node Python loops | Poor |
SVAR read (get_data) |
np.frombuffer byte stream |
Good |
SVAR write (set_data) |
ndarray → protobuf repeated fields | Inefficient |
| Monitors | pandas DataFrame, pd.concat once per streamed iteration |
Quadratic growth |
| Reductions | Python floats/lists | Fine (small data) |
Interop helpers (__array__, pandas, xarray, pyvista) |
none | Gap |
2. Checking the earlier AI answer against the code
| Earlier claim | What the source shows |
|---|---|
"Build arrays with np.frombuffer instead of repeated fields" |
Already done. ChunkParser._extract_field requests provide_bytes_stream=True (256 KiB chunks) and copies each chunk via np.frombuffer into a preallocated array. Repeated-field payloads remain only as a fallback (np.fromiter). |
| "Normals come back as a flat float32 array" | Wrong for current code. _ReturnFieldData._surface_data reshapes every non-connectivity type, normals included, to (N, 3). The dtype follows the server's precision (float32 or float64). |
"Vector fields return an (array, scale) tuple" |
Wrong / outdated. _vector_data returns an (N, 3) ndarray per surface. |
| "Face connectivity is flat VTK-style" | Correct, with flatten_connectivity=True. Without it you get a deprecation warning and a list of per-face arrays. |
"Mesh/Node are per-object Python structures" |
Correct, and worse than implied. See §4. |
| "Writing data back would make the API symmetric" | Already exists for solution variables: SolutionVariableData.set_data plus create_empty_array. Its transport is inefficient, though (§5). |
| "Residual/monitor histories could be ndarrays/pandas" | Already pandas-backed internally, and get_monitor_set_data returns ndarrays. The build-up is O(n²) and the DataFrame isn't a public API (§6). |
| "Structured / xarray-style multi-field results" | Still a valid suggestion. Results are nested dicts keyed by surface. |
3. Field data (the strong part)
Pipeline: LiveFieldData.get_field_data(request) → FieldDataBase._get_* → FieldDataService (gRPC stream) → ChunkParser.extract_fields → _ReturnFieldData (shape and key by surface).
What works well:
- Arrays are preallocated, filled from byte payloads with
np.frombuffer, and the dtype comes from the proto field type (int32,int64,float32,float64). - Batching (
new_batch().add_requests(...).get_response()) collects several requests into one RPC. - Results come back keyed by the name or ID the user passed in, which reads naturally.
- The same parser feeds streaming callbacks with
(surface_id, field_name, ndarray).
Weaknesses and improvements:
- One extra copy per chunk.
field_arr[i:j] = np.frombuffer(...)copies the data once more. That's acceptable. True zero-copy would need a single contiguous buffer from the server, so the current approach is a reasonable trade-off. - Repeated
np.concatenate. When the same(surface, field_name)arrives in several payload groups,np.concatenatereallocates each time, which is O(k²) in the number of groups. Collect the pieces in a list and concatenate once at the end. - The dtype isn't stable.
SurfaceDataannotatesNDArray[np.float64], but single-precision Fluent returnsfloat32. TheSurfaceDatadocstring also saysconnectivity: list[NDArray[np.float64]]while the code annotation saysint32. Document the precision rule, or offer adtype=option. - Empty data handling. A missing field produces
np.array([])(float64, shape(0,)) plus a warning, rather than a correctly typed(0, 3)array. Downstreamreshape(-1, 3)works, but the dtype silently changes. - Connectivity format. The flat VTK format is pyvista-friendly, but NumPy users usually want
offsetsplusindices, or(M, 3)/(M, 4)for pure tri/quad surfaces. The legacy_transform_faces_connectivity_datais a Pythonwhileloop. It's deprecated, but it could be vectorized withnp.cumsumandnp.splitwhile it still exists. - No interop protocol.
SurfaceDataandPathlinesDataare plain attribute bags with no__repr__, no__array__, and noto_pyvista(),to_dataframe()orto_xarray(). - Validation latency (not NumPy, but it dominates small requests).
_get_surface_idscalls_get_surfaces_info()(an RPC) once per string surface._AllowedSurfaceIDs(field_info)()is rebuilt per integer surface. The vector path runsscheme.string_eval("(surface? id)")once per surface. Caching these per request would help.
4. Solver mesh: LiveFieldData.get_mesh (the weakest part)
nodes = np.empty(node_count, dtype=Node) # object array of dataclasses
for nodes_pb in nested_nodes:
for node_pb in nodes_pb:
nodes[i] = Node(_id=..., x=..., y=..., z=...)
node_index_by_id[node_pb.id] = i
...
Element(..., node_indices=[node_index_by_id[id] for id in element_pb.node_ids])
dtype=Nodecreates an object array, which gives none of NumPy's benefits.Meshis annotatedlist[Node]but actually holds an ndarray, so the annotation is wrong.- Node and element building is a Python loop per node and per element, plus a dict lookup per connectivity entry. For cell zones with millions of cells, this dominates
get_mesh. The method's own timing logs separate this "construct structure" phase from the RPC. - The transport itself uses repeated protobuf messages for nodes, not byte payloads.
Recommendation: add an array-backed representation (and keep the dataclasses as a view if needed).
node_ids: int64[N]andcoords: float64[N, 3]cell_types: uint8[M], plusoffsets: int64[M+1]andconnectivity: int64[K](VTK or meshio style)- polyhedra as face-stream arrays
Remap IDs to indices with np.searchsorted on sorted node_ids, or with a lookup array, instead of a dict. If possible, extend the server to stream nodes and elements as byte payloads like field data. The result would plug directly into pyvista or meshio.
5. Solution variables (SVAR)
- Read (
extract_svars): byte stream intonp.frombufferinto a preallocated array. Good. - Write (
set_data): splits the array withnp.array_split(fine), then buildsFloatPayload(payloads=ndarray)and similar. That fills a protobuf repeated field, which converts element by element in Python. Adding abyte_payloadpath (arr.tobytes()) would make writes as cheap as reads. - Arrays are flat with length
count * dimension. Multi-component SVARs such asSV_CENTROIDaren't reshaped to(count, dimension), unlike surface vectors. That's inconsistent with the field-data API. create_empty_arrayis a nice NumPy-first touch. It returnsNonesilently if the zone or variable is missing.set_datadoesn't check the dtype: it looks upsolution_variable_data.dtype.typein a mapping. A Python list, or an ndarray of an unsupported dtype (for examplefloat16), fails with an unclear error. A shape or size check against the zone count would also help. Usenp.asarray(x, dtype=expected).
6. Monitors and pandas
MonitorsManager keeps one pandas DataFrame per monitor set (pandas is imported lazily):
new_df = pd.DataFrame([monitor_data], columns=monitors)
df_data["df"] = pd.concat([df, new_df]) # every streamed iteration
- This is O(n²) in iterations. Each
concatcopies the whole history, which slows down long transient runs. Fix it by appending into a list or growable NumPy buffers, and build or cache the DataFrame lazily when it's read. - The initial empty DataFrame has object-dtype columns, so recent pandas versions emit FutureWarnings on concat-with-empty, and the dtypes may stay
object. - Public access is
get_monitor_set_data(), which returns(x ndarray, {name: ndarray}), andget_monitor_set_plot(), which returnsdf.plot. There is no publicto_dataframe(), even though a DataFrame already exists internally. Exposing one (a copy, taken under the lock) costs nothing and helps pandas users a lot. - There's no time or flow-time column: only the x-axis index is kept.
7. Reductions
fields/reduction/functional.py returns scalars or small lists, so NumPy isn't needed. The only small gap is that vector-valued reductions (for example centroid or force) could return an ndarray of shape (3,) instead of a list.
8. Abstractions for NumPy users: assessment
Strengths
- Requests are typed namedtuples (
ScalarFieldDataRequest, …), and batching is explicit. - Results are real ndarrays with sensible
(N, 3)shapes for geometry and vectors. - SVAR read/write uses ndarrays both ways.
- Results are keyed by the surface identifiers the user supplied.
Gaps
- Results are nested
dict[surface] -> object/ndarray. There's no tidy or long-format export (one DataFrame row per node or face, with columnssurface, x, y, z, pressure, ...). - The dtype contract isn't documented (it depends on solver precision), and the annotations disagree with runtime types (
Mesh.nodes,SurfaceData.connectivity). - There's no
__array__,__repr__or.to_*()onSurfaceData,PathlinesData,DataorMesh. - Nothing states whether returned arrays may be mutated or are fresh copies. They are fresh copies today, and that should be documented as a guarantee.
- Node versus cell location is a boolean (
node_value) and isn't carried on the result, so users can't tell from the data which one they have.
9. Prioritized recommendations
- Vectorize
get_mesh(array-backedMesh, ID remapping in NumPy). This is likely the largest win, though it hasn't been measured. Ideally also move the server to byte payloads. - Fix the monitor DataFrame build-up: list or buffer append, a lazy DataFrame, and a public
to_dataframe(). - Byte-payload writes for
set_data, plus dtype and size validation vianp.asarray. - Settle the conventions once, as the earlier answer suggested: dtype policy (native precision versus always float64),
(N, k)shapes for multi-component data (including SVARs), and the connectivity format (offsets+indices). Document copy semantics. - Interop adapters, kept optional and lazily imported:
SurfaceData.to_pyvista(),to_dataframe()on field-data results and SVARData, maybeto_xarray(). - Small fixes: concatenate the chunk parser's pieces once at the end, return typed empty arrays, correct the annotations, and cache surface validation per request.
Measure items 1–3 with a profiler on realistic cases (a large cell zone, a long transient run, a large SVAR write) before and after the changes.
10. Not verified (follow-up)
solver/flobject.py: whether list-valued real settings accept or return ndarrays.- Offline readers (
offline/,execution/session/file): HDF5 case/data reading paths. - Tests, docs and examples: how users combine the API with NumPy or pandas in practice.
- Dominant language
- Python
- Stars
- 550
- Forks
- 86
- Avg merge
- 2d 1h
- Merged PRs (30d)
- 58
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from ansys/pyfluent
-
documentation
Difficulty 1/5 Under an hour Newbie friendliness 70/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
ansys/pyfluent#5515 · 2 reactions ·
Maintainers usually reply within 1 day
-
documentation
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
Maintainers usually reply within 1 day
-
[DOC]: DOE_ML: Update the keras model definition to match the supported APIPossibly taken A pull request linked to this issue is open or already merged. Opendocumentation
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
[DOC]: Lunar Lander Outdated APIPossibly taken A pull request linked to this issue is open or already merged. Opendocumentation
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
Maintainers usually reply within 1 day
Similar issues
-
`gitlab_importer_v2` pipeline failing due to malformed YAML filePossibly taken @Gowri213 claimed this today. Openbug Pipeline: Failure Priority: high
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
aboutcode-org/vulnerablecode#2523 · 1 comment ·
Maintainers usually reply within 5 days
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
intuitem/ciso-assistant-community#5380 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
confluentinc/cp-ansible#2767 ·
Maintainers usually reply within 3 days
-
bug docs
Difficulty 1/5 Under an hour Newbie friendliness 85/100
Maintainers usually reply within 1 day
-
Difficulty 1/5 Under an hour Newbie friendliness 85/100
Maintainers usually reply within 2 days