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

Clean code, remove print -> logger, add all authors. #100

Merged
merged 13 commits into from
Feb 9, 2025
Merged

Clean code, remove print -> logger, add all authors. #100

merged 13 commits into from
Feb 9, 2025

Conversation

ypriverol
Copy link
Member

@ypriverol ypriverol commented Feb 9, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced the command-line interface with configurable logging options, allowing users to set custom log levels and direct output to a file for improved runtime feedback.
    • Introduced logging functionality across various modules, improving error handling and output control.

  • Documentation
    • Streamlined help texts and error messages across commands for clearer, more consistent guidance during usage.
    • Updated function docstrings to a more structured format, enhancing clarity and usability.

Copy link
Contributor

coderabbitai bot commented Feb 9, 2025

Warning

Rate limit exceeded

@ypriverol has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 11 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 c48b46a and 0c6fc0b.

📒 Files selected for processing (3)
  • ibaqpy/ibaq/combiner.py (4 hunks)
  • ibaqpy/ibaq/utils.py (17 hunks)
  • ibaqpy/ibaqpyc.py (2 hunks)

Walkthrough

This pull request implements widespread enhancements in logging, documentation, and type annotations across multiple modules. Logger instances with NullHandler replace direct logging calls, and several docstrings have been reformatted to a structured style. In some modules, type hints have been improved (e.g., using forward references) and error handling adjusted (e.g., raising ValueError). The CLI functionality now accepts configurable logging options, and the package metadata is updated with additional authors. Overall, the core logic remains unchanged, with modifications focused on clarity, maintainability, and logging robustness.

Changes

File(s) Change Summary
ibaqpy/commands/…/correct_batches.py, ibaqpy/ibaq/…/ibaqpy_postprocessing.py, ibaqpy/ibaq/…/peptide_normalization.py, ibaqpy/ibaqpyc.py, ibaqpy/ibaq/…/file_utils.py, ibaqpy/ibaq/…/utils.py Replaced direct logging calls with logger instances (using NullHandler), improved error handling (e.g., raising ValueError, adding TooFewSamplesInBatch exception), and updated logging configuration in the CLI.
ibaqpy/commands/…/correct_batches.py, ibaqpy/commands/…/features2peptides.py, ibaqpy/commands/…/peptides2protein.py, ibaqpy/ibaq/…/ibaqpy_commons.py, ibaqpy/ibaq/…/ibaqpy_postprocessing.py, ibaqpy/ibaq/…/peptide_normalization.py, ibaqpy/ibaq/…/utils.py, ibaqpy/ibaq/…/file_utils.py Updated docstring formatting and parameter documentation to a more structured style; added or improved type hints (e.g., forward references for AnnData, explicit parameter types).
pyproject.toml Added three new authors to the authors list.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as ibaqpyc.cli
    participant Log as Logging.Config
    participant FS as FileSystem

    User->>CLI: call cli(log_level, log_file)
    CLI->>Log: Configure basic logging (set format, level)
    alt log_file provided
        CLI->>FS: Check if log_file exists
        FS-->>CLI: Existence result
        CLI->>Log: Create FileHandler for log_file (if needed)
    end
    CLI->>User: Execute CLI command with enhanced logging
Loading

Possibly related PRs

  • Dev #93: Modifications in correct_batches.py involving the introduction of a new logging variable and its application in the run_batch_correction function.
  • minor refinements #95: Updates to the documentation for is_valid_sample_id, get_batch_id_from_sample_names, and run_batch_correction functions in the same module.
  • Major refactoring of the structure of the project. #79: Enhancements in logging and documentation practices in the peptides2protein.py file, indicating a direct connection at the code level.

Poem

I'm a rabbit in the code field, hopping with glee,
Logs now whisper secrets where they once roared free.
Docstrings shine with order and a structured beat,
Each function now sings with clarity so neat.
With every updated line, I bounce in delight,
Celebrating these changes from morning till night!
(\/)\n( ••)\n/>🍎 Let's code on!


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

github-actions bot commented Feb 9, 2025

Qodana for JVM

It seems all right 👌

No new problems were found according to the checks applied

☁️ View the detailed Qodana report

Contact Qodana team

Contact us at [email protected]

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

🔭 Outside diff range comments (2)
ibaqpy/ibaq/ibaqpy_postprocessing.py (1)

264-264: Replace direct logging call with logger instance.

For consistency with other changes, use the logger instance instead of directly calling logging.warning.

Apply this diff to fix the inconsistency:

-        logging.warning(f"Found {long_df[values].isna().sum()} missing values in the result")
+        logger.warning(f"Found {long_df[values].isna().sum()} missing values in the result")
ibaqpy/commands/correct_batches.py (1)

57-59: Replace print statements with logger instance.

For consistency with other logging changes, use the logger instance instead of print statements.

Apply this diff to fix the inconsistency:

-        print("The following sample IDs are invalid:")
-        for invalid_sample in invalid_samples:
-            print(f" - {invalid_sample}")
+        logger.warning("The following sample IDs are invalid:")
+        for invalid_sample in invalid_samples:
+            logger.warning(f" - {invalid_sample}")
🧹 Nitpick comments (3)
ibaqpy/ibaqpyc.py (2)

14-19: Consider adding more logging levels for comprehensive error handling.

The logging configuration could be enhanced by:

  1. Adding "error" and "critical" levels
  2. Using "WARNING" instead of "WARN" for consistency with Python's logging module
-LOG_LEVELS = ["debug", "info", "warn"]
+LOG_LEVELS = ["debug", "info", "warning", "error", "critical"]
 LOG_LEVELS_TO_LEVELS = {
     "debug": logging.DEBUG,
     "info": logging.INFO,
-    "warn": logging.WARN,
+    "warning": logging.WARNING,
+    "error": logging.ERROR,
+    "critical": logging.CRITICAL,
 }

40-49: Simplify nested if statements for better readability.

The log file setup can be simplified by combining the conditions.

-    if log_file:
-        if not log_file.exists():
-            if not log_file.parent.exists():
-                log_file.parent.mkdir(parents=True, exist_ok=True)
+    if log_file and not log_file.exists():
+        log_file.parent.mkdir(parents=True, exist_ok=True)
🧰 Tools
🪛 Ruff (0.8.2)

40-41: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

ibaqpy/ibaq/utils.py (1)

405-411: Simplify nested if statements.

The nested if statements can be combined using and for better readability.

Apply this diff to simplify the code:

-    if covs:
-        if len(df.columns) != len(covs):
+    if covs and len(df.columns) != len(covs):
🧰 Tools
🪛 Ruff (0.8.2)

405-406: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ade3ff6 and ef03ba7.

📒 Files selected for processing (10)
  • ibaqpy/commands/correct_batches.py (8 hunks)
  • ibaqpy/commands/features2peptides.py (1 hunks)
  • ibaqpy/commands/peptides2protein.py (1 hunks)
  • ibaqpy/ibaq/file_utils.py (4 hunks)
  • ibaqpy/ibaq/ibaqpy_commons.py (6 hunks)
  • ibaqpy/ibaq/ibaqpy_postprocessing.py (7 hunks)
  • ibaqpy/ibaq/peptide_normalization.py (8 hunks)
  • ibaqpy/ibaq/utils.py (15 hunks)
  • ibaqpy/ibaqpyc.py (2 hunks)
  • pyproject.toml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • ibaqpy/commands/features2peptides.py
🧰 Additional context used
🪛 Ruff (0.8.2)
ibaqpy/ibaqpyc.py

40-41: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

ibaqpy/ibaq/utils.py

405-406: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: build
🔇 Additional comments (11)
ibaqpy/ibaqpyc.py (1)

27-33: LGTM! Well-structured CLI options for logging configuration.

The implementation provides good defaults and clear help text for the logging options.

ibaqpy/commands/peptides2protein.py (1)

80-87: LGTM! Clear and concise docstring update.

The docstring maintains essential information while improving readability.

ibaqpy/ibaq/file_utils.py (2)

4-15: LGTM! Well-implemented type checking and logging setup.

Good use of TYPE_CHECKING for forward references and proper logger configuration with NullHandler.


25-25: LGTM! Good improvements to type safety and logging.

The forward reference for AnnData and the informative log message enhance code quality.

Also applies to: 112-112

ibaqpy/ibaq/ibaqpy_commons.py (1)

98-98: LGTM! Improved type annotations and documentation.

Good improvements:

  1. More accurate return types using Figure instead of matplotlib.pyplot
  2. Well-structured numpy-style docstrings
  3. Clear parameter and return type documentation

Also applies to: 132-132, 176-194, 197-224, 227-243

ibaqpy/ibaq/ibaqpy_postprocessing.py (1)

18-19: LGTM! Logger configuration follows best practices.

The logger is correctly configured with a NullHandler, which prevents "No handlers could be found" warnings when the application doesn't configure logging.

ibaqpy/commands/correct_batches.py (1)

18-19: LGTM! Logger configuration follows best practices.

The logger is correctly configured with a NullHandler, which prevents "No handlers could be found" warnings when the application doesn't configure logging.

ibaqpy/ibaq/utils.py (1)

16-17: LGTM! Logger configuration follows best practices.

The logger is correctly configured with a NullHandler, which prevents "No handlers could be found" warnings when the application doesn't configure logging.

ibaqpy/ibaq/peptide_normalization.py (2)

34-35: LGTM! Logger configuration follows best practices.

The logger is correctly configured with a NullHandler and uses a descriptive name that follows the package hierarchy.


457-457: LGTM! Error handling improvement.

The error handling is improved by raising a ValueError with a clear message and preserving the original exception using the from clause.

pyproject.toml (1)

11-13: New Authors Added Successfully
The three new author entries are correctly formatted and integrated into the authors array. This update aligns well with the metadata enhancements described in the PR objectives. Consider verifying that all new contributors are also mentioned in the project documentation for consistency.

ypriverol and others added 3 commits February 9, 2025 07:19
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@ypriverol ypriverol changed the title Dev Clean code, remove print -> logger, add all authors. Feb 9, 2025
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

🔭 Outside diff range comments (2)
tests/test_file_utils.py (1)

31-31: Use module-level logger instead of root logger.

Using the root logger directly with logging.info() is not recommended. Instead, follow the pattern used in other test files by configuring a module-level logger with NullHandler.

+logger = logging.getLogger(__name__)
+logger.addHandler(logging.NullHandler())
-    logging.info(df_ibaq.head())
+    logger.info(df_ibaq.head())
-    logging.info(adata)
+    logger.info(adata)

Also applies to: 59-59

tests/test_batch_correction.py (1)

40-40: Use consistent logger throughout the test.

The test uses both the root logger (logging.debug()) and the module-level logger (logger.info()). Stick to using the module-level logger consistently.

-    logging.debug("Arguments for run_batch_correction: %s", args)
+    logger.debug("Arguments for run_batch_correction: %s", args)

Also applies to: 55-55

🧹 Nitpick comments (12)
ibaqpy/ibaq/utils.py (2)

404-409: Simplify nested if statements.

The nested if statements can be combined using and for better readability.

-    if covs:
-        if len(df.columns) != len(covs):
+    if covs and len(df.columns) != len(covs):
🧰 Tools
🪛 Ruff (0.8.2)

404-405: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)


502-502: Fix logger.info string formatting.

Use format string or % formatting instead of string concatenation for better logging performance.

-        logger.info("Running iteration: ", i + 1)
+        logger.info("Running iteration: %d", i + 1)
ibaqpy/ibaq/peptides2protein.py (4)

43-44: LGTM! Consider adding type hints for the logger.

The logger setup follows best practices. Consider adding type hints for better code maintainability:

-logger = logging.getLogger("ibaqpy.peptides2protein")
+logger: logging.Logger = logging.getLogger("ibaqpy.peptides2protein")

128-128: Enhance error message structure.

Consider using a more structured error message format that includes the count of nonstandard amino acids:

-    logger.error(f"Nonstandard amino acids found in {accession}: {error_aa}, ignored!")
+    logger.error(f"Found {len(error_aa)} nonstandard amino acid(s) in protein {accession}: {', '.join(error_aa)}. These will be ignored.")

337-337: Enhance data preview logging.

Add context and improve formatting of the DataFrame preview:

-    logger.info(data.head())
+    logger.info("Preview of processed peptide data:\n%s", data.head().to_string())

327-327: Address TODO comments for data integrity and documentation.

There are two TODO items that should be addressed:

  1. Implementing duplicate checks for protein lists
  2. Completing the ConcentrationWeightByProteomicRuler class documentation

Would you like me to help implement the duplicate check functionality or provide a complete class documentation? I can:

  1. Generate code to check for and handle duplicate proteins
  2. Write a comprehensive docstring for the ConcentrationWeightByProteomicRuler class

Also applies to: 136-136

ibaqpy/commands/tsne_visualization.py (2)

195-195: Enhance log message with context.

While converting print to logging is good, the message could be more descriptive for better debugging context.

Consider this improvement:

-    logger.info(total_proteins.shape)
+    logger.info("Total proteins DataFrame shape: %s", total_proteins.shape)

179-187: Add error handling and progress logging for data processing steps.

The DataFrame operations and dimensionality reduction steps could benefit from additional error handling and progress logging.

Consider these improvements:

     normalize_df = pd.pivot_table(
         total_proteins,
         index=[SAMPLE_ID, "reanalysis"],
         columns=PROTEIN_NAME,
         values=IBAQ_LOG,
     )
+    logger.debug("Created pivot table with shape: %s", normalize_df.shape)
     normalize_df = normalize_df.fillna(0)
+    logger.info("Starting PCA computation with %d components", 30)
     df_pca = compute_pca(normalize_df, n_components=30)
+    logger.info("Starting t-SNE computation")
     df_tsne = compute_tsne(df_pca)
+    logger.info("Completed dimensionality reduction")

Also consider adding try-except blocks to handle potential DataFrame operation errors:

try:
    normalize_df = pd.pivot_table(
        total_proteins,
        index=[SAMPLE_ID, "reanalysis"],
        columns=PROTEIN_NAME,
        values=IBAQ_LOG,
    )
except KeyError as e:
    logger.error("Failed to create pivot table: missing required column - %s", e)
    raise
except Exception as e:
    logger.error("Unexpected error during pivot table creation: %s", e)
    raise
tests/test_ibaqpy.py (1)

43-43: Consider adding structured logging for test parameters.

While the current logging is functional, consider using structured logging to make the test parameters more easily parseable:

-    logger.info(args)
+    logger.info("Test parameters for ibaq_compute", extra={"parameters": args})
tests/test_peptide_normalize.py (1)

51-51: Consider adding structured logging for test parameters.

While the current logging is functional, consider using structured logging to make the test parameters more easily parseable:

-    logger.info(args)
+    logger.info("Test parameters for feature_assembly", extra={"parameters": args})
ibaqpy/ibaq/combiner.py (2)

216-216: Improve logging of filtered outliers DataFrame.

Logging the entire DataFrame could produce excessive output. Consider limiting the output to key statistics or a sample of the data.

Apply this diff to improve the logging:

-        logger.info(self.df_filtered_outliers)
+        logger.info(f"Filtered outliers DataFrame stats:\n"
+                   f"Shape: {self.df_filtered_outliers.shape}\n"
+                   f"Sample of data:\n{self.df_filtered_outliers.head()}")

305-305: Improve logging of corrected DataFrame.

Logging the entire DataFrame could produce excessive output. Consider limiting the output to key statistics or a sample of the data.

Apply this diff to improve the logging:

-        logger.info(self.df_corrected)
+        logger.info(f"Batch corrected DataFrame stats:\n"
+                   f"Shape: {self.df_corrected.shape}\n"
+                   f"Sample of data:\n{self.df_corrected.head()}")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ef03ba7 and c48b46a.

📒 Files selected for processing (10)
  • ibaqpy/commands/correct_batches.py (8 hunks)
  • ibaqpy/commands/tsne_visualization.py (3 hunks)
  • ibaqpy/ibaq/combiner.py (4 hunks)
  • ibaqpy/ibaq/ibaqpy_postprocessing.py (8 hunks)
  • ibaqpy/ibaq/peptides2protein.py (4 hunks)
  • ibaqpy/ibaq/utils.py (17 hunks)
  • tests/test_batch_correction.py (2 hunks)
  • tests/test_file_utils.py (1 hunks)
  • tests/test_ibaqpy.py (2 hunks)
  • tests/test_peptide_normalize.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • ibaqpy/ibaq/ibaqpy_postprocessing.py
  • ibaqpy/commands/correct_batches.py
🧰 Additional context used
🪛 Ruff (0.8.2)
ibaqpy/ibaq/utils.py

404-405: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build
  • GitHub Check: build (3.9)
  • GitHub Check: build
🔇 Additional comments (6)
ibaqpy/ibaq/utils.py (2)

16-17: LGTM! Good logging setup.

The logger configuration follows best practices by using __name__ and adding a NullHandler to prevent "No handlers could be found" warnings.


346-350: LGTM! The custom exception class is well implemented.

The TooFewSamplesInBatch class correctly inherits from ValueError and properly formats the error message.

ibaqpy/commands/tsne_visualization.py (1)

2-2: LGTM! Logging setup follows best practices.

The logger is correctly initialized with __name__ and configured with a NullHandler, which prevents "No handlers found" warnings while allowing parent loggers to control the output.

Also applies to: 15-16

tests/test_ibaqpy.py (1)

1-2: LGTM! Logger configuration follows best practices.

The logger is properly configured with a NullHandler, which prevents "No handlers could be found" warnings while allowing parent loggers to handle the output if configured.

Also applies to: 9-10

tests/test_peptide_normalize.py (1)

1-2: LGTM! Logger configuration follows best practices.

The logger is properly configured with a NullHandler, which prevents "No handlers could be found" warnings while allowing parent loggers to handle the output if configured.

Also applies to: 8-9

tests/test_batch_correction.py (1)

13-14: LGTM! Logger configuration follows best practices.

The logger is properly configured with a NullHandler, which prevents "No handlers could be found" warnings while allowing parent loggers to handle the output if configured.

@ypriverol ypriverol requested a review from enriquea February 9, 2025 08:08
@ypriverol ypriverol merged commit d7b76a9 into master Feb 9, 2025
13 checks passed
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