Skip to content

Conversation

@adamamer20
Copy link
Member

@adamamer20 adamamer20 commented Dec 8, 2025

Introduce an advanced tutorial notebook script to rebuild the Sugarscape Instant-growback model using mesa-frames

Summary by CodeRabbit

  • Documentation
    • Added a comprehensive advanced tutorial with a complete, production-ready agent-based model example.
    • Included multiple implementation strategies demonstrating different performance and design approaches.
    • Provided detailed guidance on model reporters, data collection, and performance comparison techniques.

✏️ Tip: You can customize this high-level summary in your review settings.

@adamamer20 adamamer20 changed the title Add advanced tutorial notebook script Add advanced tutorial (Sugarscape IG) notebook script Dec 8, 2025
@codecov
Copy link

codecov bot commented Dec 8, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.23%. Comparing base (3037456) to head (0b9465e).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #189   +/-   ##
=======================================
  Coverage   89.23%   89.23%           
=======================================
  Files          14       14           
  Lines        2007     2007           
=======================================
  Hits         1791     1791           
  Misses        216      216           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@adamamer20
Copy link
Member Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 8, 2025

Walkthrough

Introduces a comprehensive Sugarscape advanced tutorial demonstrating a mesa-frames model with sugar landscape dynamics, multiple agent movement strategies (sequential, Numba-compiled, and Polars-parallel), data collection, and comparative analysis harness across implementations.

Changes

Cohort / File(s) Change Summary
Sugarscape Advanced Tutorial
docs/general/tutorials/3_advanced_tutorial.py
New file implementing a full Sugarscape model tutorial with Model and AgentSet classes, three movement policy variants (Sequential, Numba, Parallel), reporter functions (Gini, correlations), initialization logic, and a run-and-compare harness for benchmarking and validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Harness as Run Harness
    participant S as Sugarscape<br/>(init)
    participant AB as AntsBase<br/>(variant)
    participant SM as Sugar Map
    participant DC as DataCollector

    User->>Harness: run_and_compare(steps)
    
    loop For each variant (Sequential, Numba, Parallel)
        Harness->>S: __init__(agent_type, seed)
        S->>S: _generate_sugar_grid()
        S->>S: _generate_agent_frame()
        S->>DC: register reporters
        
        loop for step in range(steps)
            Harness->>S: step()
            S->>AB: move()
            alt Sequential/Numba/Parallel
                AB->>SM: query sugar positions
                AB->>AB: resolve movement & conflicts
            end
            AB->>AB: eat()
            AB->>AB: _remove_starved()
            S->>SM: _advance_sugar_field()
            S->>DC: collect()
        end
        
        Harness->>Harness: aggregate trajectory & runtime
    end
    
    Harness->>Harness: generate comparison table<br/>(gini, correlations, agents)
    Harness->>User: output results
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Multiple movement strategy implementations: Sequential, Numba-compiled, and Polars-parallel variants require separate logic review and validation of correctness across different paradigms.
  • Grid-based agent dynamics: Sugar regrowth, starvation logic, and conflict resolution in the parallel variant involve non-trivial state management.
  • Reporter functions: Gini coefficient and correlation calculations need verification for correctness against model state.
  • Type annotations and Polars/Numba usage: Complex generic types, DataFrame operations, and Numba jit decorators require careful inspection for performance and correctness.
  • Comparative analysis harness: Run loop, seeding, and metrics aggregation logic should be validated for fair comparison across implementations.

Poem

🐰 A Sugarscape dreams in three sweet ways,
Sequential hops through agent days,
Numba sprints with compiled grace,
Polars dances, parallel race!
Compare, collect, and let them play—
Mesa-frames shine bright today! 🍬✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 79.31% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding an advanced tutorial notebook script implementing the Sugarscape model with instant growback.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch split/advanced-tutorial-script

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 1

🧹 Nitpick comments (2)
docs/general/tutorials/3_advanced_tutorial.py (2)

129-143: Redundant size check in gini computation.

Lines 131-132 check if sugar.size == 0 and return nan, then line 133 sorts the array into sorted_vals, and lines 135-136 check if n == 0 again. Since sorted_vals = np.sort(sugar) preserves the size, the second check is redundant.

Apply this diff to streamline the check:

     sugar = primary_set.df["sugar"].to_numpy().astype(np.float64)
 
     if sugar.size == 0:
         return float("nan")
     sorted_vals = np.sort(sugar.astype(np.float64))
     n = sorted_vals.size
-    if n == 0:
-        return float("nan")
     cumulative = np.cumsum(sorted_vals)

390-407: Duplicate extinction check in step method.

The method checks if self.sets[0] is empty on lines 400-401 and sets self.running = False, then performs the same check again on lines 406-407 after data collection. The second check is defensive but redundant since the agent count cannot increase during data collection.

If you prefer to keep the defensive check for clarity, consider adding a comment. Otherwise, consolidate to a single check:

     def step(self) -> None:
         """Advance the model by one step.
 
         Notes
         -----
         The per-step ordering is important and this tutorial implements the
         classic Sugarscape "instant growback": agents move and eat first,
         and then empty cells are refilled immediately (move -> eat -> regrow
         -> collect).
         """
         if len(self.sets[0]) == 0:
             self.running = False
             return
         self.sets[0].step()
         self._advance_sugar_field()
         self.datacollector.collect()
-        if len(self.sets[0]) == 0:
-            self.running = False
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3037456 and 0b9465e.

📒 Files selected for processing (1)
  • docs/general/tutorials/3_advanced_tutorial.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Use Python 3.11 or later with 4-space indentation
Include type hints for all public APIs
Use NumPy-style docstrings (validated by Ruff/pydoclint)
Use CamelCase for class names
Use snake_case for function and attribute names
Avoid using TYPE_CHECKING guards for type annotations because the project uses beartype for runtime type checking, which requires the actual type objects to be available at runtime
Treat underscored attributes as internal/private and not part of the public API

Files:

  • docs/general/tutorials/3_advanced_tutorial.py
🪛 Ruff (0.14.7)
docs/general/tutorials/3_advanced_tutorial.py

47-47: String contains ambiguous (EN DASH). Did you mean - (HYPHEN-MINUS)?

(RUF001)


294-296: Avoid specifying long messages outside the exception class

(TRY003)


495-497: Avoid specifying long messages outside the exception class

(TRY003)


1145-1145: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


1546-1546: String contains ambiguous (EN DASH). Did you mean - (HYPHEN-MINUS)?

(RUF001)


1569-1569: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


1571-1571: Comment contains ambiguous (NON-BREAKING HYPHEN). Did you mean - (HYPHEN-MINUS)?

(RUF003)


1645-1645: String contains ambiguous (EN DASH). Did you mean - (HYPHEN-MINUS)?

(RUF001)

🔇 Additional comments (1)
docs/general/tutorials/3_advanced_tutorial.py (1)

1-1648: Excellent tutorial implementation demonstrating mesa-frames advanced features.

This comprehensive tutorial successfully demonstrates:

  • Three distinct movement strategies (sequential Python, Numba-compiled, and Polars-parallel)
  • Proper separation of concerns between model orchestration and agent behavior
  • Extensive documentation with NumPy-style docstrings
  • Edge case handling (empty sets, extinction, conflict resolution)
  • Comparative analysis framework showing macro-level equivalence across implementations

The code is well-structured, follows project conventions, and provides a strong pedagogical example of mesa-frames capabilities. The minor issues flagged above are optional improvements that don't affect correctness or tutorial value.

the model converges to the *same* macroscopic inequality pattern regardless of
whether agents act sequentially or in parallel and that As long as the random draws do
not push the system into extinction, the long-run Gini coefficient of wealth and
the wealth–trait correlations line up within sampling error — a classic example
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Ambiguous Unicode characters in strings and comments.

Static analysis detected non-ASCII dash characters that may cause issues with text editors or search:

  • Lines 47, 1546, 1645: EN DASH (–) in strings
  • Lines 1145, 1569, 1571: NON-BREAKING HYPHEN (‑) in comments

Consider replacing with standard ASCII HYPHEN-MINUS (-) for consistency.

You can identify and replace these using:

#!/bin/bash
# Find lines with ambiguous Unicode dash characters
rg --line-number '[\u2013\u2011]' docs/general/tutorials/3_advanced_tutorial.py

Also applies to: 1145-1145, 1546-1546, 1569-1569, 1571-1571, 1645-1645

🧰 Tools
🪛 Ruff (0.14.7)

47-47: String contains ambiguous (EN DASH). Did you mean - (HYPHEN-MINUS)?

(RUF001)

🤖 Prompt for AI Agents
In docs/general/tutorials/3_advanced_tutorial.py around lines 47, 1145, 1546,
1569, 1571, and 1645, there are ambiguous Unicode dash characters (EN DASH
U+2013 and NON‑BREAKING HYPHEN U+2011) in strings/comments; replace each with
the ASCII hyphen-minus (-) to avoid editor/search issues and ensure consistency;
perform a targeted search for U+2013 and U+2011 in those lines and apply a
simple replace, then run tests or a quick grep to confirm all occurrences were
converted.

@adamamer20 adamamer20 added the docs Improvements or additions to documentation label Dec 8, 2025
@adamamer20 adamamer20 added this to the 0.2.0 milestone Dec 8, 2025
@adamamer20 adamamer20 requested review from Ben-geo and EwoutH December 8, 2025 23:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants