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

521 to_vtk #527

Merged
merged 4 commits into from
Jun 4, 2024
Merged

521 to_vtk #527

merged 4 commits into from
Jun 4, 2024

Conversation

samjrholt
Copy link
Member

@samjrholt samjrholt commented May 8, 2024

User description

Make to_vtk work with different dim names.


PR Type

enhancement, tests


Description

  • Enhanced the to_vtk method in discretisedfield.Field to only allow conversion of 3D fields and dynamically handle dimension names based on mesh.region.dims.
  • Added comprehensive tests for the to_vtk method, ensuring it handles fields with both standard and custom dimension names correctly.

Changes walkthrough 📝

Relevant files
Enhancement
field.py
Enhance `to_vtk` to Support Dynamic Dimension Names           

discretisedfield/field.py

  • Restrict to_vtk conversion to only 3D fields.
  • Adapt coordinate retrieval to use dynamic dimension names from
    mesh.region.dims.
  • +19/-4   
    Tests
    test_field.py
    Add Tests for `to_vtk` Method with Dynamic Dimensions       

    discretisedfield/tests/test_field.py

  • Added a new test test_to_vtk to verify the conversion of fields to VTK
    format.
  • Extended testing to handle fields with custom dimension names.
  • +44/-0   

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @samjrholt samjrholt requested a review from lang-m May 8, 2024 18:26
    @samjrholt samjrholt linked an issue May 8, 2024 that may be closed by this pull request
    Copy link
    Contributor

    github-actions bot commented May 8, 2024

    PR Description updated to latest commit (ad79700)

    Copy link
    Contributor

    github-actions bot commented May 8, 2024

    PR Review 🔍

    ⏱️ Estimated effort to review [1-5]

    2, because the changes are localized to specific methods in a single file and are well-documented with a clear description of the enhancements. The addition of tests also helps in understanding the impact of these changes.

    🧪 Relevant tests

    Yes

    ⚡ Possible issues

    Possible Bug: The to_vtk method assumes that mesh.region.dims will always have exactly three dimensions. If not, this could lead to errors or unexpected behavior.

    🔒 Security concerns

    No

    Code feedback:
    relevant filediscretisedfield/field.py
    suggestion      

    Consider adding a check to ensure that mesh.region.dims contains exactly three dimensions before proceeding with the conversion. This would prevent potential runtime errors if the dimensions are not as expected. [important]

    relevant linecan be converted. The ``x``, ``y``, and ``z``, spatial coordinates of

    relevant filediscretisedfield/field.py
    suggestion      

    To improve code readability and maintainability, consider refactoring the repeated code for setting coordinates into a loop or a helper function. This change would make the code cleaner and easier to manage if modifications are needed in the future. [medium]

    relevant linevns.numpy_to_vtk(

    Copy link
    Contributor

    github-actions bot commented May 8, 2024

    PR Code Suggestions ✨

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Add a check for the 'nvdim' attribute to ensure it is set before converting to VTK.

    Consider adding a check to ensure that the nvdim attribute is properly set before
    proceeding with the conversion to VTK format. This will prevent potential errors or
    undefined behavior if nvdim is not set or incorrectly set.

    discretisedfield/field.py [3384-3386]

    +if not hasattr(self, 'nvdim'):
    +    raise ValueError("The 'nvdim' attribute must be set to convert to VTK format.")
     Scalar fields (``nvdim=1``)
     contain one VTK array called ``field``. Vector fields (``nvdim>1``)
     contain one VTK array called ``field`` containing vector data and
     
    Enhance the test_to_vtk function by adding assertions to verify the data in the VTK arrays.

    To ensure the robustness of the test_to_vtk function, add assertions to check the
    correctness of the data in the VTK arrays, not just their names.

    discretisedfield/tests/test_field.py [2811-2815]

     assert cell_data.GetArrayName(0) == "norm"
    +assert np.allclose(cell_data.GetArray(0).GetTuple(0), expected_norm_values)
     assert cell_data.GetArrayName(1) == "x"
    +assert np.allclose(cell_data.GetArray(1).GetTuple(0), expected_x_values)
     assert cell_data.GetArrayName(2) == "y"
    +assert np.allclose(cell_data.GetArray(2).GetTuple(0), expected_y_values)
     assert cell_data.GetArrayName(3) == "z"
    +assert np.allclose(cell_data.GetArray(3).GetTuple(0), expected_z_values)
     assert cell_data.GetArrayName(4) == "field"
    +assert np.allclose(cell_data.GetArray(4).GetTuple(0), expected_field_values)
     
    Maintainability
    Use a loop to set X, Y, and Z coordinates to enhance code readability and maintainability.

    To improve code readability and maintainability, consider using a loop to set the
    coordinates instead of repeating similar code blocks for X, Y, and Z coordinates.

    discretisedfield/field.py [3426-3445]

    -rgrid.SetXCoordinates(
    -    vns.numpy_to_vtk(
    -        np.fromiter(
    -            getattr(self.mesh.vertices, self.mesh.region.dims[0]), float
    -        )
    -    )
    -)
    -rgrid.SetYCoordinates(
    -    vns.numpy_to_vtk(
    -        np.fromiter(
    -            getattr(self.mesh.vertices, self.mesh.region.dims[1]), float
    -        )
    -    )
    -)
    -rgrid.SetZCoordinates(
    -    vns.numpy_to_vtk(
    -        np.fromiter(
    -            getattr(self.mesh.vertices, self.mesh.region.dims[2]), float
    -        )
    -    )
    -)
    +for dim, setter in zip(self.mesh.region.dims, [rgrid.SetXCoordinates, rgrid.SetYCoordinates, rgrid.SetZCoordinates]):
    +    setter(vns.numpy_to_vtk(np.fromiter(getattr(self.mesh.vertices, dim), float)))
     
    Bug
    Add error handling for fields with dimensions other than 3 in the to_vtk method.

    Ensure that the to_vtk method handles cases where the field dimension (ndim) is not equal
    to 3, either by raising an exception or providing a fallback mechanism.

    discretisedfield/field.py [3381]

    +if self.ndim != 3:
    +    raise ValueError("Only fields with ndim=3 can be converted to VTK format.")
     Only fields with ``ndim=3``
     can be converted.
     
    Possible issue
    Add checks to ensure the existence of required attributes in mesh.vertices before accessing them.

    To avoid potential issues with attribute access, use a more robust method to check for the
    existence of mesh.vertices attributes based on mesh.region.dims.

    discretisedfield/field.py [3429-3443]

    +for dim in self.mesh.region.dims:
    +    if not hasattr(self.mesh.vertices, dim):
    +        raise AttributeError(f"Mesh vertices do not have the dimension '{dim}'")
     getattr(self.mesh.vertices, self.mesh.region.dims[0]), float
     getattr(self.mesh.vertices, self.mesh.region.dims[1]), float
     getattr(self.mesh.vertices, self.mesh.region.dims[2]), float
     

    Copy link

    codecov bot commented May 9, 2024

    Codecov Report

    All modified and coverable lines are covered by tests ✅

    Project coverage is 93.39%. Comparing base (f1b4cda) to head (d0cf601).
    Report is 86 commits behind head on master.

    Additional details and impacted files
    @@            Coverage Diff             @@
    ##           master     #527      +/-   ##
    ==========================================
    - Coverage   93.48%   93.39%   -0.10%     
    ==========================================
      Files          28       31       +3     
      Lines        3025     3286     +261     
    ==========================================
    + Hits         2828     3069     +241     
    - Misses        197      217      +20     

    ☔ View full report in Codecov by Sentry.
    📢 Have feedback on the report? Share it here.

    @samjrholt samjrholt merged commit d975a20 into master Jun 4, 2024
    9 of 10 checks passed
    @samjrholt samjrholt deleted the 521-to_vtk branch June 4, 2024 08:53
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    to_vtk()
    1 participant