Skip to content

CRM update#105

Merged
Fontanapink merged 7 commits intomasterfrom
CRM
Apr 9, 2025
Merged

CRM update#105
Fontanapink merged 7 commits intomasterfrom
CRM

Conversation

@ChaniaClare
Copy link
Copy Markdown
Member

@ChaniaClare ChaniaClare commented Apr 9, 2025

Pull Request To-Do List

Description of the changes:

I have done the following to make this PR ready for review:

  • I have re-based my branch on the latest master branch
  • I have added necessary documentation (if appropriate)
  • I have commented my code, particularly in hard-to-understand areas
  • I have assigned a reviewer to this PR

For the reviewer, make sure this PR meets these criteria before merging:

  • New code has comments
  • New code has tests (if appropriate)
  • New code has documentation (if appropriate)
  • New code has been reviewed by at least one other person

Summary by Sourcery

Enhance the Consumer-Resource Model (CRM) plotting utilities by adding a new function to visualize model dynamics with confidence intervals and true data points

New Features:

  • Add a new plotting function plot_CRM_with_intervals that supports visualization of model trajectories with 95% credible intervals and optional true data overlay

Enhancements:

  • Improve visualization capabilities for Consumer-Resource Model by adding support for confidence intervals
  • Extend plotting functionality to include scatter points from true data for comparison

Chores:

  • Minor formatting adjustment in the Bayesian inference code

ChaniaClare and others added 6 commits April 4, 2025 15:57
Added plot of CRM with confidence intervals, and removed some old notes
improved CRM plotting with confidence intervals and made a function in utilities.py
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Apr 9, 2025

Reviewer's Guide by Sourcery

This pull request introduces a new plotting function for visualizing CRM dynamics with credible intervals and modifies the shape of the sigma parameter in the run_inference function within infer_CRM_bayes.py.

No diagrams generated as the changes look simple and do not need a visual representation.

File-Level Changes

Change Details Files
Added a new function plot_CRM_with_intervals to visualize CRM dynamics with credible intervals.
  • Implemented plotting of median trajectories for species and resources.
  • Implemented plotting of confidence intervals (ribbons) around the median trajectories.
  • Added functionality to overlay true data points from a CSV file for comparison.
  • Added labels, titles, and legends for clarity.
  • Added functionality to save the plot to a file.
mimic/utilities/utilities.py
Modified the run_inference function in infer_CRM_bayes.py to adjust the shape of the sigma parameter.
  • Changed the shape of the 'sigma' parameter in the pm.HalfNormal distribution to (1,).
mimic/model_infer/infer_CRM_bayes.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
Copy Markdown
Contributor

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

Overall Comments:

  • Consider extracting the plotting logic into a separate module to improve code organization.
  • It might be helpful to add argument validation to the plotting functions.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 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.


return fig, ax

def plot_CRM_with_intervals(observed_species, observed_resources, species_lower, species_upper,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider extracting the repeated plotting patterns into helper functions to reduce code duplication and improve readability in the plot_CRM_with_intervals function, such as plotting trajectories with intervals and plotting true data points.

The new function introduces duplicated loops for plotting trajectories, intervals, and optional true data points. Consider extracting the repeated patterns into small helper functions. For example, create one helper to plot a series with its ribbon and another to plot true data points:

def plot_trajectory_with_interval(ax, times, data, lower, upper, label_prefix, linestyle='-', linewidth=2, color_offset=0):
    cmap = plt.cm.tab10
    for i in range(data.shape[1]):
        color = cmap(i + color_offset)
        ax.plot(times, data[:, i], label=f'{label_prefix} {i+1}', linestyle=linestyle, linewidth=linewidth, color=color)
        ax.fill_between(times, lower[:, i], upper[:, i], alpha=0.2, color=color)

def plot_true_data(ax, times, true_data, data_prefix, color_offset=0):
    cmap = plt.cm.tab10
    col_template = f'{data_prefix.lower()}_{{}}'
    for i in range(1, true_data.shape[1]+1):  # Adjust range if needed
        col_name = col_template.format(i)
        if col_name in true_data.columns:
            marker = 'o' if data_prefix.lower() == 'species' else 's'
            ax.scatter(times, true_data[col_name], marker=marker, s=30, 
                       color=cmap(i - 1 + color_offset), label=f'True {data_prefix} {i}')

# In plot_CRM_with_intervals, use:
def plot_CRM_with_intervals(observed_species, observed_resources, species_lower, species_upper,
                            resource_lower, resource_upper, times, filename=None):
    fig, ax = plt.subplots(figsize=(12, 8))
    plot_trajectory_with_interval(ax, times, observed_species, species_lower, species_upper, 'Species', linestyle='-', linewidth=2)
    plot_trajectory_with_interval(ax, times, observed_resources, resource_lower, resource_upper, 'Resource', linestyle='--', linewidth=2, color_offset=observed_species.shape[1])

    if filename:
        true_data = pd.read_csv(filename)
        true_times = true_data['time'].values
        plot_true_data(ax, true_times, true_data, 'species')
        plot_true_data(ax, true_times, true_data, 'resource', color_offset=observed_species.shape[1])

    ax.set_xlabel('Time', fontsize=14)
    ax.set_ylabel('Concentration', fontsize=14)
    ax.set_title('Consumer-Resource Model Dynamics with 95% Credible Intervals', fontsize=16)
    ax.legend(loc='best', fontsize=12)
    ax.grid(True, alpha=0.3)
    plt.tight_layout()
    if filename:
        plt.savefig(f"{filename.split('.')[0]}_with_intervals.png", dpi=300)
    plt.show()

This reduces duplication while keeping functionality intact.

@Fontanapink Fontanapink merged commit 2d86c83 into master Apr 9, 2025
@Fontanapink Fontanapink deleted the CRM branch April 9, 2025 15:02
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.

3 participants