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

Polish CLI #99

Merged
merged 3 commits into from
Feb 9, 2025
Merged

Conversation

mobiusklein
Copy link
Contributor

@mobiusklein mobiusklein commented Feb 8, 2025

User description

This change set tries to polish the CLI, being more intrusive than the last batch of changes because of the increase in use of the logging module.

I've replaced calls to logging.info and print with dedicated module loggers. Additionally, I moved the logging initialization into the CLI. If the code is used as a library, it will be the responsibility of the calling code to initialize logging, as is convention.

I spent some time normalizing docstrings to use the Numpydoc style, but did not get through all of them at this point. I tried to make the failure modes of run_batch_correction clearer. Are you using an AI tool to generate some of your docstrings?

Separately, I removed the parameter documentation from the click.command functions because their docstrings are injected as part of the CLI help text, and the parameters will be described by their help text.

Finally, I made the anndata import late-binding to not delay starting up the program for the optional dependency.


PR Type

Enhancement, Documentation, Bug fix


Description

  • Enhanced logging by replacing print and logging.info with dedicated loggers.

    • Added logger initialization with NullHandler for modules.
    • Introduced CLI options for log level and log file configuration.
  • Updated docstrings across multiple files to adhere to Numpydoc style.

    • Improved parameter descriptions and added missing sections like Raises and Examples.
    • Standardized return type annotations and descriptions.
  • Refactored error handling for better clarity and robustness.

    • Replaced SystemExit and print with exceptions like ValueError and custom exceptions.
    • Improved error messages for better debugging.
  • Made anndata imports conditional to avoid unnecessary dependencies during startup.


Changes walkthrough 📝

Relevant files
Enhancement
5 files
correct_batches.py
Refactored logging and updated docstrings for batch correction
+71/-53 
file_utils.py
Added logger and conditional `anndata` import                       
+12/-4   
ibaqpy_postprocessing.py
Enhanced logging and standardized docstrings                         
+79/-44 
peptide_normalization.py
Improved logging and error handling in peptide normalization
+45/-30 
ibaqpyc.py
Added CLI logging configuration options                                   
+31/-2   
Documentation
4 files
features2peptides.py
Simplified docstrings for feature-to-parquet conversion   
+1/-18   
peptides2protein.py
Simplified docstrings for peptide-to-protein computation 
+1/-17   
ibaqpy_commons.py
Updated docstrings and improved type annotations                 
+38/-12 
utils.py
Standardized docstrings and added custom exception             
+146/-75

Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Copy link
    Contributor

    coderabbitai bot commented Feb 8, 2025

    Important

    Review skipped

    Auto reviews are disabled on base/target branches other than the default branch.

    Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

    You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


    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

    qodo-merge-pro bot commented Feb 8, 2025

    Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account here.

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The new TooFewSamplesInBatch exception class has an incorrect super() call that will cause runtime errors. The correct syntax should be super().init().

    class TooFewSamplesInBatch(ValueError):
        def __init__(self, batches):
            super.__init__(
                f"Batches must contain at least two samples, the following batch factors did not: {batches}"
            )
    Exception Handling

    The error handling for pg_accessions parsing could be improved by adding more specific exception types and error messages to help with debugging.

    f_table.dropna(subset=["pg_accessions"], inplace=True)
    try:
        f_table["pg_accessions"] = f_table["pg_accessions"].apply(lambda x: x[0].split("|")[1])
    except IndexError:
        f_table["pg_accessions"] = f_table["pg_accessions"].apply(lambda x: x[0])
    except Exception as e:
        raise ValueError("Some errors occurred when parsing pg_accessions column in feature parquet!") from e
    f_table.set_index(["sequence", "pg_accessions"], inplace=True)

    Copy link
    Contributor

    qodo-merge-pro bot commented Feb 8, 2025

    Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account here.

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Fix incorrect filtering logic

    The filter_missing_value_by_group() function has incorrect logic in its return
    statement. The current condition keeps samples with FEWER proteins than the
    threshold, which is the opposite of what's intended. The lambda function needs
    to be changed to keep samples with MORE proteins than the threshold.

    ibaqpy/ibaq/utils.py [198-200]

     return df_input.groupby(col, as_index=False).filter(
    -    lambda x: len(x) < non_missing_percent_to_keep * len(df_input)
    +    lambda x: len(x) >= non_missing_percent_to_keep * len(df_input)
     )
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    __

    Why: The current logic is reversed, keeping samples with fewer proteins than the threshold instead of more. This is a critical bug that would significantly impact the data filtering results.

    High
    Fix incorrect super() call

    The super() call in TooFewSamplesInBatch.init() is incorrect - it's missing
    parentheses after super. This will cause an error when the exception is raised.
    The correct syntax should include parentheses.

    ibaqpy/ibaq/peptide_normalization.py [348-350]

     def __init__(self, batches):
    -    super.__init__(
    +    super().__init__(
             f"Batches must contain at least two samples, the following batch factors did not: {batches}"
         )

    [To ensure code accuracy, apply this suggestion manually]

    Suggestion importance[1-10]: 8

    __

    Why: The missing parentheses in super() call is a syntax error that would prevent the custom exception from being properly initialized, causing runtime errors when the exception is raised.

    Medium
    General
    Add missing log levels

    The log level mapping dictionary should include all standard Python logging
    levels for completeness. Add ERROR and CRITICAL levels.

    ibaqpy/ibaqpyc.py [14-19]

    -LOG_LEVELS = ["debug", "info", "warn"]
    +LOG_LEVELS = ["debug", "info", "warn", "error", "critical"]
     LOG_LEVELS_TO_LEVELS = {
         "debug": logging.DEBUG,
         "info": logging.INFO,
         "warn": logging.WARN,
    +    "error": logging.ERROR,
    +    "critical": logging.CRITICAL
     }
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    __

    Why: Adding ERROR and CRITICAL log levels is important for proper error handling and system monitoring, as these are standard logging levels that might be needed for critical issues and error conditions.

    Medium
    Ensure consistent log formatting

    The log file handler should have the same formatter as the root logger. Extract
    the formatter into a variable and reuse it to ensure consistent log formatting
    across handlers.

    ibaqpy/ibaqpyc.py [35-49]

    +log_formatter = logging.Formatter("%(asctime)s [%(funcName)s] - %(message)s")
     logging.basicConfig(
         format="%(asctime)s [%(funcName)s] - %(message)s", level=LOG_LEVELS_TO_LEVELS[log_level.lower()]
     )
     logging.captureWarnings()
     
     if log_file:
         if not log_file.exists():
             if not log_file.parent.exists():
                 log_file.parent.mkdir(parents=True, exist_ok=True)
             handler = logging.FileHandler(log_file)
             handler.setLevel(LOG_LEVELS_TO_LEVELS[log_level.lower()])
    -        handler.setFormatter(
    -            logging.Formatter("%(asctime)s [%(funcName)s] - %(message)s")
    -        )
    +        handler.setFormatter(log_formatter)
             logging.getLogger().addHandler(handler)
    • Apply this suggestion
    Suggestion importance[1-10]: 5

    __

    Why: The suggestion improves code maintainability by avoiding duplicate log format strings and making it easier to update the format consistently across handlers. While valid, it's a minor optimization with moderate impact.

    Low

    @ypriverol
    Copy link
    Member

    @mobiusklein This is a good point:

    I spent some time normalizing docstrings to use the Numpydoc style but did not get through all of them at this point. I tried to make the failure modes of run_batch_correction clearer. Are you using an AI tool to generate some of your docstrings?

    Because we have multiple people generating with AI but also with their Editor, we have multiple styles. I have tried to move to Numpy everything but also got stock in the middle. Do you know any tool that allows you to move all docstring to Numpy? Something like black?

    @ypriverol ypriverol merged commit 92d7b54 into bigbio:dev Feb 9, 2025
    8 of 10 checks passed
    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.

    2 participants