PyFluent (`ansys-fluent-core`) and NumPy / pandas: source audit
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
- Ambito
- backend, data, performance
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.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.
- Lingua principale
- Python
- Stelle
- 550
- Fork
- 86
- Merge medio
- 2g 1h
- PR unite (30g)
- 58
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di ansys/pyfluent
-
documentation
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 70/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 65/100
ansys/pyfluent#5515 · 2 reazioni ·
I maintainer di solito rispondono entro 1 giorno
-
documentation
Difficoltà 2/5 1-3 ore Idoneità per principianti 62/100
I maintainer di solito rispondono entro 1 giorno
-
[DOC]: DOE_ML: Update the keras model definition to match the supported APIForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertadocumentation
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
[DOC]: Lunar Lander Outdated APIForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertadocumentation
Difficoltà 2/5 1-3 ore Idoneità per principianti 66/100
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di ansys/pyfluent
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 74/100
Pantheon-Security/medusa#24 ·
-
enhancement
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
docs(notation): the ipa_to_arpa section does not name the tied and non-syllabic diphthong formsAperta
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 88/100
TigreGotico/scriptconv#445 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
TigreGotico/phoonnx#1045 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 75/100
I maintainer di solito rispondono entro 2 giorni