Skip to content
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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft

Vtk #944

wants to merge 2 commits into from

Conversation

nicolasaunai
Copy link
Member

@nicolasaunai nicolasaunai commented Jan 27, 2025

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.

Copy link

coderabbitai bot commented Jan 27, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a new Python script in the pyphare/pyphare/pharesee/tovtk.py file for converting PHARE HDF5 files to VTKHDF format. The script provides functionality to transform electromagnetic field data from Yee grid to a flat primal format. It includes functions for processing magnetic and electric field components, extracting patch bounding boxes, calculating node numbers, and a main function that manages the file conversion process, handling multiple time steps and levels of data.

Changes

File Change Summary
pyphare/pyphare/pharesee/tovtk.py Added multiple functions:
- BtoFlatPrimal: Converts magnetic field components to flat primal format
- EtoFlatPrimal: Converts electric field components to flat primal format
- primalScalarToFlatPrimal: Converts scalar data to flat primal format
- primalVectorToFlatPrimal: Converts vector data to flat primal format
- boxFromPatch: Extracts bounding box from a patch
- nbrNodes: Calculates number of nodes based on box dimensions
- primalFlattener: Determines conversion function based on diagnostic filename
- max_nbr_levels_in: Retrieves maximum number of levels in the data
- times_in: Retrieves time steps from the HDF5 file
- is_vector_data: Checks if data is vector
- main: Orchestrates HDF5 to VTKHDF file conversion

Sequence Diagram

sequenceDiagram
    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
Loading

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
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

AMRBoxOffsets = []
dataOffsets = []

cellData_g = lvl.create_group("CellData")

Check notice

Code scanning / CodeQL

Unused local variable Note

Variable cellData_g is not used.

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

Variable fieldData_g is not used.
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

Variable cellDataOffset_g is not used.
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

Variable FieldDataOffset_g is not used.
Copy link

@coderabbitai coderabbitai bot left a 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:

  1. Docstring explaining the input parameters and return value
  2. Mathematical explanation of the averaging operations
  3. 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 of key not in dict.keys()

Remove .keys()

(SIM118)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ce77d6b and fde2af2.

📒 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 f

Length 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 2

Length of output: 4385

Comment on lines +163 to +215
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")

Copy link

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.

Suggested change
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)

Comment on lines 94 to 98
def main():

path = sys.argv[1]
phare_h5 = h5py.File(path, "r")
times_str = list(phare_h5["t"].keys())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

Suggested change
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())

Copy link

@coderabbitai coderabbitai bot left a 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 and EtoFlatPrimal 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 result

Also 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 points

Also 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

📥 Commits

Reviewing files that changed from the base of the PR and between fde2af2 and 874c684.

📒 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, and FieldDataOffset_g.

🧰 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)


94-97: Add error handling for command-line arguments.

The script assumes the input path is always provided and valid.

pointData_b[current_size:, :] = data
# pass

current_size += b.shape[0]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

Suggested change
current_size += b.shape[0]
current_size += data.shape[0]
🧰 Tools
🪛 Ruff (0.8.2)

223-223: Undefined name b

(F821)

Comment on lines +79 to +106
def boxFromPatch(patch):
lower = patch.attrs["lower"]
upper = patch.attrs["upper"]
return [lower[0], upper[0], lower[1], upper[1], 0, 0] # 2D

Copy link

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
Copy link

@coderabbitai coderabbitai bot left a 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 an IndexError 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 of key 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

📥 Commits

Reviewing files that changed from the base of the PR and between 874c684 and d9f1328.

📒 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, and FieldDataOffset_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 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)

Copy link

@coderabbitai coderabbitai bot left a 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 suggestion

Hardcoded 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 suggestion

Potential uninitialized variable risk

The toFlatPrimal variable might be uninitialized if primalFlattener raises a ValueError. 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 operation

In primalVectorToFlatPrimal, line 95-97 applies flatten(order="F") to arrays that are already flattened by the primalScalarToFlatPrimal 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 check

The 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 of key not in dict.keys()

Remove .keys()

(SIM118)


275-276: Unnecessary commented code

There'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 code

Another 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 typo

There'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

📥 Commits

Reviewing files that changed from the base of the PR and between d9f1328 and 69c2531.

📒 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 technique

The 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 handling

The added input validation for command-line arguments is a good improvement from the previous version.


218-223: Remove unused group variables

Several HDF5 group variables are created but never used: cellData_g, fieldData_g, cellDataOffset_g, and FieldDataOffset_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 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)


316-317: Script entrypoint looks good

The 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:

  1. The slicing operations only work with 2D data
  2. 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]
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant