-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Vtk #944
base: master
Are you sure you want to change the base?
Vtk #944
Conversation
📝 WalkthroughWalkthroughThe pull request introduces a new Python script in the Changes
Sequence DiagramsequenceDiagram
participant Input as HDF5 Input File
participant Converter as tovtk.py
participant Output as VTKHDF Output File
Input->>Converter: Read HDF5 File
Converter->>Converter: Extract Time Steps
Converter->>Converter: Process Magnetic Fields
Converter->>Converter: Process Electric Fields
Converter->>Output: Write Converted Data
The sequence diagram illustrates the high-level conversion process from HDF5 to VTKHDF, showing how the script reads the input file, processes magnetic and electric fields, and writes the converted data to the output file. ✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
AMRBoxOffsets = [] | ||
dataOffsets = [] | ||
|
||
cellData_g = lvl.create_group("CellData") |
Check notice
Code scanning / CodeQL
Unused local variable Note
|
||
cellData_g = lvl.create_group("CellData") | ||
pointData_g = lvl.create_group("PointData") | ||
fieldData_g = lvl.create_group("FieldData") |
Check notice
Code scanning / CodeQL
Unused local variable Note
cellData_g = lvl.create_group("CellData") | ||
pointData_g = lvl.create_group("PointData") | ||
fieldData_g = lvl.create_group("FieldData") | ||
cellDataOffset_g = steps_lvl.create_group("CellDataOffset") |
Check notice
Code scanning / CodeQL
Unused local variable Note
fieldData_g = lvl.create_group("FieldData") | ||
cellDataOffset_g = steps_lvl.create_group("CellDataOffset") | ||
pointDataOffset_g = steps_lvl.create_group("PointDataOffset") | ||
FieldDataOffset_g = steps_lvl.create_group("FieldDataOffset") |
Check notice
Code scanning / CodeQL
Unused local variable Note
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (4)
pyphare/pyphare/pharesee/tovtk.py (4)
11-43
: Add detailed documentation for the Yee grid to primal conversion.The function performs complex averaging operations to convert from Yee grid to primal format. Consider adding:
- Docstring explaining the input parameters and return value
- Mathematical explanation of the averaging operations
- Documentation about the 2D to 3D conversion strategy
Here's a suggested docstring:
def BtoFlatPrimal(ph_bx, ph_by, ph_bz, npx, npy, npz, gn=2): + """Convert magnetic field components from Yee grid to flat primal format. + + Args: + ph_bx, ph_by, ph_bz: Magnetic field components on Yee grid + npx, npy, npz: Number of points in each dimension + gn: Number of ghost nodes (default=2) + + Returns: + numpy.ndarray: Flattened magnetic field in primal format (nbrPoints, 3) + """
45-77
: Maintain documentation consistency with BtoFlatPrimal.The function has good inline comments but would benefit from the same level of documentation as suggested for BtoFlatPrimal.
Here's a suggested docstring:
def EtoFlatPrimal(ph_ex, ph_ey, ph_ez, npx, npy, npz, gn=2): + """Convert electric field components from Yee grid to flat primal format. + + Args: + ph_ex, ph_ey, ph_ez: Electric field components on Yee grid + npx, npy, npz: Number of points in each dimension + gn: Number of ghost nodes (default=2) + + Returns: + numpy.ndarray: Flattened electric field in primal format (nbrPoints, 3) + """
79-83
: Remove hardcoded 2D assumption.The function hardcodes a 2D case by setting z-coordinates to 0. Consider making it dimension-agnostic for future extensibility.
def boxFromPatch(patch): + """Extract bounding box from patch attributes. + + Args: + patch: HDF5 group containing patch data + + Returns: + list: [x_min, x_max, y_min, y_max, z_min, z_max] + """ lower = patch.attrs["lower"] upper = patch.attrs["upper"] - return [lower[0], upper[0], lower[1], upper[1], 0, 0] # 2D + # Handle both 2D and 3D cases + z_min = lower[2] if len(lower) > 2 else 0 + z_max = upper[2] if len(upper) > 2 else 0 + return [lower[0], upper[0], lower[1], upper[1], z_min, z_max]
185-188
: Optimize dictionary key check.Use
not in
operator directly on the dictionary instead of calling.keys()
.- if phare_lvl_name not in phare_h5["t"][time_str].keys(): + if phare_lvl_name not in phare_h5["t"][time_str]: print(f"no level {ilvl} at time {time}") continue🧰 Tools
🪛 Ruff (0.8.2)
185-185: Use
key not in dict
instead ofkey not in dict.keys()
Remove
.keys()
(SIM118)
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
pyphare/pyphare/pharesee/tovtk.py
(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
pyphare/pyphare/pharesee/tovtk.py
163-163: Local variable cellData_g
is assigned to but never used
Remove assignment to unused variable cellData_g
(F841)
165-165: Local variable fieldData_g
is assigned to but never used
Remove assignment to unused variable fieldData_g
(F841)
166-166: Local variable cellDataOffset_g
is assigned to but never used
Remove assignment to unused variable cellDataOffset_g
(F841)
168-168: Local variable FieldDataOffset_g
is assigned to but never used
Remove assignment to unused variable FieldDataOffset_g
(F841)
185-185: Use key not in dict
instead of key not in dict.keys()
Remove .keys()
(SIM118)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: build (macos-latest)
- GitHub Check: Analyze (cpp)
- GitHub Check: build (macos-14)
- GitHub Check: build (macos-13)
- GitHub Check: Analyze (python)
- GitHub Check: build (ubuntu-latest)
🔇 Additional comments (2)
pyphare/pyphare/pharesee/tovtk.py (2)
1-9
: LGTM! Imports are appropriate.The necessary imports for HDF5 handling, numerical operations, and system operations are present.
85-91
: Document the reason for adding 1 twice.The function adds 1 twice to each dimension when calculating the number of nodes. This needs explanation.
def nbrNodes(box): + """Calculate number of nodes in each dimension. + + Args: + box: List containing [x_min, x_max, y_min, y_max, z_min, z_max] + + Returns: + tuple: (npx, npy, npz) number of nodes in each dimension + """ lower = box[0], box[2], box[4] upper = box[1], box[3], box[5] + # Adding 1 for converting from cell count to node count + # and another 1 for including the end point npx = upper[0] - lower[0] + 1 + 1 npy = upper[1] - lower[1] + 1 + 1 npz = upper[2] - lower[2] + 1 + 1✅ Verification successful
Documentation accurately explains the double +1 addition
The double addition of 1 is correct and well-documented. The first +1 converts from cell count to node count (as there's always one more node than cells), and the second +1 ensures the endpoint is included, which is required for VTK format compatibility.
🏁 Scripts executed
The following scripts were executed for the analysis:
Error: No shell scripts found
Script:
#!/bin/bash # Search for usages of nbrNodes function rg "nbrNodes" -B 2 -A 2 # Search for similar grid calculations with double +1 pattern rg "([^+]\+\s*1\s*\+\s*1)" -B 2 -A 2 # Look for grid/mesh related files and documentation fd "grid|mesh" --type fLength of output: 3453
Script:
#!/bin/bash # Search for VTK-related code and documentation rg -g "*.py" -g "*.hpp" -g "*.cpp" "vtk|VTK" -B 2 -A 2 # Search for toFlatPrimal implementation rg "toFlatPrimal" -B 5 -A 5 # Search for any documentation about grid/node conversion rg -g "*.py" -g "*.md" "grid.*node|node.*grid" -B 2 -A 2Length of output: 4385
cellData_g = lvl.create_group("CellData") | ||
pointData_g = lvl.create_group("PointData") | ||
fieldData_g = lvl.create_group("FieldData") | ||
cellDataOffset_g = steps_lvl.create_group("CellDataOffset") | ||
pointDataOffset_g = steps_lvl.create_group("PointDataOffset") | ||
FieldDataOffset_g = steps_lvl.create_group("FieldDataOffset") | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove or document unused group variables.
Several group variables are created but never used: cellData_g
, fieldData_g
, cellDataOffset_g
, and FieldDataOffset_g
. Either remove them or document their intended future use.
- cellData_g = lvl.create_group("CellData")
pointData_g = lvl.create_group("PointData")
- fieldData_g = lvl.create_group("FieldData")
- cellDataOffset_g = steps_lvl.create_group("CellDataOffset")
pointDataOffset_g = steps_lvl.create_group("PointDataOffset")
- FieldDataOffset_g = steps_lvl.create_group("FieldDataOffset")
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
cellData_g = lvl.create_group("CellData") | |
pointData_g = lvl.create_group("PointData") | |
fieldData_g = lvl.create_group("FieldData") | |
cellDataOffset_g = steps_lvl.create_group("CellDataOffset") | |
pointDataOffset_g = steps_lvl.create_group("PointDataOffset") | |
FieldDataOffset_g = steps_lvl.create_group("FieldDataOffset") | |
pointData_g = lvl.create_group("PointData") | |
pointDataOffset_g = steps_lvl.create_group("PointDataOffset") |
🧰 Tools
🪛 Ruff (0.8.2)
163-163: Local variable cellData_g
is assigned to but never used
Remove assignment to unused variable cellData_g
(F841)
165-165: Local variable fieldData_g
is assigned to but never used
Remove assignment to unused variable fieldData_g
(F841)
166-166: Local variable cellDataOffset_g
is assigned to but never used
Remove assignment to unused variable cellDataOffset_g
(F841)
168-168: Local variable FieldDataOffset_g
is assigned to but never used
Remove assignment to unused variable FieldDataOffset_g
(F841)
pyphare/pyphare/pharesee/tovtk.py
Outdated
def main(): | ||
|
||
path = sys.argv[1] | ||
phare_h5 = h5py.File(path, "r") | ||
times_str = list(phare_h5["t"].keys()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add error handling for command-line arguments.
The script assumes the input path is always provided and valid. Add proper error handling.
def main():
+ if len(sys.argv) != 2:
+ print("Usage: python tovtk.py <input_h5_file>")
+ sys.exit(1)
+
path = sys.argv[1]
+ if not os.path.exists(path):
+ print(f"Error: File {path} does not exist")
+ sys.exit(1)
+
phare_h5 = h5py.File(path, "r")
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
def main(): | |
path = sys.argv[1] | |
phare_h5 = h5py.File(path, "r") | |
times_str = list(phare_h5["t"].keys()) | |
def main(): | |
if len(sys.argv) != 2: | |
print("Usage: python tovtk.py <input_h5_file>") | |
sys.exit(1) | |
path = sys.argv[1] | |
if not os.path.exists(path): | |
print(f"Error: File {path} does not exist") | |
sys.exit(1) | |
phare_h5 = h5py.File(path, "r") | |
times_str = list(phare_h5["t"].keys()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (5)
pyphare/pyphare/pharesee/tovtk.py (5)
5-8
: Add type hints and docstrings to improve code maintainability.Consider adding type hints and docstrings to all functions to improve code maintainability and IDE support. This will help other developers understand the expected input/output types and function purposes.
Example for the
BtoFlatPrimal
function:-def BtoFlatPrimal(ph_bx, ph_by, ph_bz, npx, npy, npz, gn=2): +from typing import Tuple, ndarray + +def BtoFlatPrimal( + ph_bx: ndarray, + ph_by: ndarray, + ph_bz: ndarray, + npx: int, + npy: int, + npz: int, + gn: int = 2 +) -> ndarray: + """Convert magnetic field components from Yee grid to flat primal format. + + Args: + ph_bx: X-component of magnetic field on Yee grid + ph_by: Y-component of magnetic field on Yee grid + ph_bz: Z-component of magnetic field on Yee grid + npx: Number of points in X direction + npy: Number of points in Y direction + npz: Number of points in Z direction + gn: Number of ghost nodes (default: 2) + + Returns: + ndarray: Flattened magnetic field components in primal format + """Also applies to: 11-11, 45-45, 79-79, 85-85, 94-94
11-43
: Consider refactoring field conversion functions to reduce code duplication.The
BtoFlatPrimal
andEtoFlatPrimal
functions share similar structure. Consider extracting common logic into a base function.Example refactor:
def _toFlatPrimal(components: dict, npx: int, npy: int, npz: int, gn: int = 2) -> ndarray: """Base function for converting field components to flat primal format. Args: components: Dictionary containing field components and their averaging rules npx, npy, npz: Number of points in each direction gn: Number of ghost nodes """ nbrPoints = npx * npy * npz result = np.zeros((nbrPoints, 3), dtype="f") # Create pure primal arrays primal = {k: np.zeros((npx, npy, npz), dtype=np.float32) for k in components} # Convert each component using its averaging rule for k, (data, rule) in components.items(): primal[k][:, :, 0] = rule(data, gn) primal[k][:, :, 1] = primal[k][:, :, 0] # Copy to z-dimension # Flatten to output format for i, k in enumerate(components): result[:, i] = primal[k].flatten(order="F") return resultAlso applies to: 45-77
21-32
: Add detailed comments explaining the Yee grid to primal conversion process.The ghost node handling and averaging process in the dual direction needs better documentation. Also, document that this implementation assumes 2D data.
Add comments like:
# In Yee grid, B-field components are staggered: # Bx is defined at (i, j+1/2, k+1/2) # By is defined at (i+1/2, j, k+1/2) # Bz is defined at (i+1/2, j+1/2, k) # We average in the dual direction to get values at the primal grid pointsAlso applies to: 55-66
85-91
: Document the node number calculation logic.The function adds 1 twice to each dimension. Add comments explaining why this is necessary (e.g., if it's related to cell-centered vs node-centered data).
def nbrNodes(box): + """Calculate number of nodes in each dimension. + + The +1 is added twice because: + 1. Convert from cell count to node count (+1) + 2. [Explain the second +1 here] + """
111-113
: Use os.path.join for path construction.Replace string concatenation with
os.path.join
for more robust path handling across different operating systems.- vtk_fn = f"{data_directory}/{phare_fn}.vtkhdf" + vtk_fn = os.path.join(data_directory, f"{phare_fn}.vtkhdf")
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
pyphare/pyphare/pharesee/tovtk.py
(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
pyphare/pyphare/pharesee/tovtk.py
163-163: Local variable cellData_g
is assigned to but never used
Remove assignment to unused variable cellData_g
(F841)
165-165: Local variable fieldData_g
is assigned to but never used
Remove assignment to unused variable fieldData_g
(F841)
166-166: Local variable cellDataOffset_g
is assigned to but never used
Remove assignment to unused variable cellDataOffset_g
(F841)
168-168: Local variable FieldDataOffset_g
is assigned to but never used
Remove assignment to unused variable FieldDataOffset_g
(F841)
185-185: Use key not in dict
instead of key not in dict.keys()
Remove .keys()
(SIM118)
223-223: Undefined name b
(F821)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: build (macos-latest)
- GitHub Check: build (macos-14)
- GitHub Check: Analyze (cpp)
- GitHub Check: build (macos-13)
- GitHub Check: build (ubuntu-latest)
- GitHub Check: Analyze (python)
🔇 Additional comments (2)
pyphare/pyphare/pharesee/tovtk.py (2)
163-168
: Remove unused group variables or document their future use.Several group variables are created but never used:
cellData_g
,fieldData_g
,cellDataOffset_g
, andFieldDataOffset_g
.🧰 Tools
🪛 Ruff (0.8.2)
163-163: Local variable
cellData_g
is assigned to but never usedRemove assignment to unused variable
cellData_g
(F841)
165-165: Local variable
fieldData_g
is assigned to but never usedRemove assignment to unused variable
fieldData_g
(F841)
166-166: Local variable
cellDataOffset_g
is assigned to but never usedRemove assignment to unused variable
cellDataOffset_g
(F841)
168-168: Local variable
FieldDataOffset_g
is assigned to but never usedRemove assignment to unused variable
FieldDataOffset_g
(F841)
94-97
: Add error handling for command-line arguments.The script assumes the input path is always provided and valid.
pyphare/pyphare/pharesee/tovtk.py
Outdated
pointData_b[current_size:, :] = data | ||
# pass | ||
|
||
current_size += b.shape[0] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix undefined variable reference.
Line 223 uses undefined variable b
instead of data
.
- current_size += b.shape[0]
+ current_size += data.shape[0]
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
current_size += b.shape[0] | |
current_size += data.shape[0] |
🧰 Tools
🪛 Ruff (0.8.2)
223-223: Undefined name b
(F821)
def boxFromPatch(patch): | ||
lower = patch.attrs["lower"] | ||
upper = patch.attrs["upper"] | ||
return [lower[0], upper[0], lower[1], upper[1], 0, 0] # 2D | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Hardcoded 2D assumption in boxFromPatch needs to be fixed
The codebase has infrastructure for handling 3D data (as seen in core/box.py
), but boxFromPatch
in tovtk.py
artificially limits functionality by hardcoding z=0. This should be modified to handle the z-dimension when present.
- Consider extracting z-coordinates from patch.attrs when available:
lower[2], upper[2]
- Add dimension detection to support both 2D and 3D cases
🔗 Analysis chain
Validate 2D assumption in boxFromPatch function.
The function hardcodes z-dimension to 0, assuming 2D data. Consider validating this assumption or making it configurable for future 3D support.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if there are any 3D data files in the codebase
rg -l "upper\[2\]|lower\[2\]" --type py
Length of output: 167
Script:
#!/bin/bash
# Check Box class implementation and usage
ast-grep --pattern 'class Box' pyphare/pyphare/core/box.py
rg -A 5 "upper\[2\]|lower\[2\]" pyphare/pyphare/core/box.py
Length of output: 554
works for E, B, n, V 2D
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
pyphare/pyphare/pharesee/tovtk.py (4)
102-106
: Consider providing 3D support instead of hardcoding 2D bounds.Currently,
boxFromPatch
returns[lower[0], upper[0], lower[1], upper[1], 0, 0]
, artificially fixing the z-dimension to 0. If you eventually need 3D support, expand the function to handle[lower[2], upper[2]]
, or otherwise clarify its 2D-only intent.
155-158
: Validate and handle missing command-line arguments.Relying on
sys.argv[1]
may cause anIndexError
if no arguments are passed. Adding a simple argument-count check and verifying file existence can prevent runtime errors.def main(): + if len(sys.argv) < 2: + print("Usage: python tovtk.py <input_h5_file>") + sys.exit(1) path = sys.argv[1] + if not os.path.isfile(path): + print(f"Error: File '{path}' does not exist") + sys.exit(1) phare_h5 = h5py.File(path, "r")
231-231
: Use dict membership directly instead of calling.keys()
.Improve readability and conform to Python best practices by removing redundant
.keys()
.- if phare_lvl_name not in phare_h5["t"][time_str].keys(): + if phare_lvl_name not in phare_h5["t"][time_str]:🧰 Tools
🪛 Ruff (0.8.2)
231-231: Use
key not in dict
instead ofkey not in dict.keys()
Remove
.keys()
(SIM118)
297-302
: Clarify the dataset shape comment for scalar data.This comment mentions “shape (current_size, 3)” but in the scalar path, the dataset is actually 1D with shape
(current_size,)
. Updating the comment ensures consistency and avoids confusion.- # dataset already created with shape (current_size,3) + # dataset already created with shape (current_size,) for scalar fields
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
pyphare/pyphare/pharesee/tovtk.py
(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
pyphare/pyphare/pharesee/tovtk.py
209-209: Local variable cellData_g
is assigned to but never used
Remove assignment to unused variable cellData_g
(F841)
211-211: Local variable fieldData_g
is assigned to but never used
Remove assignment to unused variable fieldData_g
(F841)
212-212: Local variable cellDataOffset_g
is assigned to but never used
Remove assignment to unused variable cellDataOffset_g
(F841)
214-214: Local variable FieldDataOffset_g
is assigned to but never used
Remove assignment to unused variable FieldDataOffset_g
(F841)
231-231: Use key not in dict
instead of key not in dict.keys()
Remove .keys()
(SIM118)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: Analyze (cpp)
- GitHub Check: Analyze (python)
- GitHub Check: build (macos-14)
- GitHub Check: build (macos-13)
- GitHub Check: build (macos-latest)
- GitHub Check: build (ubuntu-latest)
🔇 Additional comments (1)
pyphare/pyphare/pharesee/tovtk.py (1)
209-214
: Remove or document the unused group variables.Variables
cellData_g
,fieldData_g
,cellDataOffset_g
, andFieldDataOffset_g
are assigned but never used. They can be removed to reduce clutter or documented if you plan to use them in the future.- cellData_g = lvl.create_group("CellData") pointData_g = lvl.create_group("PointData") - fieldData_g = lvl.create_group("FieldData") - cellDataOffset_g = steps_lvl.create_group("CellDataOffset") pointDataOffset_g = steps_lvl.create_group("PointDataOffset") - FieldDataOffset_g = steps_lvl.create_group("FieldDataOffset")🧰 Tools
🪛 Ruff (0.8.2)
209-209: Local variable
cellData_g
is assigned to but never usedRemove assignment to unused variable
cellData_g
(F841)
211-211: Local variable
fieldData_g
is assigned to but never usedRemove assignment to unused variable
fieldData_g
(F841)
212-212: Local variable
cellDataOffset_g
is assigned to but never usedRemove assignment to unused variable
cellDataOffset_g
(F841)
214-214: Local variable
FieldDataOffset_g
is assigned to but never usedRemove assignment to unused variable
FieldDataOffset_g
(F841)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (2)
pyphare/pyphare/pharesee/tovtk.py (2)
102-106
: 🛠️ Refactor suggestionHardcoded 2D assumption in boxFromPatch needs to be fixed
The function artificially limits functionality by hardcoding z=0, making it incompatible with 3D data.
def boxFromPatch(patch): lower = patch.attrs["lower"] upper = patch.attrs["upper"] - return [lower[0], upper[0], lower[1], upper[1], 0, 0] # 2D + # Handle both 2D and 3D cases + if len(lower) > 2: # 3D case + return [lower[0], upper[0], lower[1], upper[1], lower[2], upper[2]] + else: # 2D case + return [lower[0], upper[0], lower[1], upper[1], 0, 0]
178-178
: 🛠️ Refactor suggestionPotential uninitialized variable risk
The
toFlatPrimal
variable might be uninitialized ifprimalFlattener
raises aValueError
. This was flagged in previous static analysis.- toFlatPrimal = primalFlattener(phare_fn) + try: + toFlatPrimal = primalFlattener(phare_fn) + except ValueError as e: + print(f"Error: {e}") + sys.exit(1)
🧹 Nitpick comments (5)
pyphare/pyphare/pharesee/tovtk.py (5)
79-100
: Vector flattening implementation has redundant flattening operationIn
primalVectorToFlatPrimal
, line 95-97 appliesflatten(order="F")
to arrays that are already flattened by theprimalScalarToFlatPrimal
function on lines 91-93.- v[:, 0] = vx.flatten(order="F") - v[:, 1] = vy.flatten(order="F") - v[:, 2] = vz.flatten(order="F") + v[:, 0] = vx + v[:, 1] = vy + v[:, 2] = vz
240-242
: Simplify dictionary key checkThe code can be simplified using Python's more idiomatic dictionary membership check.
- if phare_lvl_name not in phare_h5["t"][time_str].keys(): + if phare_lvl_name not in phare_h5["t"][time_str]:🧰 Tools
🪛 Ruff (0.8.2)
240-240: Use
key not in dict
instead ofkey not in dict.keys()
Remove
.keys()
(SIM118)
275-276
: Unnecessary commented codeThere's a commented
# pass
statement that should be removed.pointData.resize(current_size + data.shape[0], axis=0) pointData[current_size:, :] = data - # pass
298-298
: Unnecessary commented codeAnother commented
# pass
statement that should be removed.pointData.resize(current_size + data.shape[0], axis=0) pointData[current_size:] = data - # pass
303-303
: Fix comment typoThere's a minor typo in the comment.
- # of of the patch loops at that time + # end of the patch loops at that time
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
pyphare/pyphare/pharesee/tovtk.py
(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
pyphare/pyphare/pharesee/tovtk.py
218-218: Local variable cellData_g
is assigned to but never used
Remove assignment to unused variable cellData_g
(F841)
220-220: Local variable fieldData_g
is assigned to but never used
Remove assignment to unused variable fieldData_g
(F841)
221-221: Local variable cellDataOffset_g
is assigned to but never used
Remove assignment to unused variable cellDataOffset_g
(F841)
223-223: Local variable FieldDataOffset_g
is assigned to but never used
Remove assignment to unused variable FieldDataOffset_g
(F841)
240-240: Use key not in dict
instead of key not in dict.keys()
Remove .keys()
(SIM118)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: build (macos-14)
- GitHub Check: build (macos-latest)
- GitHub Check: build (macos-13)
- GitHub Check: Analyze (python)
- GitHub Check: Analyze (cpp)
- GitHub Check: build (ubuntu-latest)
🔇 Additional comments (5)
pyphare/pyphare/pharesee/tovtk.py (5)
45-76
: E field transformation uses the correct averaging techniqueThe function properly transforms E field components from Yee grid to primal nodes. The comment on line 65 correctly notes that Ez is already at primal nodes in 2D configuration, so no averaging is needed.
162-165
: Improved command-line argument handlingThe added input validation for command-line arguments is a good improvement from the previous version.
218-223
: Remove unused group variablesSeveral HDF5 group variables are created but never used:
cellData_g
,fieldData_g
,cellDataOffset_g
, andFieldDataOffset_g
. This was flagged in static analysis.- cellData_g = lvl.create_group("CellData") pointData_g = lvl.create_group("PointData") - fieldData_g = lvl.create_group("FieldData") - cellDataOffset_g = steps_lvl.create_group("CellDataOffset") pointDataOffset_g = steps_lvl.create_group("PointDataOffset") - FieldDataOffset_g = steps_lvl.create_group("FieldDataOffset")🧰 Tools
🪛 Ruff (0.8.2)
218-218: Local variable
cellData_g
is assigned to but never usedRemove assignment to unused variable
cellData_g
(F841)
220-220: Local variable
fieldData_g
is assigned to but never usedRemove assignment to unused variable
fieldData_g
(F841)
221-221: Local variable
cellDataOffset_g
is assigned to but never usedRemove assignment to unused variable
cellDataOffset_g
(F841)
223-223: Local variable
FieldDataOffset_g
is assigned to but never usedRemove assignment to unused variable
FieldDataOffset_g
(F841)
316-317
: Script entrypoint looks goodThe main function invocation is properly guarded by the
if __name__ == "__main__"
statement, which is a best practice.
11-42
:❓ Verification inconclusive
B field transformation logic looks correct but relies on 2D assumptions
The function is well-implemented for converting Yee grid B fields to primal nodes through averaging. However, the code only truly handles 2D data despite the 3D array structures, as seen in:
- The slicing operations only work with 2D data
- Lines 34-36 simply duplicate the same z-slice values
This approach works for the immediate 2D use case but will need refactoring to handle true 3D data in the future.
🏁 Script executed:
#!/bin/bash # Verify if there are any 3D electromagnetic field data in the codebase rg -l "3D" --glob "*.py" | grep -E "field|electromagnetic|B_|E_"Length of output: 64
Action: Confirm 2D Assumptions and Plan for 3D Support
The transformation logic in
pyphare/pyphare/pharesee/tovtk.py
is correctly implemented for converting Yee grid B fields to primal nodes using averaging. However, note that:
- The slicing operations and averaging are effectively handling 2D data.
- Lines 34–36 duplicate the same z-slice values, reinforcing the 2D-only assumption.
- To support true 3D electromagnetic fields in the future, this implementation will require refactoring.
Please manually verify if any parts of the codebase are intended for 3D field processing and consider future changes accordingly.
|
||
def level_spacing_from(root_spacing, ilvl): | ||
# hard-coded 2D adds 0 for last dim spacing | ||
return [dl / 2**ilvl for dl in root_spacing] + [0.0] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Hard-coded Z dimension spacing
The function explicitly adds a zero for Z dimension spacing, again showing the 2D-only assumption.
🏁 Script executed:
#!/bin/bash
# Check if there's any infrastructure for 3D data in the codebase
rg -A 3 --max-count=5 "3D" pyphare/
Length of output: 3031
Action Required: Address Hard-Coded Z Dimension Spacing
It looks like the function in pyphare/pyphare/pharesee/tovtk.py
(line 157) presently appends a 0.0
for the Z spacing:
return [dl / 2**ilvl for dl in root_spacing] + [0.0]
However, our codebase clearly supports 3D data (e.g., Box3D
in pyphare/pyphare/core/box.py
and the 3D logic in pyphare/pharein/simulation.py
and its tests). Hard-coding a zero for the Z spacing may lead to incorrect behavior when handling 3D datasets.
Recommendations:
- Update the spacing logic: Instead of always appending
0.0
, compute the Z dimension spacing appropriately when the application uses 3D data. - Conditional handling/documentation: If this function is intended only for 2D cases, add a clear assertion or document the 2D-only assumption to avoid confusion with the rest of the 3D-supportive codebase.
Just a quick and incomplete (just handles E and B) script to convert our data to vtkhdf and open it with paraview.
Just here as a way to learn paraview and decide whether it's a viable way for future diag formats.