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

Implement more additive models #161

Merged
merged 7 commits into from
Feb 21, 2025
Merged

Implement more additive models #161

merged 7 commits into from
Feb 21, 2025

Conversation

wcxve
Copy link
Owner

@wcxve wcxve commented Feb 20, 2025

Summary by Sourcery

Implements several new additive models, including Bent Power Law, Broken Power Law, Smoothly Broken Power Law, and Lorentz models. Also adds a test to evaluate all available models.

New Features:

  • Implements a Bent Power Law model for spectral analysis.
  • Implements a Broken Power Law model for spectral analysis.
  • Implements a Smoothly Broken Power Law model for spectral analysis.
  • Implements a Lorentz model for spectral analysis.

Tests:

  • Adds a test to evaluate all available models to check for NaN values in the output.

Copy link

sourcery-ai bot commented Feb 20, 2025

Reviewer's Guide by Sourcery

This pull request introduces four new additive models (Bent Power Law, Broken Power Law, Smoothly Broken Power Law, and Lorentz) to the elisa.models.add module. It also includes a utility function for power law integration and a test to ensure that all models can be evaluated without producing NaN values.

Updated class diagram for additive models

classDiagram
    class NumIntAdditive {
        +continuum(egrid: JAXArray, params: NameValMapping): JAXArray
    }
    class AnaIntAdditive {
        +integral(egrid: JAXArray, params: NameValMapping): JAXArray
    }
    class Band extends NumIntAdditive
    class BandEp extends NumIntAdditive
    class BentPL extends NumIntAdditive {
        -_config
        +continuum(egrid: JAXArray, params: NameValMapping): JAXArray
    }
    class Blackbody extends NumIntAdditive
    class BlackbodyRad extends NumIntAdditive
    class BrokenPL extends AnaIntAdditive {
        -_config
        +integral(egrid: JAXArray, params: NameValMapping): JAXArray
    }
    class Compt extends NumIntAdditive
    class CutoffPL extends NumIntAdditive
    class Gauss extends NumIntAdditive
    class Lorentz extends AnaIntAdditive {
        -_config
        +integral(egrid: JAXArray, params: NameValMapping): JAXArray
    }
    class OTTB extends NumIntAdditive
    class OTTS extends NumIntAdditive
    class PLEnFlux extends NumIntAdditive
    class PLPhFlux extends NumIntAdditive
    class PowerLaw extends AnaIntAdditive
    class SmoothlyBrokenPL extends NumIntAdditive {
        -_config
        +continuum(egrid: JAXArray, params: NameValMapping): JAXArray
    }

    NumIntAdditive <|-- Band
    NumIntAdditive <|-- BandEp
    NumIntAdditive <|-- BentPL
    NumIntAdditive <|-- Blackbody
    NumIntAdditive <|-- BlackbodyRad
    AnaIntAdditive <|-- BrokenPL
    NumIntAdditive <|-- Compt
    NumIntAdditive <|-- CutoffPL
    NumIntAdditive <|-- Gauss
    AnaIntAdditive <|-- Lorentz
    NumIntAdditive <|-- OTTB
    NumIntAdditive <|-- OTTS
    NumIntAdditive <|-- PLEnFlux
    NumIntAdditive <|-- PLPhFlux
    AnaIntAdditive <|-- PowerLaw
    NumIntAdditive <|-- SmoothlyBrokenPL
Loading

File-Level Changes

Change Details Files
Implemented new additive models: Bent Power Law, Broken Power Law, Smoothly Broken Power Law, and Lorentz models.
  • Added BentPL class, a numerical integration additive model.
  • Added BrokenPL class, an analytical integration additive model.
  • Added SmoothlyBrokenPL class, a numerical integration additive model.
  • Added Lorentz class, an analytical integration additive model.
src/elisa/models/add.py
Added a utility function for power law integration.
  • Added _powerlaw_integral function to calculate the integral of a power law.
src/elisa/models/add.py
Added a test to evaluate all models.
  • Added test_model_eval to check for NaN values in model evaluations over a wide energy grid.
tests/test_model.py

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!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

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

Copy link

@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 @wcxve - I've reviewed your changes - here's some feedback:

Overall Comments:

  • It would be good to include a unit test for each of the new models.
  • Consider refactoring common logic into helper functions to reduce code duplication between models.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

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.

idx = jnp.flatnonzero(mask, size=egrid.size - 1)[-1]
pb1 = _powerlaw_integral(jnp.hstack([egrid_[idx], Eb]), alpha1)
pb2 = _powerlaw_integral(jnp.hstack([Eb, egrid_[idx + 1]]), alpha2)
f.at[idx].set(sum(pb1 + pb2))
Copy link

Choose a reason for hiding this comment

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

suggestion (performance): Consider using jnp.sum rather than the built-in sum.

Using Python’s built-in sum on arrays can be unpredictable in a JAX context. Switching to jnp.sum or a similar JAX-native operation might improve clarity and performance.

Suggested change
f.at[idx].set(sum(pb1 + pb2))
f.at[idx].set(jnp.sum(pb1 + pb2))


@staticmethod
def integral(egrid: JAXArray, params: NameValMapping) -> JAXArray:
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider refactoring the integral calculation in BrokenPL to use vectorized operations and piecewise integration, avoiding manual index finding and in-place updates.

Consider refactoring the integral so that you avoid manual index‐finding and in-place updates. For example, instead of building a mask, extracting an index with `jnp.flatnonzero`, and then patching that bin with a custom “cross‐bin” calculation, you can compute the definite integrals in a vectorized, piecewise manner. One approach is:

```python
@staticmethod
def integral(egrid: JAXArray, params: NameValMapping) -> JAXArray:
    alpha1 = params['alpha1']
    Eb = params['Eb']
    alpha2 = params['alpha2']
    K = params['K']

    # Define the antiderivative in terms of the normalized energy E/Eb.
    def antideriv(E, alpha):
        return _powerlaw_integral(E / Eb, alpha)

    # Bin edges
    E_low = egrid[:-1]
    E_high = egrid[1:]

    # Determine which bins are fully below, fully above, or cross the break.
    lower_bins = E_high <= Eb
    upper_bins = E_low >= Eb
    cross_bins = ~(lower_bins | upper_bins)

    # Compute integrals for bins entirely in one regime:
    int_lower = antideriv(E_high[lower_bins], alpha1) - antideriv(E_low[lower_bins], alpha1)
    int_upper = antideriv(E_high[upper_bins], alpha2) - antideriv(E_low[upper_bins], alpha2)
    # For bins that cross the break, split the integration at Eb.
    int_cross = (antideriv(Eb, alpha1) - antideriv(E_low[cross_bins], alpha1) +
                 antideriv(E_high[cross_bins], alpha2) - antideriv(Eb, alpha2))

    # Allocate and fill the result.
    result = jnp.empty(egrid.size - 1)
    result = result.at[lower_bins].set(int_lower)
    result = result.at[upper_bins].set(int_upper)
    result = result.at[cross_bins].set(int_cross)

    return K * result

This approach removes the need for manual index extraction and in-place patching while preserving all functionality. Adjust the antiderivative logic if needed based on your implementation of _powerlaw_integral.

@wcxve
Copy link
Owner Author

wcxve commented Feb 21, 2025

@sourcery-ai review

Copy link

@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 @wcxve - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a short description of the parameters to the docstrings of the new models.
  • It might be good to have a consistent style for the parameter names (e.g. El vs E_l).
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

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.

p1 = _powerlaw_integral(egrid_, alpha1)
p2 = _powerlaw_integral(egrid_, alpha2)
f = jnp.where(mask, p1, p2)
idx = jnp.flatnonzero(mask, size=egrid.size - 1)[-1]
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Potential normalization mismatch in BrokenPL.integral endpoints.

In BrokenPL.integral, the energy grid is normalized (egrid_ = egrid / Eb) so that the break occurs at 1, yet when computing pb1 and pb2 the code uses Eb directly. Verify that the endpoints for _powerlaw_integral are correctly scaled (possibly using 1.0 rather than Eb) to ensure consistency.

Comment on lines 192 to 193
egrid = np.geomspace(1e-4, 1e9, 1301)
assert not np.any(np.isnan(model(**kwargs).compile().eval(egrid)))
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Consider testing for infinite values.

Besides NaN values, it's also important to check for infinite values, as they can also indicate issues with the models. Suggest adding np.isinf checks as well.

]


def _powerlaw_integral(egrid: JAXArray, alpha: JAXArray) -> JAXArray:
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider refactoring the integration logic in _powerlaw_integral and BrokenPL.integral into smaller, purpose-specific helper functions to improve readability and maintainability.

Consider extracting parts of the integration logic into small, purpose‐specific helper functions to simplify the conditional handling and array slicing. For example, in _powerlaw_integral you can separate the power‐law and logarithmic parts:

def _integral_non_unity(egrid: JAXArray, alpha: JAXArray) -> JAXArray:
    one_minus_alpha = 1.0 - alpha
    f = jnp.power(egrid, one_minus_alpha) / one_minus_alpha
    return f[1:] - f[:-1]

def _integral_unity(egrid: JAXArray) -> JAXArray:
    f = jnp.log(egrid)
    return f[1:] - f[:-1]

def _powerlaw_integral(egrid: JAXArray, alpha: JAXArray) -> JAXArray:
    # Use jnp.not_equal to decide which integration rule to apply
    condition = jnp.not_equal(alpha, 1.0)
    f1 = _integral_non_unity(egrid, alpha)
    f2 = _integral_unity(egrid)
    return jnp.where(condition[:-1], f1, f2)

Similarly, in the integral method for BrokenPL, isolate the break-region adjustment:

def _adjust_break_integral(egrid_: JAXArray, Eb: float, alpha1: float, alpha2: float, idx: int) -> float:
    pb1 = _powerlaw_integral(jnp.hstack([egrid_[idx], Eb]), alpha1)
    pb2 = _powerlaw_integral(jnp.hstack([Eb, egrid_[idx + 1]]), alpha2)
    return pb1[0] + pb2[0]

# In the BrokenPL.integral method:
mask = egrid[:-1] <= Eb
# ... existing setup ...
idx = jnp.flatnonzero(mask, size=egrid.size - 1)[-1]
f = f.at[idx].set(_adjust_break_integral(egrid_, Eb, alpha1, alpha2, idx))

These small refactorings keep functionality intact while isolating complex operations, making the code easier to read and maintain without reverting any changes.

@wcxve wcxve merged commit 86827d2 into main Feb 21, 2025
9 checks passed
@wcxve wcxve deleted the more-models branch February 21, 2025 07:10
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.

1 participant