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

added logging output and description #96

Merged
merged 2 commits into from
Feb 7, 2025
Merged

Conversation

enriquea
Copy link
Contributor

@enriquea enriquea commented Feb 7, 2025

PR Type

Enhancement, Documentation


Description

  • Added logging outputs for key operations in batch correction.

  • Enhanced command-line interface with a short help description.

  • Improved documentation for the correct_batches command.

  • Logged metadata creation in AnnData object utility.


Changes walkthrough 📝

Relevant files
Enhancement
correct_batches.py
Added logging and improved CLI documentation                         

ibaqpy/commands/correct_batches.py

  • Introduced logging for loading data, batch correction, and exporting.
  • Added a short help description to the correct-batches command.
  • Enhanced docstring for the correct_batches command.
  • Logged completion of batch correction process.
  • +14/-1   
    file_utils.py
    Logged metadata creation in AnnData utility                           

    ibaqpy/ibaq/file_utils.py

  • Added logging for AnnData object creation.
  • Enhanced visibility into metadata creation process.
  • +3/-0     

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

    • New Features
      • Enhanced process tracking with improved logging, providing greater visibility into key batch correction and data export steps.
    • Documentation
      • Updated command help texts and usage descriptions for clearer guidance on applying batch effect corrections.

    Copy link
    Contributor

    coderabbitai bot commented Feb 7, 2025

    Walkthrough

    The changes add logging capabilities to two modules. In the commands module, logging statements have been inserted within the batch correction routine to note key steps, and the command’s docstring and decorator have been enhanced with clearer descriptions and a short help. In the file utilities module, the logging module is imported and a log statement is added to record the creation of an AnnData object. The core logic and execution flow remain unchanged.

    Changes

    File(s) Change Summary
    ibaqpy/commands/correct_batches.py Added logging statements in run_batch_correction; expanded the command’s docstring and updated the click decorator with a short help description.
    ibaqpy/ibaq/file_utils.py Introduced the logging module and added a log call in create_anndata to record the creation of the AnnData object.

    Possibly related PRs

    • Added cli option for batch correction #91: The changes in the main PR, which enhance logging and documentation for the correct_batches command, are directly related to the modifications in the retrieved PR that also involve the correct_batches command and its associated functions. Both PRs focus on the same command and its functionality.

    Suggested labels

    Review effort [1-5]: 4

    Poem

    I'm a rabbit with code so neat,
    Logging each step with a rhythmic beat.
    Batches corrected with gentle care,
    Docstrings and decorators now clear and fair.
    I nibble on carrots as the log entries flow,
    Hopping through updates, watch our project grow!
    🐇🥕


    📜 Recent review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between bdbe25c and 17215dd.

    📒 Files selected for processing (2)
    • ibaqpy/commands/correct_batches.py (5 hunks)
    • ibaqpy/ibaq/file_utils.py (2 hunks)
    🚧 Files skipped from review as they are similar to previous changes (2)
    • ibaqpy/ibaq/file_utils.py
    • ibaqpy/commands/correct_batches.py
    ⏰ Context from checks skipped due to timeout of 90000ms (2)
    • GitHub Check: build
    • GitHub Check: Codacy Static Code Analysis

    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 7, 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: 2 🔵🔵⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The logging messages are added after the try blocks, so they won't be logged if an error occurs. Consider moving logging statements inside try blocks for better error tracking.

    logging.info(f"Loading iBAQ data from TSV files in folder '{folder}'")
    try:
        df_ibaq = combine_ibaq_tsv_files(folder, pattern=pattern, comment=comment, sep=sep)
    except Exception as e:
        raise ValueError(f"Failed to load input files: {str(e)}")
    Log Level

    All logging statements use info level. Consider using different log levels (debug, warning, error) for different types of messages to enable better log filtering.

    logging.info(f"Loading iBAQ data from TSV files in folder '{folder}'")
    try:
        df_ibaq = combine_ibaq_tsv_files(folder, pattern=pattern, comment=comment, sep=sep)
    except Exception as e:
        raise ValueError(f"Failed to load input files: {str(e)}")
    
    # Reshape the data to wide format
    df_wide = pivot_wider(
        df_ibaq,
        row_name=protein_id_column,
        col_name=sample_id_column,
        values=ibaq_raw_column,
        fillna=True,
    )
    
    # Validate the sample IDs
    if not is_valid_sample_id(df_wide.columns, SAMPLE_ID_REGEX):
        raise ValueError("Invalid sample IDs found in the data.")
    
    # Get the batch IDs
    batch_ids = get_batch_id_from_sample_names(df_wide.columns)
    
    # Run batch correction
    logging.info("Applying batch correction to iBAQ values")
    df_corrected = apply_batch_correction(df_wide, list(batch_ids), kwargs={})
    
    # Convert the data back to long format
    df_corrected = df_corrected.reset_index()
    df_corrected_long = pivot_longer(
        df_corrected,
        row_name=protein_id_column,
        col_name=sample_id_column,
        values=ibaq_corrected_column,
    )
    
    # Add the corrected ibaq values to the original dataframe.
    # Use sample/protein ID keys to merge the dataframes.
    df_ibaq = df_ibaq.merge(
        df_corrected_long, how="left", on=[sample_id_column, protein_id_column]
    )
    
    # Save the corrected iBAQ values to a file
    if output:
        try:
            df_ibaq.to_csv(output, sep=sep, index=False)
        except Exception as e:
            raise ValueError(f"Failed to save output file: {str(e)}")
    
    # Export the raw and corrected iBAQ values to an AnnData object
    if export_anndata:
        logging.info("Exporting raw and corrected iBAQ values to an AnnData object")
        output_path = Path(output)
        if not output_path.exists():
            raise FileNotFoundError(f"Output file {output} does not exist!")
        adata = create_anndata(
            df_ibaq,
            obs_col=sample_id_column,
            var_col=protein_id_column,
            value_col=ibaq_raw_column,
            layer_cols=[ibaq_corrected_column],
        )
        adata_filename = output_path.with_suffix('.h5ad')
        try:
            adata.write(adata_filename)
        except Exception as e:
            raise ValueError(f"Failed to write AnnData object: {e}")
    
    logging.info("Batch correction completed...")

    @enriquea enriquea self-assigned this Feb 7, 2025
    Copy link
    Contributor

    qodo-merge-pro bot commented Feb 7, 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
    General
    Improve logging severity levels

    Add log level to the logging messages to better indicate severity. Use
    logging.debug() for detailed progress info and logging.warning()/error() for
    issues.

    ibaqpy/commands/correct_batches.py [109-113]

    -logging.info(f"Loading iBAQ data from TSV files in folder '{folder}'")
    +logging.debug(f"Loading iBAQ data from TSV files in folder '{folder}'")
     try:
         df_ibaq = combine_ibaq_tsv_files(folder, pattern=pattern, comment=comment, sep=sep)
     except Exception as e:
    +    logging.error(f"Failed to load input files: {str(e)}")
         raise ValueError(f"Failed to load input files: {str(e)}")
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    __

    Why: The suggestion improves logging practices by using appropriate severity levels and adds error logging before raising exceptions, which enhances debugging capabilities and log completeness.

    Medium
    Add data size to logs

    The AnnData object logging should include size information to help track memory
    usage and data scale.

    ibaqpy/ibaq/file_utils.py [108]

    -logging.info(f"Created AnnData object:\n {adata}")
    +logging.info(f"Created AnnData object with shape {adata.shape} and {len(adata.layers)} layers")
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    __

    Why: The suggestion enhances logging by including specific size information about the AnnData object, which is valuable for monitoring memory usage and understanding data scale in production environments.

    Low

    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

    🧹 Nitpick comments (2)
    ibaqpy/ibaq/file_utils.py (1)

    108-109: Consider adjusting the logging level and format.

    1. For large AnnData objects, logging at INFO level might be too verbose. Consider using DEBUG level instead.
    2. The newline character in the format string might affect log parsing.

    Apply this diff to improve the logging:

    -    logging.info(f"Created AnnData object:\n {adata}")
    +    logging.debug(f"Created AnnData object: {adata}")
    ibaqpy/commands/correct_batches.py (1)

    109-109: Enhance logging messages with more context.

    The logging statements could provide more detailed information about the process:

    1. Include the pattern when logging file loading
    2. Include the batch correction parameters
    3. Include the output path when logging AnnData export
    4. Include summary statistics in the completion message

    Apply this diff to improve the logging messages:

    -    logging.info(f"Loading iBAQ data from TSV files in folder '{folder}'")
    +    logging.info(f"Loading iBAQ data from TSV files in folder '{folder}' with pattern '{pattern}'")
    
    -    logging.info("Applying batch correction to iBAQ values")
    +    logging.info(f"Applying batch correction to iBAQ values for {len(batch_ids)} batches")
    
    -    logging.info("Exporting raw and corrected iBAQ values to an AnnData object")
    +    logging.info(f"Exporting raw and corrected iBAQ values to AnnData object at {adata_filename}")
    
    -    logging.info("Batch correction completed...")
    +    logging.info(f"Batch correction completed. Processed {len(df_ibaq)} samples across {len(batch_ids)} batches")

    Also applies to: 132-132, 159-159, 176-176

    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between 5ced41d and bdbe25c.

    📒 Files selected for processing (2)
    • ibaqpy/commands/correct_batches.py (6 hunks)
    • ibaqpy/ibaq/file_utils.py (2 hunks)
    ⏰ Context from checks skipped due to timeout of 90000ms (2)
    • GitHub Check: Codacy Static Code Analysis
    • GitHub Check: build
    🔇 Additional comments (4)
    ibaqpy/ibaq/file_utils.py (2)

    2-2: LGTM!

    The logging module import is correctly placed with other standard library imports.


    1-110: Verify logging configuration.

    Ensure that logging is properly configured at the application level to handle these log messages effectively.

    Run this script to check for logging configuration:

    🧰 Tools
    🪛 Ruff (0.8.2)

    78-78: No explicit stacklevel keyword argument found

    (B028)


    99-99: No explicit stacklevel keyword argument found

    (B028)

    ibaqpy/commands/correct_batches.py (2)

    1-1: LGTM!

    The logging module import is correctly placed at the top with other standard library imports.


    181-181: LGTM!

    The command decorator and docstring improvements enhance clarity and usability:

    1. Short help description is concise and informative
    2. Docstring clearly explains the command's functionality

    Also applies to: 254-260

    @ypriverol ypriverol merged commit 9d18299 into bigbio:master Feb 7, 2025
    4 of 5 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