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

adding instrumental model #221

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

adding instrumental model #221

wants to merge 1 commit into from

Conversation

renecotyfanboy
Copy link
Owner

@renecotyfanboy renecotyfanboy commented Feb 6, 2025

Summary by Sourcery

Add support for instrument models in spectral fitting.

New Features:

  • Introduce instrument models to account for gain and shift variations during spectral fitting.

Tests:

  • Update tests to cover the new instrument model functionality.

📚 Documentation preview 📚: https://jaxspec--221.org.readthedocs.build/en/221/

Copy link

sourcery-ai bot commented Feb 6, 2025

Reviewer's Guide by Sourcery

This pull request introduces an instrumental model to the fitting process, allowing for the calibration of energy gain and shift in observations. It also includes minor fixes and improvements to integration and plotting functionalities.

Sequence diagram for forward model with instrument calibration

sequenceDiagram
    participant FM as Forward Model
    participant IM as Instrument Model
    participant M as Model

    FM->>IM: get_gain_and_shift_model(obs_name)
    alt observation is reference
        IM-->>FM: None, None
    else observation needs calibration
        IM-->>FM: gain_func, shift_func
    end

    Note over FM: Apply energy shift if present
    Note over FM: Apply gain correction if present
    FM->>M: photon_flux(parameters, energies)
    M-->>FM: flux
    Note over FM: Apply transfer matrix
Loading

Class diagram for the new instrument model hierarchy

classDiagram
    class InstrumentModel {
      +reference_observation_name: str
      +gain_model: GainModel
      +shift_model: ShiftModel
      +get_gain_and_shift_model(observation_name: str)
    }

    class GainModel {
      <<abstract>>
      +numpyro_model(observation_name: str)*
    }

    class ShiftModel {
      <<abstract>>
      +numpyro_model(observation_name: str)*
    }

    class ConstantGain {
      +prior_distribution: Distribution
      +numpyro_model(observation_name: str)
    }

    class PolynomialGain {
      +prior_distribution: Distribution
      +degree: int
      +numpyro_model(observation_name: str)
    }

    class PolynomialShift {
      +prior_distribution: Distribution
      +degree: int
      +numpyro_model(observation_name: str)
    }

    GainModel <|-- ConstantGain
    GainModel <|-- PolynomialGain
    ShiftModel <|-- PolynomialShift
    InstrumentModel o-- GainModel
    InstrumentModel o-- ShiftModel
Loading

File-Level Changes

Change Details Files
Introduced an instrumental model for energy gain and shift calibration.
  • Added InstrumentModel class to handle gain and shift models.
  • Implemented ConstantGain and PolynomialGain models for gain calibration.
  • Implemented PolynomialShift model for shift calibration.
  • Modified the fitting process to incorporate gain and shift models during forward modeling.
src/jaxspec/fit.py
src/jaxspec/_fit/_build_model.py
src/jaxspec/model/instrument.py
Fixed and improved integration functionalities.
  • Added typing to integrate.py
  • Fixed gradient calculation in integration functions.
  • Added more tests for integration.
src/jaxspec/util/integrate.py
tests/test_integrate.py
Improved plot_ppc function for better visualization.
  • Handled NaN values in plot_ppc function.
  • Improved plot limits and labels.
  • Added title to the plot.
src/jaxspec/analysis/results.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 @renecotyfanboy - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Replace np.nanmin/np.nanmax calls with min/max or np.minimum/np.maximum when comparing scalar values (e.g. lowest_y and y_observed_bkg) to avoid parameter misinterpretation.
  • Use the correct keyword (a_min) in jnp.clip to ensure consistency with the JAX API.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 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.

src/jaxspec/_fit/_build_model.py Show resolved Hide resolved


class InstrumentModel:
def __init__(
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider adding validation for gain and shift model combinations

Some combinations of gain and shift models might not be physically meaningful or could lead to numerical instabilities. Consider adding validation in the constructor.

Suggested implementation:

    def __init__(
        self,
        reference_observation_name: str,
        gain_model: GainModel | None = None,
        shift_model: ShiftModel | None = None,
    ):
        self.reference = reference_observation_name

        # Validate gain and shift model combinations
        if gain_model is not None and shift_model is not None:
            # Check if both models reference the same observation
            if (gain_model.reference != reference_observation_name or 
                shift_model.reference != reference_observation_name):
                raise ValueError(
                    "When both gain and shift models are used, they must reference "
                    "the same observation as the instrument model."
                )

            # Add any physics-based validation specific to your use case
            # For example, if certain polynomial orders shouldn't be combined
            if isinstance(gain_model, PolynomialGainModel) and isinstance(shift_model, PolynomialShiftModel):
                if gain_model.order > 1 and shift_model.order > 1:
                    raise ValueError(
                        "Using high-order polynomials for both gain and shift "
                        "simultaneously may lead to numerical instabilities."
                    )

        self.gain_model = gain_model
        self.shift_model = shift_model

The implementation above assumes:

  1. GainModel and ShiftModel classes have a 'reference' attribute
  2. There are PolynomialGainModel and PolynomialShiftModel classes with an 'order' attribute

You may need to:

  1. Adjust the specific validation rules based on your physics requirements
  2. Add or modify the checks based on the actual model types you support
  3. Update the error messages to match your project's terminology

Return the gain and shift models for the given observation. It should be called within a numpyro model.
"""

if observation_name == self.reference:
Copy link

Choose a reason for hiding this comment

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

issue (code-quality): Remove unnecessary else after guard condition (remove-unnecessary-else)

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