Skip to content

Fix array dimension handling for x_normalized#3

Merged
hbmartin merged 3 commits intomainfrom
x_normalized-fix
Jul 17, 2025
Merged

Fix array dimension handling for x_normalized#3
hbmartin merged 3 commits intomainfrom
x_normalized-fix

Conversation

@hbmartin
Copy link
Copy Markdown
Owner

@hbmartin hbmartin commented Jul 17, 2025

Summary by Sourcery

Fix array dimension handling in the log-space fallback for beta PPF, add tests to verify correct behavior for scalar and array inputs, and bump the package version.

Bug Fixes:

  • Use flat indexing in _ppf_fallback_log_space results to correctly handle array returns from beta.ppf

Build:

  • Bump package version from 0.1.7 to 0.1.8

Tests:

  • Add test to ensure _ppf_fallback_log_space handles both scalar and array inputs and preserves shapes, bounds, and finiteness

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced support for multi-dimensional array inputs, including 3D arrays, ensuring correct output shape and value bounds.
  • Chores

    • Updated the application version to 0.1.8.

Important

Fix array dimension handling in _ppf_fallback_log_space and add tests for scalar and array inputs, updating package version to 0.1.8.

  • Bug Fixes:
    • Fix array dimension handling in _ppf_fallback_log_space in funcs.py to correctly handle array returns from beta.ppf.
    • Use np.ndenumerate for flat indexing in _ppf_fallback_log_space.
  • Tests:
    • Add tests in test_ppf_log_fallback.py to verify _ppf_fallback_log_space handles scalar and array inputs, preserving shapes and bounds.
    • Test cases include 1D, 2D, and 3D arrays, and edge cases for extreme probabilities.
  • Build:
    • Bump package version in pyproject.toml from 0.1.7 to 0.1.8.

This description was created by Ellipsis for 6277e54. You can customize this summary. It will automatically update as commits are pushed.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Jul 17, 2025

Reviewer's Guide

This PR fixes array dimension handling in the log-space PPF fallback by switching to flat indexing, adds tests for both scalar and array inputs to verify correct output shape and value constraints, and bumps the package version.

Class diagram for updated log_cdf_eq function array handling

classDiagram
    class log_cdf_eq {
        +log_cdf_eq(x_normalized)
        # results: ndarray
    }
    log_cdf_eq : results.flat[i] assignment
    log_cdf_eq : returns scalar or array depending on input
Loading

File-Level Changes

Change Details Files
Use flat indexing for PPF fallback assignment
  • Replaced results[i] with results.flat[i] to correctly map values in multi-dimensional arrays.
betapert/funcs.py
Add tests for scalar and array fallback behavior
  • Added a test for scalar input to assert type, range, and finiteness.
  • Added a test for array input to assert output is an ndarray, matches input shape, and respects bounds and finiteness.
tests/test_ppf_log_fallback.py
Bump project version
  • Incremented version from 0.1.7 to 0.1.8.
pyproject.toml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 17, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The _ppf_fallback_log_space function in betapert/funcs.py was updated to use np.ndenumerate for iterating and assigning results in multi-dimensional arrays, added a DEBUG flag with optional error logging, and improved exception handling. The project version in pyproject.toml was incremented from 0.1.7 to 0.1.8. A new test was added to verify 3D input handling in tests/test_ppf_log_fallback.py.

Changes

File(s) Change Summary
betapert/funcs.py Enhanced _ppf_fallback_log_space with np.ndenumerate for multi-dimensional indexing, added DEBUG flag and detailed error logging.
pyproject.toml Bumped version number from 0.1.7 to 0.1.8.
tests/test_ppf_log_fallback.py Added test_log_fallback_3d_input method to test _ppf_fallback_log_space with 3D numpy arrays, verifying shape, bounds, and finiteness.

Possibly related PRs

Suggested labels

Review effort 4/5

Poem

A hop and a skip through arrays so wide,
Now indices match on every side.
Debug logs whisper secrets bright,
Catching errors in the night.
Version bumped, tests in flight—
Multi-dim arrays handled just right!
🐇✨


📜 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 6dbd6aa and 6277e54.

📒 Files selected for processing (2)
  • betapert/funcs.py (3 hunks)
  • tests/test_ppf_log_fallback.py (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @hbmartin, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical bug related to array dimension handling within the betapert library's probability point function (PPF) fallback logic. The change ensures that the calculation correctly assigns values when scipy.stats.beta.ppf returns an array, preventing a ValueError and improving the robustness of the numerical computations. A new test case has been added to validate this fix, enhancing the overall stability of the library.

Highlights

  • Bug Fix: Array Dimension Handling: Corrected an issue in betapert/funcs.py within the log_cdf_eq function's fallback mechanism. Previously, results[i] = mini + (maxi - mini) * x_normalized could lead to a ValueError if x_normalized was an array (e.g., when scipy.stats.beta.ppf returned an array). This has been fixed by using results.flat[i] = ... to ensure correct assignment regardless of x_normalized's shape, treating the results array as a flat sequence for individual element assignment.
  • New Test Case: Added a new test test_log_fallback_handles_beta_ppf_array_return in tests/test_ppf_log_fallback.py. This test specifically validates that the _ppf_fallback_log_space function correctly handles cases where scipy.stats.beta.ppf returns an array, ensuring robustness for both scalar and array inputs and preventing the ValueError that the fix addresses.
  • Version Update: The project version in pyproject.toml has been incremented from 0.1.7 to 0.1.8, reflecting this bug fix.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review Bot commented Jul 17, 2025

PR Reviewer Guide 🔍

(Review updated until commit 6dbd6aa)

Here are some key observations to aid the review process:

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

Indexing Logic

The change from enumerate(_q.flat) to np.ndenumerate(_q) and from results.flat[i] to results[i] needs verification that the indexing behavior is correct for multidimensional arrays and that the results array is properly initialized with the right shape.

for i, qi in np.ndenumerate(_q):
    try:
        # Use brentq instead of fsolve, guaranteed convergence within bounds
        x_normalized = scipy.optimize.brentq(
            make_log_cdf_eq(qi),
            _BRENTQ_BOUND,
            1 - _BRENTQ_BOUND,
        )
        results[i] = mini + (maxi - mini) * x_normalized

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @hbmartin - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `tests/test_ppf_log_fallback.py:349` </location>
<code_context>
+        """Test that log fallback correctly handles when beta.ppf returns an array."""
+        mini, mode, maxi = 0, 1, 10
+
+        # Test scalar input - this used to cause "ValueError: setting an array element with a sequence"
+        q_scalar = 0.5
+        result_scalar = funcs._ppf_fallback_log_space(q_scalar, mini, mode, maxi, 4)
+        
+        assert isinstance(result_scalar, np.number)
+        assert mini <= result_scalar <= maxi
+        assert np.isfinite(result_scalar)
+        
+        # Test array input 
</code_context>

<issue_to_address>
Consider adding a test for q values at the boundaries (0 and 1) to ensure correct clipping behavior.

Explicitly test q=0 and q=1 to verify the function returns valid, finite results without errors at these boundaries.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/test_ppf_log_fallback.py Outdated
@openhands-ai
Copy link
Copy Markdown

openhands-ai Bot commented Jul 17, 2025

Looks like there are a few issues preventing this PR from being merged!

  • GitHub Actions are failing:
    • Pytest, ruff, and black

If you'd like me to help, just leave a comment, like

@OpenHands please fix the failing actions on PR #3

Feel free to include any additional details that might help me get this PR into a better state.

You can manage your notification settings

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review Bot commented Jul 17, 2025

PR Code Suggestions ✨

No code suggestions found for the PR.

Copy link
Copy Markdown

@ellipsis-dev ellipsis-dev Bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to 8079cf8 in 52 seconds. Click for details.
  • Reviewed 56 lines of code in 3 files
  • Skipped 0 files when reviewing.
  • Skipped posting 2 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. betapert/funcs.py:44
  • Draft comment:
    Good fix: using results.flat[i] guarantees correct assignment for multi‐dimensional arrays. Consider adding a brief inline comment explaining this usage for future maintainability.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. tests/test_ppf_log_fallback.py:325
  • Draft comment:
    Direct comparison on a NumPy array (e.g. 'assert mini <= result_single <= maxi') may yield ambiguous truth values. Consider using np.all(result_single >= mini) and np.all(result_single <= maxi) or converting the single‐element array to a scalar (e.g. result_single.item()).
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.

Workflow ID: wflow_oZuUJOzIIh66fvH3

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request correctly fixes a bug in array dimension handling for the log-space fallback by using flat indexing. The version bump is appropriate, and the new tests improve coverage for scalar and array inputs. I've added one medium-severity comment to suggest improving the clarity of the new test's name and documentation to better reflect the nature of the fix.

Comment thread tests/test_ppf_log_fallback.py Outdated
Comment on lines +345 to +346
def test_log_fallback_handles_beta_ppf_array_return(self):
"""Test that log fallback correctly handles when beta.ppf returns an array."""
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The test name and docstring could be misleading about the nature of the bug being fixed.

The root cause of the issue addressed by using results.flat[i] is the handling of multi-dimensional q arrays, not necessarily beta.ppf returning an array. When q is multi-dimensional, results is as well. The loop iterates with a flat index i, so results[i] would incorrectly reference an entire row, while results.flat[i] correctly targets a single element.

For beta.ppf to return an array in this context, alpha or beta would need to be arrays, which would likely cause the brentq call in the try block to fail before reaching the fallback logic, as brentq expects a scalar-valued function.

To improve clarity and future maintainability, I recommend renaming the test and updating its docstring to more accurately reflect the problem of handling multi-dimensional inputs. For example:

To improve clarity and future maintainability, I recommend renaming the test and updating its docstring to more accurately reflect the problem of handling multi-dimensional inputs. For example, rename test_log_fallback_handles_beta_ppf_array_return to test_log_fallback_handles_multidimensional_q and update the docstring to Test that log fallback correctly handles multi-dimensional q and preserves shapes.

Copy link
Copy Markdown

@ellipsis-dev ellipsis-dev Bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 6dbd6aa in 1 minute and 11 seconds. Click for details.
  • Reviewed 61 lines of code in 2 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. betapert/funcs.py:36
  • Draft comment:
    Using np.ndenumerate instead of enumerate(_q.flat) correctly preserves multi-dimensional indices. This is a clear improvement for handling array dimensions.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. betapert/funcs.py:44
  • Draft comment:
    Updating assignment from results.flat[i] to results[i] aligns with the use of np.ndenumerate and improves readability.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
3. tests/test_ppf_log_fallback.py:341
  • Draft comment:
    The redundant test 'test_log_fallback_handles_beta_ppf_array_return' has been removed. Ensure that existing tests adequately cover both scalar and array outputs.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None

Workflow ID: wflow_cP7gJdETvtttuSPa

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

@hbmartin
Copy link
Copy Markdown
Owner Author

/review

@qodo-code-review
Copy link
Copy Markdown

Persistent review updated to latest commit 6dbd6aa

@hbmartin hbmartin merged commit 3e9d2f7 into main Jul 17, 2025
3 of 4 checks passed
@hbmartin hbmartin deleted the x_normalized-fix branch July 17, 2025 23:33
Copy link
Copy Markdown

@ellipsis-dev ellipsis-dev Bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 6277e54 in 1 minute and 28 seconds. Click for details.
  • Reviewed 76 lines of code in 2 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. betapert/funcs.py:18
  • Draft comment:
    Consider using Python’s logging module instead of sys.stderr.write for debug messages. This improves flexibility and allows better control over logging levels.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. betapert/funcs.py:52
  • Draft comment:
    Good improvement: capturing the exception as 'e' allows logging detailed error info in DEBUG mode.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
3. tests/test_ppf_log_fallback.py:316
  • Draft comment:
    Consider using np.isscalar(result_scalar) to check for scalar output instead of isinstance(result_scalar, np.number), since built‐in floats may not always be recognized as np.number.
  • Reason this comment was not posted:
    Confidence changes required: 50% <= threshold 50% None
4. tests/test_ppf_log_fallback.py:327
  • Draft comment:
    When testing single-element array returns, avoid chain comparisons (e.g. 'assert mini <= result_single <= maxi') since they can be ambiguous for numpy arrays. Use elementwise checks like np.all(result_single >= mini) and np.all(result_single <= maxi).
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.

Workflow ID: wflow_bVCIdCxQC4DnzxpF

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

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.

1 participant