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

feat: update plot correlation functions #104

Open
wants to merge 18 commits into
base: main
Choose a base branch
from

Conversation

strixy16
Copy link
Collaborator

@strixy16 strixy16 commented Dec 20, 2024

add self and cross correlation plot functions

Summary by CodeRabbit

  • New Features
    • Introduced functionality for plotting self and cross correlation heatmaps and histograms.
    • Added methods for generating histograms with customizable parameters and optional saving options.
  • Bug Fixes
    • Enhanced error handling for plot saving to prevent overwriting existing files.
  • Tests
    • Added a comprehensive suite of unit tests for correlation plotting functionalities, ensuring correct outputs and file handling.

Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Warning

Rate limit exceeded

@strixy16 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2ff4913 and b0de8eb.

📒 Files selected for processing (2)
  • src/readii/analyze/plot_correlation.py (5 hunks)
  • tests/analyze/test_plot_correlation.py (1 hunks)

Walkthrough

The pull request introduces several new functionalities to the plot_correlation.py module, including the addition of functions for plotting self and cross correlation heatmaps and histograms. New functions plotSelfCorrHeatmap, plotCrossCorrHeatmap, plotSelfCorrHistogram, and plotCrossCorrHistogram are implemented, allowing for customizable plotting and saving options. Additionally, error handling is refined with the introduction of a new exception class in the plot_writer.py file, enhancing the robustness of the plotting process.

Changes

File Change Summary
src/readii/analyze/plot_correlation.py - Added plotSelfCorrHeatmap, plotCrossCorrHeatmap, plotSelfCorrHistogram, and plotCrossCorrHistogram functions for generating heatmaps and histograms.
- Updated existing plotting functions to support new functionalities and adjusted return types.
- Enhanced error handling and logging for new functions.
src/readii/io/writers/plot_writer.py - Introduced PlotWriterPlotExistsError exception for handling attempts to save plots to existing paths without overwriting.
tests/analyze/test_plot_correlation.py - Added unit tests for the new plotting functions, including tests for default parameters and file saving functionality.

Possibly related PRs

  • feat: add CorrelationWriter #96: The CorrelationWriter class introduced in this PR may be related to the new plotting functions in the main PR, as both involve handling correlation data and include mechanisms for managing file outputs.
  • feat: update correlation functions to get subsections of matrix #103: The updates to the correlation functions, specifically the renaming and enhancement of getSelfCorrelations and getCrossCorrelations, are directly related to the new plotting functions in the main PR, which utilize these correlation retrieval methods for generating heatmaps and histograms.

Suggested reviewers

  • jjjermiah

Poem

🐰 In the garden of data, we plot and we play,
Heatmaps and histograms brighten the way.
With colors that dance and patterns that sing,
Correlation's magic, oh what joy it brings!
A rabbit's delight in each statistical trace! 📊


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. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

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 (2)
src/readii/analyze/plot_correlation.py (2)

191-192: Optional docstring improvement.

The return statement is straightforward, but consider adding descriptive text to the docstring near lines 191-192 to provide clarity about the returned values, especially if future maintainers need more context on bin_values versus bin_edges.


225-262: Save directory & error handling.

  1. The usage of PlotWriter to control output directories under lines 235-255 is a good approach for consistent file saving.
  2. The conditional check at lines 248-249 logs a warning if a file already exists, preventing accidental overwrites. This is excellent for data integrity.
  3. Consider adding a try-except around the actual saving (line 254) if you want to log or handle file I/O errors more gracefully, although the current approach might suffice if PlotWriter handles exceptions.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 684d4b4 and 73492d8.

⛔ Files ignored due to path filters (1)
  • pixi.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • src/readii/analyze/plot_correlation.py (3 hunks)
🔇 Additional comments (2)
src/readii/analyze/plot_correlation.py (2)

Line range hint 1-12: Imports and integration.

These newly added imports for getCrossCorrelations, getSelfCorrelations, and PlotWriter are appropriate and clearly integrate with the existing correlation and plotting code. Ensure that the respective modules are available at runtime and that you maintain consistent versioning of these dependencies within the project.


193-224: Function naming and usage clarity.

The function name plotSelfCorrHeatmap accurately describes its purpose. The introductory docstring is also consistent with the code. The parameter naming (especially feature_type_name, correlation_method, cmap, save_dir_path) is self-explanatory, enhancing readability.

Comment on lines 265 to 339
vertical_feature_name:str,
horizontal_feature_name:str,
correlation_method:str = "pearson",
cmap:str='nipy_spectral',
save_dir_path:Optional[str] = None) -> tuple[Figure | Figure, Path]:
"""Plot a heatmap of the cross correlations from a correlation matrix.

Parameters
----------
correlation_matrix : pd.DataFrame
Dataframe containing the correlation matrix to plot.
vertical_feature_name : str
Name of the vertical feature to get cross correlations for. Must be the suffix of some feature names in the correlation matrix index.
horizontal_feature_name : str
Name of the horizontal feature to get cross correlations for. Must be the suffix of some feature names in the correlation matrix columns.
correlation_method : str, optional
Method to use for calculating correlations. Default is "pearson".
cmap : str, optional
Colormap to use for the heatmap. Default is "nipy_spectral".
save_path : str, optional
Path to save the heatmap to. If None, the heatmap will not be saved. Default is None.
File will be saved to {save_dir_path}/heatmap/{cmap}/{vertical_feature_name}_vs_{horizontal_feature_name}_{correlation_method}_cross_correlation_heatmap.png

Returns
-------
cross_corr_heatmap : matplotlib.pyplot.figure
Figure object containing the heatmap of the cross correlations.
if save_path is not None:
cross_corr_save_path : Path
Path to the saved heatmap.
"""
# Get the cross correlations for the specified feature type
cross_corr = getCrossCorrelations(correlation_matrix, vertical_feature_name, horizontal_feature_name)

# Make the heatmap figure
cross_corr_heatmap = plotCorrelationHeatmap(cross_corr,
diagonal=True,
cmap=cmap,
xlabel=vertical_feature_name,
ylabel=horizontal_feature_name,
title=f"{correlation_method.capitalize()} Cross Correlations", subtitle=f"{vertical_feature_name} vs {horizontal_feature_name}")

if save_dir_path is not None:
# Create a PlotWriter instance to save the heatmap
heatmap_writer = PlotWriter(root_directory = save_dir_path / "heatmap",
filename_format = "{ColorMap}/" + "{VerticalFeatureType}_vs_{HorizontalFeatureType}_{CorrelationType}_cross_correlation_heatmap.png",
overwrite = False,
create_dirs = True
)

# Get the output path for the heatmap
cross_corr_save_path = heatmap_writer.resolve_path(VerticalFeatureType = vertical_feature_name,
HorizontalFeatureType = horizontal_feature_name,
CorrelationType = correlation_method,
ColorMap = cmap)

# Check if the heatmap already exists
if cross_corr_save_path.exists():
logger.warning(f"Correlation heatmap already exists at {cross_corr_save_path}.")

else:
logger.debug("Saving correlation heatmap.")
# Save the heatmap
cross_corr_save_path = heatmap_writer.save(cross_corr_heatmap,
VerticalFeatureType = vertical_feature_name,
HorizontalFeatureType = horizontal_feature_name,
CorrelationType = correlation_method,
ColorMap = cmap)
# Return the figure and the path to the saved heatmap
return cross_corr_heatmap, cross_corr_save_path

else:
# Return the heatmap figure
return cross_corr_heatmap
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Parameter name mismatch and diagonal setting are valid concerns

  1. The docstring incorrectly references "save_path" while the function uses "save_dir_path".
  2. Setting diagonal=True in plotCorrelationHeatmap for cross-correlations is incorrect. The getCrossCorrelations function returns a matrix where rows and columns represent different feature types (vertical vs. horizontal), so there's no meaningful diagonal to mask. The diagonal=True parameter would unnecessarily hide part of the cross-correlation data.
  • Update the docstring to use "save_dir_path" instead of "save_path"
  • Change diagonal=True to diagonal=False in the plotCorrelationHeatmap call to show the complete cross-correlation matrix
🔗 Analysis chain

Docstring parameter mismatch and diagonal setting for cross correlation.

  1. In lines 285-287, the docstring references a parameter named “save_path,” whereas the function parameter is “save_dir_path.” Rename either the docstring parameter or the function parameter to maintain consistency.
  2. The heatmap calls plotCorrelationHeatmap with diagonal=True for cross correlation. While this may be intentional to highlight only half the matrix, consider verifying whether a full matrix display (diagonal=False) is more appropriate for cross correlations.
  3. Overall logic is consistent: the function retrieves cross correlations, plots them, and optionally saves the figure with a well-structured naming convention.

Let me gather more information about the cross-correlation plotting functionality to verify both concerns.


Let me check the implementation of getCrossCorrelations to understand if diagonal=True is appropriate for cross-correlations.


Let me try a different pattern to get the implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check references to save_path or save_dir_path in docstrings vs. function signatures
rg -A 3 "def plotCrossCorrHeatmap"

Length of output: 417


Script:

#!/bin/bash
# Check the implementation of plotCorrelationHeatmap to understand diagonal parameter usage
ast-grep --pattern 'def plotCorrelationHeatmap($$$)'

# Search for other cross-correlation related functions to understand the context
rg -B 2 -A 5 "getCrossCorrelations"

Length of output: 3559


Script:

#!/bin/bash
# Check the implementation of getCrossCorrelations to understand the matrix structure
ast-grep --pattern 'def getCrossCorrelations($$$) {
  $$$
}'

Length of output: 62


Script:

#!/bin/bash
# Check the implementation of getCrossCorrelations
rg -B 2 -A 20 "^def getCrossCorrelations"

Length of output: 2165

Copy link

codecov bot commented Dec 20, 2024

Codecov Report

Attention: Patch coverage is 70.58824% with 15 lines in your changes missing coverage. Please review.

Project coverage is 47.66%. Comparing base (343d876) to head (b0de8eb).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/readii/analyze/plot_correlation.py 70.83% 14 Missing ⚠️
src/readii/io/writers/plot_writer.py 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #104      +/-   ##
==========================================
+ Coverage   41.91%   47.66%   +5.75%     
==========================================
  Files          33       33              
  Lines        1453     1502      +49     
==========================================
+ Hits          609      716     +107     
+ Misses        844      786      -58     

☔ 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: 2

🧹 Nitpick comments (2)
tests/analyze/test_plot_correlation.py (1)

83-84: Remove f-string prefix

The string doesn't contain any placeholders, so the f-string prefix is unnecessary.

-    assert corr_fig.get_suptitle() == f"Correlation Heatmap", \
+    assert corr_fig.get_suptitle() == "Correlation Heatmap", \
🧰 Tools
🪛 Ruff (0.8.2)

83-83: f-string without any placeholders

Remove extraneous f prefix

(F541)

src/readii/analyze/plot_correlation.py (1)

259-572: Consider performance optimization for large matrices

For large correlation matrices, consider:

  1. Using numpy's optimized functions for matrix operations
  2. Implementing caching for frequently accessed correlation data
  3. Adding progress logging for long-running operations
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73492d8 and 907d348.

📒 Files selected for processing (3)
  • src/readii/analyze/plot_correlation.py (5 hunks)
  • src/readii/io/writers/plot_writer.py (2 hunks)
  • tests/analyze/test_plot_correlation.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/analyze/test_plot_correlation.py

2-2: readii.io.writers.plot_writer.PlotWriter imported but unused

Remove unused import: readii.io.writers.plot_writer.PlotWriter

(F401)


12-12: pathlib.Path imported but unused

Remove unused import: pathlib.Path

(F401)


83-83: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (6)
src/readii/io/writers/plot_writer.py (1)

22-25: LGTM: Well-structured exception handling enhancement

The addition of PlotWriterPlotExistsError improves error handling specificity for existing plot scenarios.

tests/analyze/test_plot_correlation.py (1)

18-132: LGTM: Comprehensive test coverage

The test suite provides thorough coverage of the correlation plotting functionality:

  • Well-structured fixtures for test data
  • Parameterized tests for different correlation types
  • Proper validation of output paths and file existence
🧰 Tools
🪛 Ruff (0.8.2)

83-83: f-string without any placeholders

Remove extraneous f prefix

(F541)

src/readii/analyze/plot_correlation.py (4)

17-49: LGTM: Well-implemented save functionality

The saveCorrelationHeatmap function is well-structured with proper:

  • Error handling using the new PlotWriterPlotExistsError
  • Path construction for different feature types
  • Logging of warnings and debug information

287-287: Fix docstring parameter name mismatch

The docstring references save_path but the parameter is named save_dir_path.

-    if save_path is not None:
+    if save_dir_path is not None:

Also applies to: 361-361


295-296: Verify diagonal parameter usage for self-correlation

Setting diagonal=True for self-correlation heatmaps is correct as it helps visualize the symmetry of self-correlations.


369-370: LGTM: Correct diagonal parameter for cross-correlation

Setting diagonal=False for cross-correlation heatmaps is correct as cross-correlations don't have meaningful diagonal elements.

Comment on lines 1 to 2
from readii.analyze.correlation import getFeatureCorrelations
from readii.io.writers.plot_writer import PlotWriter
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unused imports

The imports PlotWriter and Path are not used in the test file.

-from readii.io.writers.plot_writer import PlotWriter
-from pathlib import Path

Also applies to: 12-12

🧰 Tools
🪛 Ruff (0.8.2)

2-2: readii.io.writers.plot_writer.PlotWriter imported but unused

Remove unused import: readii.io.writers.plot_writer.PlotWriter

(F401)

Comment on lines 534 to 541
cross_corr_hist = plotCorrelationHistogram(cross_corr,
num_bins=num_bins,
xlabel = f"{correlation_method.capitalize()} Correlation",
y_lower_bound = y_lower_bound,
y_upper_bound = y_upper_bound,
title = f"Distribution of {correlation_method.capitalize()} Cross Correlations",
subtitle=f"{vertical_feature_name} vs {horizontal_feature_name}")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent return value unpacking

The function call to plotCorrelationHistogram returns a tuple of three values, but only one is being assigned.

-    cross_corr_hist = plotCorrelationHistogram(cross_corr, 
+    cross_corr_hist, _, _ = plotCorrelationHistogram(cross_corr, 
📝 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
# Make the histogram figure
cross_corr_hist = plotCorrelationHistogram(cross_corr,
num_bins=num_bins,
xlabel = f"{correlation_method.capitalize()} Correlation",
y_lower_bound = y_lower_bound,
y_upper_bound = y_upper_bound,
title = f"Distribution of {correlation_method.capitalize()} Cross Correlations",
subtitle=f"{vertical_feature_name} vs {horizontal_feature_name}")
# Make the histogram figure
cross_corr_hist, _, _ = plotCorrelationHistogram(cross_corr,
num_bins=num_bins,
xlabel = f"{correlation_method.capitalize()} Correlation",
y_lower_bound = y_lower_bound,
y_upper_bound = y_upper_bound,
title = f"Distribution of {correlation_method.capitalize()} Cross Correlations",
subtitle=f"{vertical_feature_name} vs {horizontal_feature_name}")

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

🧹 Nitpick comments (2)
tests/analyze/test_plot_correlation.py (1)

68-71: Avoid hardcoding test values.

The test uses hardcoded values (4.0 and 30.0) for bin validation. Consider:

  1. Using dynamic calculation based on the input data
  2. Adding tolerance for floating-point comparisons
  3. Documenting why these specific values are expected
-    assert bin_values[0] == 4.0, \
-        f"Wrong first bin value, expect 4.0, got {bin_values[0]}"
-    assert bin_values[-1] == 30.0, \
-        f"Wrong last value, expect 30.0, got {bin_values[-1]}"
+    # Calculate expected values based on the correlation matrix
+    expected_first_bin = len([x for x in correlation_matrix.values.flatten() if -1.0 <= x < -0.98])
+    expected_last_bin = len([x for x in correlation_matrix.values.flatten() if 0.98 <= x <= 1.0])
+    
+    np.testing.assert_allclose(bin_values[0], expected_first_bin, rtol=1e-10,
+        err_msg=f"Wrong first bin value, expect {expected_first_bin}, got {bin_values[0]}")
+    np.testing.assert_allclose(bin_values[-1], expected_last_bin, rtol=1e-10,
+        err_msg=f"Wrong last bin value, expect {expected_last_bin}, got {bin_values[-1]}")
src/readii/analyze/plot_correlation.py (1)

487-493: Consider adding correlation range to histogram title.

For better context, consider including the correlation range in the histogram title or subtitle:

     cross_corr_hist, _, _ = plotCorrelationHistogram(cross_corr, 
                                               num_bins=num_bins,
                                               xlabel = f"{correlation_method.capitalize()} Correlation",
                                               y_lower_bound = y_lower_bound,
                                               y_upper_bound = y_upper_bound,
-                                               title = f"Distribution of {correlation_method.capitalize()} Cross Correlations",
+                                               title = f"Distribution of {correlation_method.capitalize()} Cross Correlations (Range: -1 to 1)",
                                               subtitle=f"{vertical_feature_name} vs {horizontal_feature_name}")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 907d348 and 2ff4913.

📒 Files selected for processing (2)
  • src/readii/analyze/plot_correlation.py (5 hunks)
  • tests/analyze/test_plot_correlation.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/analyze/test_plot_correlation.py

2-2: readii.io.writers.plot_writer.PlotWriter imported but unused

Remove unused import: readii.io.writers.plot_writer.PlotWriter

(F401)


16-16: pathlib.Path imported but unused

Remove unused import: pathlib.Path

(F401)


87-87: f-string without any placeholders

Remove extraneous f prefix

(F541)


146-146: f-string without any placeholders

Remove extraneous f prefix

(F541)


159-159: f-string without any placeholders

Remove extraneous f prefix

(F541)


171-171: f-string without any placeholders

Remove extraneous f prefix

(F541)


184-184: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (5)
tests/analyze/test_plot_correlation.py (2)

1-2: Remove unused imports.

The imports PlotWriter and Path are not used in the test file.

🧰 Tools
🪛 Ruff (0.8.2)

2-2: readii.io.writers.plot_writer.PlotWriter imported but unused

Remove unused import: readii.io.writers.plot_writer.PlotWriter

(F401)


22-52: LGTM! Well-structured test fixtures.

The fixtures provide a clean setup for the test environment with:

  • Temporary directory for correlations
  • Feature names for vertical and horizontal axes
  • Correlation method specification
  • Random correlation matrix generation
src/readii/analyze/plot_correlation.py (3)

347-347: ⚠️ Potential issue

Fix docstring parameter name mismatch.

The docstring references 'save_path' but the parameter is named 'save_dir_path':

-    if save_path is not None:
+    if save_dir_path is not None:

Likely invalid or redundant comment.


287-287: ⚠️ Potential issue

Fix docstring parameter name mismatch.

The docstring references 'save_path' but the parameter is named 'save_dir_path':

-    if save_path is not None:
+    if save_dir_path is not None:

Likely invalid or redundant comment.


355-357: ⚠️ Potential issue

Remove diagonal masking for cross-correlation heatmap.

Setting diagonal=True for cross-correlations is incorrect as the matrix represents correlations between different feature types. The diagonal has no special meaning in this context.

     cross_corr_heatmap = plotCorrelationHeatmap(cross_corr, 
-                                                diagonal=False, 
                                                 cmap=cmap, 

Likely invalid or redundant comment.

Comment on lines +82 to +187
"Wrong title, expect Correlation Heatmap"


@pytest.mark.parametrize(
"correlation_type, feature_types",
[
("pearson_self", ["vertical"]),
("pearson_cross", ["vertical", "horizontal"]),
]
)
def test_save_corr_heatmap(correlation_matrix, correlations_dir, correlation_type, feature_types):
"""Test saving a heatmap from a cross-correlation matrix"""
corr_fig = plotCorrelationHeatmap(correlation_matrix)

expected_path = correlations_dir / "heatmap" / "nipy_spectral" / ("_vs_".join(feature_types)) + f"_{correlation_type}_correlation_heatmap.png"

actual_path = saveCorrelationHeatmap(corr_fig,
correlations_dir,
cmap="nipy_spectral",
feature_types=feature_types,
correlation_type=correlation_type)
assert actual_path == expected_path, \
"Wrong path returned, expect {expected_path}"
assert actual_path.exists(), \
"Figure is not being saved to path provided or at all."



@pytest.mark.parametrize(
"correlation_type, feature_types",
[
("pearson_self", ["vertical"]),
("pearson_cross", ["vertical", "horizontal"]),
]
)
def test_save_corr_histogram(correlation_matrix, correlations_dir, correlation_type, feature_types):
"""Test saving a histogram from a correlation matrix"""
corr_fig, _, _ = plotCorrelationHistogram(correlation_matrix)

expected_path = correlations_dir / "histogram" / ("_vs_".join(feature_types)) + f"_{correlation_type}_correlation_histogram.png"

actual_path = saveCorrelationHistogram(corr_fig,
correlations_dir,
feature_types=feature_types,
correlation_type=correlation_type)
assert actual_path == expected_path, \
"Wrong path returned, expect {expected_path}"
assert actual_path.exists(), \
"Figure is not being saved to path provided or at all."



def test_plot_selfcorr_heatmap_defaults(correlation_matrix, vertical_feature_name):
"""Test plotting a self-correlation heatmap from a correlation matrix"""
corr_fig = plotSelfCorrHeatmap(correlation_matrix,
feature_type_name=vertical_feature_name)
assert isinstance(corr_fig, Figure), \
"Wrong return type, expect a matplotlib Figure"
assert corr_fig.get_suptitle() == f"Pearson Self Correlations", \
"Wrong title, expect Pearson Self Correlations"
assert corr_fig.get_axes()[0].get_title(), \
"Wrong subtitle, expect vertical"


def test_plot_crosscorr_heatmap_defaults(correlation_matrix, vertical_feature_name, horizontal_feature_name):
"""Test plotting a cross-correlation heatmap from a correlation matrix"""
corr_fig = plotCrossCorrHeatmap(correlation_matrix,
vertical_feature_name=vertical_feature_name,
horizontal_feature_name=horizontal_feature_name)
assert isinstance(corr_fig, Figure), \
"Wrong return type, expect a matplotlib Figure"
assert corr_fig.get_suptitle() == f"Pearson Cross Correlations", \
"Wrong title, expect Pearson Cross Correlations"
assert corr_fig.get_axes()[0].get_title(), \
"Wrong subtitle, expect vertical vs horizontal"


def test_plot_selfcorr_histogram_defaults(correlation_matrix, vertical_feature_name):
"""Test plotting a self-correlation histogram from a correlation matrix"""
corr_fig = plotSelfCorrHistogram(correlation_matrix,
feature_type_name=vertical_feature_name)
assert isinstance(corr_fig, Figure), \
"Wrong return type, expect a matplotlib Figure"
assert corr_fig.get_suptitle() == f"Distribution of Pearson Self Correlations", \
"Wrong title, expect Distribution of Pearson Self Correlations"
assert corr_fig.get_axes()[0].get_title(), \
"Wrong subtitle, expect vertical"


def test_plot_crosscorr_histogram_defaults(correlation_matrix, vertical_feature_name, horizontal_feature_name):
"""Test plotting a cross-correlation histogram from a correlation matrix"""
corr_fig = plotCrossCorrHistogram(correlation_matrix,
vertical_feature_name=vertical_feature_name,
horizontal_feature_name=horizontal_feature_name)
assert isinstance(corr_fig, Figure), \
"Wrong return type, expect a matplotlib Figure"
assert corr_fig.get_suptitle() == f"Distribution of Pearson Cross Correlations", \
"Wrong title, expect Pearon Cross Correlations"
assert corr_fig.get_axes()[0].get_title(), \
"Wrong subtitle, expect vertical vs horizontal"
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error case tests.

The test suite lacks coverage for error scenarios. Consider adding tests for:

  1. Invalid correlation methods
  2. Non-existent feature names
  3. Invalid bin counts
  4. File permission errors when saving

Example test case:

def test_invalid_bin_count():
    """Test that negative bin count raises ValueError."""
    with pytest.raises(ValueError, match="Number of bins must be positive"):
        plotCorrelationHistogram(correlation_matrix, num_bins=-1)
🧰 Tools
🪛 Ruff (0.8.2)

87-87: f-string without any placeholders

Remove extraneous f prefix

(F541)


146-146: f-string without any placeholders

Remove extraneous f prefix

(F541)


159-159: f-string without any placeholders

Remove extraneous f prefix

(F541)


171-171: f-string without any placeholders

Remove extraneous f prefix

(F541)


184-184: f-string without any placeholders

Remove extraneous f prefix

(F541)

Comment on lines +109 to +110
assert actual_path == expected_path, \
"Wrong path returned, expect {expected_path}"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix f-string formatting in assertion message.

The f-string is missing the f prefix:

-    assert actual_path == expected_path, \
-        "Wrong path returned, expect {expected_path}"
+    assert actual_path == expected_path, \
+        f"Wrong path returned, expect {expected_path}"
📝 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
assert actual_path == expected_path, \
"Wrong path returned, expect {expected_path}"
assert actual_path == expected_path, \
f"Wrong path returned, expect {expected_path}"

Comment on lines +184 to +185
assert corr_fig.get_suptitle() == f"Distribution of Pearson Cross Correlations", \
"Wrong title, expect Pearon Cross Correlations"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in assertion message.

There's a typo in the expected title:

-    assert corr_fig.get_suptitle() == f"Distribution of Pearson Cross Correlations", \
-        "Wrong title, expect Pearon Cross Correlations"
+    assert corr_fig.get_suptitle() == "Distribution of Pearson Cross Correlations", \
+        "Wrong title, expect Distribution of Pearson Cross Correlations"
📝 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
assert corr_fig.get_suptitle() == f"Distribution of Pearson Cross Correlations", \
"Wrong title, expect Pearon Cross Correlations"
assert corr_fig.get_suptitle() == "Distribution of Pearson Cross Correlations", \
"Wrong title, expect Distribution of Pearson Cross Correlations"
🧰 Tools
🪛 Ruff (0.8.2)

184-184: f-string without any placeholders

Remove extraneous f prefix

(F541)

Comment on lines +133 to +134
assert actual_path == expected_path, \
"Wrong path returned, expect {expected_path}"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix f-string formatting in assertion message.

The f-string is missing the f prefix:

-    assert actual_path == expected_path, \
-        "Wrong path returned, expect {expected_path}"  
+    assert actual_path == expected_path, \
+        f"Wrong path returned, expect {expected_path}"
📝 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
assert actual_path == expected_path, \
"Wrong path returned, expect {expected_path}"
assert actual_path == expected_path, \
f"Wrong path returned, expect {expected_path}"

correlation_directory:Path,
feature_types:list[str],
correlation_type:str,
overwrite:bool = False) -> None:
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect return type hint.

The function returns a Path but the type hint indicates None:

-                             overwrite:bool = False) -> None:
+                             overwrite:bool = False) -> Path:
📝 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
overwrite:bool = False) -> None:
overwrite:bool = False) -> Path:

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

Successfully merging this pull request may close these issues.

1 participant