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

WIP: testing datagraph with test data #235

Open
wants to merge 5 commits into
base: development
Choose a base branch
from

Conversation

JoshuaSiraj
Copy link
Collaborator

@JoshuaSiraj JoshuaSiraj commented Feb 21, 2025

Summary by CodeRabbit

  • New Features

    • Automatic data refresh is now enabled by default, ensuring end users benefit from the most up-to-date information without extra configuration.
    • Introduced new classes for managing and visualizing medical imaging series, enhancing the organization and querying of imaging data.
    • Added functionality to visualize the hierarchical structure of medical imaging data as an interactive network graph.
  • Refactor

    • Streamlined the data selection process to retain only essential components, enhancing overall data accuracy and performance.
  • Documentation

    • Revised configuration details to clearly reflect these improvements for easier interpretation.

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

📝 Walkthrough

Walkthrough

This pull request introduces updates to the DataGraph class in the src/imgtools/modules/datagraph.py file, changing the default value of the update parameter in the __init__ method from False to True. The _get_df method has been modified to use a keep_index list for component filtering instead of the previous remove_index list. Additionally, a new file src/imgtools/modules/interlacer.py has been added, which implements classes for managing and visualizing a hierarchical structure of medical imaging series.

Changes

File Change Summary
src/imgtools/modules/datagraph.py • Updated update parameter default in __init__ from False to True and modified its documentation.
• Replaced remove_index with keep_index in _get_df for filtering components.
• Applied minor formatting fixes in graph_query and _form_agg methods.
src/imgtools/modules/interlacer.py • Added classes SeriesNode, Branch, and Interlacer.
• Implemented methods for managing and visualizing a hierarchical structure of medical imaging series, including node management, querying, and visualization.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.

@JoshuaSiraj
Copy link
Collaborator Author

@jjjermiah

For a 'CT,SEG' query, it keeps a lot of empty unused columns:

Index(['patient_ID', 'study', 'study_description_x', 'series_CT',
       'series_description_x', 'subseries_CT', 'modality_x', 'instances_x',
       'instance_uid_x', 'reference_ct_x', 'reference_rs_x', 'reference_pl_x',
       'reference_frame_x', 'folder_CT', 'orientation_x', 'orientation_type_x',
       'MR_repetition_time_x', 'MR_echo_time_x', 'MR_scan_sequence_x',
       'MR_magnetic_field_strength_x', 'MR_imaged_nucleus_x', 'file_path_x',
       'series_SEG', 'subseries_SEG', 'modality_y', 'instances_y',
       'instance_uid_y', 'reference_ct_y', 'reference_rs_y', 'reference_pl_y',
       'reference_frame_y', 'folder_SEG', 'orientation_y',
       'orientation_type_y', 'MR_repetition_time_y', 'MR_echo_time_y',
       'MR_scan_sequence_y', 'MR_magnetic_field_strength_y',
       'MR_imaged_nucleus_y', 'file_path_y', 'edge_type'],
      dtype='object') 

Can I remove the ones not needed?

Copy link

codecov bot commented Feb 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 65.12%. Comparing base (d9a83d1) to head (d63961f).
Report is 1 commits behind head on development.

Additional details and impacted files
@@             Coverage Diff              @@
##           development     #235   +/-   ##
============================================
  Coverage        65.12%   65.12%           
============================================
  Files               55       55           
  Lines             3710     3710           
============================================
  Hits              2416     2416           
  Misses            1294     1294           

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

Copy link
Contributor

@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

🧹 Nitpick comments (4)
src/imgtools/modules/interlacer.py (4)

1-1: Remove unused import "time".
This import is never used in the code, so removing it improves cleanliness and eliminates any confusion.

- import time
🧰 Tools
🪛 Ruff (0.8.2)

1-1: time imported but unused

Remove unused import: time

(F401)


10-10: Add a class docstring for clarity.
Providing a short docstring at the class level helps future maintainers quickly understand what SeriesNode represents and how it should be used.


59-59: Consider using a standard dict instead of defaultdict.
Without a specified default factory, this behaves the same as a normal dict. It may be clearer to use dict unless you plan to leverage defaultdict features.


90-96: Evaluate performance of copying branches on each recursive call.
Using branch.copy() in a depth-first search can be costly for large trees. Consider alternative approaches (e.g., adding/removing from the branch list or building the result once the leaf is reached) to improve performance and memory usage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f32a7e1 and 81cb13e.

📒 Files selected for processing (1)
  • src/imgtools/modules/interlacer.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/**/*.py`: Review the Python code for compliance with PE...

src/**/*.py: Review the Python code for compliance with PEP 8 and PEP 257 (docstring conventions). Ensure the following: - Variables and functions follow meaningful naming conventions. - Docstrings are present, accurate, and align with the implementation. - Code is efficient and avoids redundancy while adhering to DRY principles. - Consider suggestions to enhance readability and maintainability. - Highlight any potential performance issues, edge cases, or logical errors. - Ensure all imported libraries are used and necessary.

  • src/imgtools/modules/interlacer.py
🪛 Ruff (0.8.2)
src/imgtools/modules/interlacer.py

1-1: time imported but unused

Remove unused import: time

(F401)


37-37: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Unit-Tests (windows-latest, py313)
  • GitHub Check: Unit-Tests (windows-latest, py312)
  • GitHub Check: Unit-Tests (windows-latest, py311)
  • GitHub Check: Unit-Tests (windows-latest, py310)
  • GitHub Check: Unit-Tests (macos-13, py313)
  • GitHub Check: Unit-Tests (macos-13, py312)
  • GitHub Check: Unit-Tests (macos-13, py311)
  • GitHub Check: Unit-Tests (macos-13, py310)
  • GitHub Check: Unit-Tests (macos-latest, py310)
  • GitHub Check: Unit-Tests (ubuntu-latest, py313)
  • GitHub Check: Unit-Tests (ubuntu-latest, py312)
  • GitHub Check: Unit-Tests (ubuntu-latest, py311)
  • GitHub Check: Unit-Tests (ubuntu-latest, py310)

Copy link
Contributor

@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

♻️ Duplicate comments (1)
src/imgtools/modules/interlacer.py (1)

35-37: ⚠️ Potential issue

Avoid using mutable default arguments.

Lists as default arguments can lead to unexpected behavior. It's safer to use None and initialize a new list inside the method.

+ from typing import Dict, List, Set, Optional

- def __init__(self, series_nodes: List[SeriesNode] = []):
+ def __init__(self, series_nodes: Optional[List[SeriesNode]] = None):
+     if series_nodes is None:
+         series_nodes = []
      self.series_nodes = series_nodes
🧰 Tools
🪛 Ruff (0.8.2)

35-35: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

🧹 Nitpick comments (8)
src/imgtools/modules/interlacer.py (8)

1-7: Consider adding a module-level docstring.

This module would benefit from a descriptive docstring at the beginning explaining its purpose, functionality, and how the classes relate to each other. This would help users understand the high-level purpose before diving into class details.


8-15: Improve attribute initialization with validation and more explicit type hints.

The current implementation dynamically sets attributes from row fields, which could make it difficult to track which attributes are available on each node. Consider:

  1. Adding explicit type annotations for commonly used attributes
  2. Adding validation for required fields
  3. Documenting the expected structure of the input row
+ from typing import Dict, List, Set, Any, Optional
  
  class SeriesNode():
-     def __init__(self, row: pd.Series):
+     def __init__(self, row: pd.Series):
+         """
+         Initialize a SeriesNode from a DataFrame row.
+         
+         Parameters
+         ----------
+         row : pd.Series
+             A row from a DataFrame containing at minimum 'Index', 'Modality', 
+             'PatientID', and 'ReferencedSeriesUID' fields.
+         """
          self.Series: str = row.Index 
          for field in row._fields[1:]:  # Skip "Index" (first field)
              setattr(self, field, getattr(row, field)) 
+         
+         # Validate required attributes
+         required_fields = ['Modality', 'PatientID']
+         for field in required_fields:
+             if not hasattr(self, field):
+                 raise ValueError(f"Required field '{field}' missing from row")

          self.children: List[SeriesNode] = []

16-19: Add type hints to add_child method.

The add_child method is missing parameter and return type annotations, which would improve code clarity and help with static analysis.

-     def add_child(self, child_node):
+     def add_child(self, child_node: 'SeriesNode') -> None:
          """Add SeriesNode to children"""
          self.children.append(child_node)

38-41: Add return type annotation to add_node method.

The method is missing a return type annotation. Adding one would improve code clarity.

-     def add_node(self, node: SeriesNode):
+     def add_node(self, node: SeriesNode) -> None:
          """Add a SeriesNode to the branch."""
          self.series_nodes.append(node)

79-85: Enhance error handling for edge cases in parent-child relationship building.

The current implementation assumes that referenced series will always exist in the forest. Consider adding more robust error handling and logging to handle cases where the reference doesn't exist.

      if modality in ["CT", "MR"] or (modality == "PT" and pd.isna(reference_series_uid)):
          self.root_nodes.append(node)

-     if pd.notna(reference_series_uid) and reference_series_uid in self.forest:
-         parent_node = self.forest[reference_series_uid]
-         parent_node.add_child(node)
+     if pd.notna(reference_series_uid):
+         if reference_series_uid in self.forest:
+             parent_node = self.forest[reference_series_uid]
+             parent_node.add_child(node)
+         else:
+             # Handle case where reference exists but is not in forest
+             print(f"Warning: Referenced series {reference_series_uid} not found in forest for {series_instance_uid}")

137-149: Consider simplifying the DataFrame creation logic.

The nested dictionary comprehension with multiple levels and conditions is complex. Consider breaking this down into more readable parts with intermediate variables.

-     data = [
-         {
-             'Patient_ID': branch.series_nodes[0].PatientID,  # Patient ID (same for all nodes)
-             **{
-                 f'{field}_{modality}': getattr(branch.get_modality_map().get(modality), field)
-                 for field in ['Series', 'folder']
-                 for modality in queried_modalities 
-             }
-         }
-         for branch in query_result
-     ]
+     data = []
+     fields_to_extract = ['Series', 'folder']
+     
+     for branch in query_result:
+         # Start with patient ID
+         branch_data = {'Patient_ID': branch.series_nodes[0].PatientID}
+         
+         # Get modality map once per branch
+         modality_map = branch.get_modality_map()
+         
+         # Add fields for each modality
+         for modality in queried_modalities:
+             if modality in modality_map:
+                 for field in fields_to_extract:
+                     branch_data[f'{field}_{modality}'] = getattr(modality_map[modality], field, None)
+             else:
+                 # Handle missing modalities gracefully
+                 for field in fields_to_extract:
+                     branch_data[f'{field}_{modality}'] = None
+                     
+         data.append(branch_data)

151-177: Make visualization more configurable and handle paths better.

The visualization method hardcodes the output filename and doesn't provide options for customization. Consider enhancing it:

-     def visualize_forest(self) -> None:
+     def visualize_forest(self, output_path: Optional[Path] = None, height: str = '800px', 
+                         width: str = '100%', physics_enabled: bool = True) -> Path:
          """
          Visualizes the forest of `SeriesNode` objects as an interactive network graph.

-         The visualization is saved as an HTML file (`forest_visualization.html`), displaying nodes 
+         The visualization is saved as an HTML file, displaying nodes 
          for each `SeriesNode` and edges representing parent-child relationships.
+         
+         Parameters
+         ----------
+         output_path : Path, optional
+             The path where the HTML file will be saved. If None, saves to the current
+             working directory with filename 'forest_visualization.html'.
+         height : str, default '800px'
+             Height of the visualization.
+         width : str, default '100%'
+             Width of the visualization.
+         physics_enabled : bool, default True
+             Whether to enable physics simulation in the visualization.
+             
+         Returns
+         -------
+         Path
+             The path to the saved HTML file.
          """
-         net = Network(height='800px', width='100%', notebook=False, directed=True)
+         net = Network(height=height, width=width, notebook=False, directed=True)

          def add_node_and_edges(node, parent=None):
              net.add_node(node.Series, label=node.Modality, title=node.Series)  # Display Series on click
              if parent:
                  net.add_edge(node.Series, parent.Series) 
              for child in node.children:
                  add_node_and_edges(child, node) 

          for root in self.root_nodes:
              add_node_and_edges(root)

          net.force_atlas_2based()
-         net.show_buttons(filter_=['physics'])
+         if physics_enabled:
+             net.show_buttons(filter_=['physics'])

-         save_path = Path.cwd() / 'forest_visualization.html'
+         if output_path is None:
+             save_path = Path.cwd() / 'forest_visualization.html'
+         else:
+             save_path = output_path
          save_path.parent.mkdir(parents=True, exist_ok=True)
          net.write_html(save_path.as_posix())

          print(f"Visualization saved at: {save_path}")
+         return save_path

99-108: Enhance _query method documentation and type safety.

The method uses set comparison with <= which may not be immediately clear. Consider enhancing the documentation and adding more explicit conditions.

-     def _query(self, queried_modalities: Set[str]) -> List[Branch]:
+     def _query(self, queried_modalities: Set[str]) -> List[Branch]:
          """Returns Branches that contain *all* specified modalities."""
+         """
+         Returns Branches that contain *all* specified modalities.
+         
+         The method uses set containment to find branches where all queried
+         modalities are present.
+         
+         Parameters
+         ----------
+         queried_modalities : Set[str]
+             Set of modality strings to query (e.g., {'CT', 'SEG'})
+             
+         Returns
+         -------
+         List[Branch]
+             List of branches containing all specified modalities
+         """
          result = []

          for branch in self.branches:
              present_modalities = {node.Modality for node in branch} 
-             if queried_modalities <= present_modalities:
+             # Check if all queried modalities are in this branch
+             if queried_modalities.issubset(present_modalities):
                  result.append(branch)

          return result
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81cb13e and d63961f.

📒 Files selected for processing (1)
  • src/imgtools/modules/interlacer.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/**/*.py`: Review the Python code for compliance with PE...

src/**/*.py: Review the Python code for compliance with PEP 8 and PEP 257 (docstring conventions). Ensure the following: - Variables and functions follow meaningful naming conventions. - Docstrings are present, accurate, and align with the implementation. - Code is efficient and avoids redundancy while adhering to DRY principles. - Consider suggestions to enhance readability and maintainability. - Highlight any potential performance issues, edge cases, or logical errors. - Ensure all imported libraries are used and necessary.

  • src/imgtools/modules/interlacer.py
🪛 Ruff (0.8.2)
src/imgtools/modules/interlacer.py

35-35: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)

⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Unit-Tests (windows-latest, py313)
  • GitHub Check: Unit-Tests (windows-latest, py312)
  • GitHub Check: Unit-Tests (windows-latest, py311)
  • GitHub Check: Unit-Tests (windows-latest, py310)
  • GitHub Check: Unit-Tests (macos-13, py313)
  • GitHub Check: Unit-Tests (macos-13, py312)
  • GitHub Check: Unit-Tests (macos-13, py311)
  • GitHub Check: Unit-Tests (macos-13, py310)
  • GitHub Check: Unit-Tests (macos-latest, py310)
  • GitHub Check: Unit-Tests (ubuntu-latest, py313)
  • GitHub Check: Unit-Tests (ubuntu-latest, py312)
  • GitHub Check: Unit-Tests (ubuntu-latest, py311)
  • GitHub Check: Unit-Tests (ubuntu-latest, py310)
🔇 Additional comments (1)
src/imgtools/modules/interlacer.py (1)

111-133: Great comprehensive docstring for query method!

The docstring for the query method is well structured with clear parameters, returns, and a detailed explanation of supported modalities. This is a good example of how other methods in the class should be documented.

@jjjermiah
Copy link
Contributor

nice work

should be good once its ruff and mypy compliant

pixi run -e dev ruff check src/imgtools/modules/interlacer.py 

and

pixi run -e dev mypy src/imgtools/modules/interlacer.py

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.

2 participants