PyFluent (`ansys-fluent-core`) and NumPy / pandas: source audit

Aperta
#5,565 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
35/100
Tipo di issue
Funzionalità
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
numpy, pandas, python

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.py
  • fields/solution_variables/solution_variables.py
  • services/streaming_services/monitor_streaming.py and field_data_streaming.py
  • fields/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:

  1. 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.
  2. Repeated np.concatenate. When the same (surface, field_name) arrives in several payload groups, np.concatenate reallocates each time, which is O(k²) in the number of groups. Collect the pieces in a list and concatenate once at the end.
  3. The dtype isn't stable. SurfaceData annotates NDArray[np.float64], but single-precision Fluent returns float32. The SurfaceData docstring also says connectivity: list[NDArray[np.float64]] while the code annotation says int32. Document the precision rule, or offer a dtype= option.
  4. Empty data handling. A missing field produces np.array([]) (float64, shape (0,)) plus a warning, rather than a correctly typed (0, 3) array. Downstream reshape(-1, 3) works, but the dtype silently changes.
  5. Connectivity format. The flat VTK format is pyvista-friendly, but NumPy users usually want offsets plus indices, or (M, 3)/(M, 4) for pure tri/quad surfaces. The legacy _transform_faces_connectivity_data is a Python while loop. It's deprecated, but it could be vectorized with np.cumsum and np.split while it still exists.
  6. No interop protocol. SurfaceData and PathlinesData are plain attribute bags with no __repr__, no __array__, and no to_pyvista(), to_dataframe() or to_xarray().
  7. Validation latency (not NumPy, but it dominates small requests). _get_surface_ids calls _get_surfaces_info() (an RPC) once per string surface. _AllowedSurfaceIDs(field_info)() is rebuilt per integer surface. The vector path runs scheme.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=Node creates an object array, which gives none of NumPy's benefits. Mesh is annotated list[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] and coords: float64[N, 3]
  • cell_types: uint8[M], plus offsets: int64[M+1] and connectivity: 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 into np.frombuffer into a preallocated array. Good.
  • Write (set_data): splits the array with np.array_split (fine), then builds FloatPayload(payloads=ndarray) and similar. That fills a protobuf repeated field, which converts element by element in Python. Adding a byte_payload path (arr.tobytes()) would make writes as cheap as reads.
  • Arrays are flat with length count * dimension. Multi-component SVARs such as SV_CENTROID aren't reshaped to (count, dimension), unlike surface vectors. That's inconsistent with the field-data API.
  • create_empty_array is a nice NumPy-first touch. It returns None silently if the zone or variable is missing.
  • set_data doesn't check the dtype: it looks up solution_variable_data.dtype.type in a mapping. A Python list, or an ndarray of an unsupported dtype (for example float16), fails with an unclear error. A shape or size check against the zone count would also help. Use np.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 concat copies 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}), and get_monitor_set_plot(), which returns df.plot. There is no public to_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 columns surface, 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_*() on SurfaceData, PathlinesData, Data or Mesh.
  • 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

  1. Vectorize get_mesh (array-backed Mesh, ID remapping in NumPy). This is likely the largest win, though it hasn't been measured. Ideally also move the server to byte payloads.
  2. Fix the monitor DataFrame build-up: list or buffer append, a lazy DataFrame, and a public to_dataframe().
  3. Byte-payload writes for set_data, plus dtype and size validation via np.asarray.
  4. 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.
  5. Interop adapters, kept optional and lazily imported: SurfaceData.to_pyvista(), to_dataframe() on field-data results and SVAR Data, maybe to_xarray().
  6. 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.
Lingua principale
Python
Stelle
550
Fork
86
Merge medio
2g 1h
PR unite (30g)
58

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di ansys/pyfluent

Tutte le issue di ansys/pyfluent

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.