Giter Club home page Giter Club logo

krabmaga / krabmaga Goto Github PK

View Code? Open in Web Editor NEW
155.0 10.0 13.0 65.17 MB

krABMaga: A modern developing art for reliable and efficient Agent-based Model (ABM) simulation with the Rust language

Home Page: http://krABMaga.github.io

License: MIT License

Rust 100.00%
rust rust-lang agent-based-modeling agents agent-based-simulation simulation discrete-event-simulation boids-simulation simulation-engine abm parallel-computing parallel parallel-programming multithreading multiprocessing wasm physics-simulation

krabmaga's Introduction

krabmaga animated logo

krABMaga

A modern developing art for reliable and efficient ABM simulation with the Rust language

Crates.io Crates.io docs.rs Rust CI codecov

(Notice that the parallel and visualization components are excluded from codecov as are experimental ore release candidate)

krABMaga (Previously named Rust-AB) is a discrete events simulation engine for developing ABM simulation that is written in Rust language.

krABMaga is designed to be a ready-to-use tool for the ABM community and for this reason the architectural concepts of the well-adopted MASON library were re-engineered to exploit the Rust peculiarities and programming model.

Developed by ISISLab

Examples

All the examples are hosted in a separate repository here.

Usage

Add this to your Cargo.toml:

[dependencies]
krabmaga = 0.5.*

To get started using krABMaga, see the examples. There's also a template to set up the correct project structure and the required files here.

Model Visualization with Bevy Game Engine

Based on Bevy game engine, it's possible to run simulation with visualization. It's also available a menu to start and stop simulations and a slider to set simulation speed. To run a model with visualization enabled, you have to start the simulation with the command:

cargo run --release --features  visualization

# Alternative command. Requires 'cargo make' installed
cargo make run --release 

In addition to the classical visualization, you can run your krABMaga simulation inside your browser using Web Assembly. This is possible with the command:

# Requires 'cargo make' installed
cargo make serve --release 

Visualization FAQs

In case you have troubles compiling your visualization, consult this following list of common errors first before making an issue:

cargo update -p tracing-wasm --precise 0.2.0
  • "Data remaining" issue or "len is 0 but index is 0" when running a simulation on the web: Force update your wasm-bindgen-cli local installation to version 0.2.79.
  • Out of memory error when running a simulation on the web, in chrome: run your simulation with the release profile.

Dependencies

The visualization framework requires certain dependencies to run the simulation properly.

  • 🖥️ Windows: VS2019 build tools
  • 🍎 MacOS: No dependencies needed.
  • 🐧 Linux: A few dependencies are needed. Check here for a list based on your distribution.

How to write your first model

If you don't start from our Template, add this to your Cargo.toml:

[dependencies]
krabmaga = 0.5.*

[features]
visualization = ["krabmaga/visualization"]
visualization_wasm = ["krabmaga/visualization_wasm"]

We strongly recommend to use Template or any other example as base of a new project, especially if you want to provide any visualization.

Each krABMaga model needs structs that implements our Traits, one for State and the other for Agent. In the State struct you have to put Agent field(s), because it represents the ecosystem of a simulation. More details for each krABMaga componenet are in the Architecture section.

The simplest part is main.rs, because is similar for each example. You can define two main functions using cfg directive, that can remove code based on which features are (not) enabled.
Without visualization, you have only to use simulate! to run simulation, passing a state, step number and how may time repeat your simulation. With visualization, you have to set graphical settings (like dimension or background) and call start method.

// Main used when only the simulation should run, without any visualization.
#[cfg(not(any(feature = "visualization", feature = "visualization_wasm")))]
fn main() {
  let dim = (200., 200.);
  let num_agents = 100;  
  let state = Flocker::new(dim, num_agents);
  let step = 10;
  let reps = 1;
  let _ = simulate!(state, step, reps);
}

// Main used when a visualization feature is applied.
#[cfg(any(feature = "visualization", feature = "visualization_wasm"))]
fn main() {
  let dim = (200., 200.);
  let num_agents = 100;
  let state = Flocker::new(dim, num_agents);
  Visualization::default()
      .with_window_dimensions(1000., 700.)
      .with_simulation_dimensions(dim.0 as f32, dim.1 as f32)
      .with_background_color(Color::rgb(0., 0., 0.))
      .with_name("Flockers")
      .start::<VisState, Flocker>(VisState, state);
}

Available features

Compilation Feature Description Experimental Release Candidate Stable
No Features Possibility to run model using Simulation Terminal and setup model-exploration experiments (Parameter Sweeping, Genetic and Random) in sequential/parallel mode. It's enough to create your base simulations. 🦀
visualization Based on Bevy engine, it makes possible to visualize your model elements, to understand better the behavior of your simulation. 🦀
visualization-wasm Based on Web Assembly, give you the possibility to execute your visualized simulation inside your own browser. 🦀
distributed-mpi Enable distributed model exploration using MPI. At each iteration, the amount of configurations are balanced among your nodes. 🦀
bayesian Use ML Rust libraries to use/create function to use Bayesian Optimization. 🦀
parallel Speed-up a single simulation parallelizing agent scheduling during a step. 🦀

Macros for playing with Simulation Terminal

Simulation Terminal is enabled by default using macro simulate!, so can be used passing a state, step number and how may time repeat your simulation.. That macro has a fourth optional parameter, a boolean. When false is passed, Simulation Terminal is disabled.

($s:expr, $step:expr, $reps:expr $(, $flag:expr)?) => {{
      // Macro code 
}}

You can create tabs and plot your data using two macro:

  • addplot! let you create a new plot that will be displayed in its own tab.
addplot!(String::from("Chart Name"), String::from("xxxx"), String::from("yyyyy"));
  • plot! to add a point to a plot. Points can be added during simulation execution, for example inside after_step method. You have to pass plot name, series name, x value and y value. Coordinate values need to be f64.
plot!(String::from("Chart name"), String::from("s1"), x, y);

On Terminal home page there is also a log section, you can plot log messages when some event needs to be noticed. You can navigate among all logs using ↑↓ arrows. To add a log use the macro log!, passing a LogType (an enum) and the log message.

 log!(LogType::Info, String::from("Log Message"));

Are available four type of Logs:

pub enum LogType {
    Info,
    Warning,
    Error,
    Critical,
}

Support conference paper

If you find this code useful in your research, please consider citing:

@ARTICLE{AntelmiASIASIM2019,
  author={Antelmi, A. and Cordasco, G. and D’Auria, M. and De Vinco, D. and Negro, A. and Spagnuolo, C.},
  title={On Evaluating Rust as a Programming Language for the Future of Massive Agent-Based Simulations},
  journal={Communications in Computer and Information Science},
  note={Conference of 19th Asia Simulation Conference, AsiaSim 2019 ; Conference Date: 30 October 2019 Through 1 November 2019;  Conference Code:233729},
  year={2019},
  volume={1094},
  pages={15-28},
  doi={10.1007/978-981-15-1078-6_2},
  issn={18650929},
  isbn={9789811510779},
}

🏆 Best Paper Nominee

License

The MIT License

Copyright (c) ISISLab, Università degli Studi di Salerno 2019.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

krabmaga's People

Contributors

andreat98 avatar caramao avatar carbonhell avatar ddevin96 avatar ewouth avatar giusdam avatar litschiw avatar matdau avatar spagnuolocarmine avatar zioposty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

krabmaga's Issues

Build error while running the examples

While trying to run the examples without visualization with cargo run --release command, I am getting following error:

Screenshot from 2022-05-11 01-04-49

As it states, the problem seems to be in log! macro.

When I try to run it with visualization with cargo run --release --features visualization command, it works perfectly fine.

Version: 0.1.4
Platform: x86_64, Ubuntu 22.04

DenseGrid2D visualization apply_to_all_values

Hi I saw this implementation while using apply_to_all_values and I was wondering if that was meant to be:

pub fn apply_to_all_values<F>(&self, closure: F, option: GridOption)
            where
                F: Fn(&Int2D, &O) -> Option<O>,
            {
                match option {
                    GridOption::READ => {
                        self.obj2loc.apply_to_all_keys(closure);
                    },
                    GridOption::WRITE => {
                        self.obj2loc.apply_to_all_keys(closure);
                    },
                    GridOption::READWRITE =>{
                        self.obj2loc.apply_to_all_keys(closure);

                    }
                }
            }

Essentially, I am trying to update all values of a dense grid and then use lazy_update to update the buffers, but I noticed that all of my data kept disappearing.

Is this what the code was meant to be?

pub fn apply_to_all_values<F>(&self, closure: F, option: GridOption)
            where
                F: Fn(&Int2D, &O) -> Option<O>,
            {
                match option {
                    GridOption::READ => {
                        self.obj2loc.apply_to_all_keys(closure);
                    },
                    GridOption::WRITE => {
                        self.loc2objs.apply_to_all_keys(closure);
                    },
                    GridOption::READWRITE =>{
                        self.obj2loc.apply_to_all_keys(closure);
                        self.loc2objs.apply_to_all_keys(closure);
                    }
                }
            }

Open access publication

Hi! I'm one of Bevy's core developers, but I have an academic background in complex systems ecology. It's really cool to see this project!

The conference paper looks interesting, and I'd love to read it, but I'm no longer affiliated with an institution.

If you're able to, could you post a PDF or preprint?

LogTracer error during init()

I'm trying to use latest git version of krabmaga and I'm running into an issue with bevy it looks like:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SetLoggerError(())', /Users/chholcombe/.cargo/registry/src/github.com-1ecc6299db9ec823/bevy_log-0.6.0/src/lib.rs:92:27
stack backtrace:
   0: rust_begin_unwind
             at /rustc/bd39bbb4bb92df439bf6d85470e296cc6a47ffbd/library/std/src/panicking.rs:575:5
   1: core::panicking::panic_fmt
             at /rustc/bd39bbb4bb92df439bf6d85470e296cc6a47ffbd/library/core/src/panicking.rs:64:14
   2: core::result::unwrap_failed
             at /rustc/bd39bbb4bb92df439bf6d85470e296cc6a47ffbd/library/core/src/result.rs:1790:5
   3: core::result::Result<T,E>::unwrap
             at /rustc/bd39bbb4bb92df439bf6d85470e296cc6a47ffbd/library/core/src/result.rs:1112:23
   4: <bevy_log::LogPlugin as bevy_app::plugin::Plugin>::build
             at /Users/chholcombe/.cargo/registry/src/github.com-1ecc6299db9ec823/bevy_log-0.6.0/src/lib.rs:92:9
   5: bevy_app::plugin_group::PluginGroupBuilder::finish
             at /Users/chholcombe/.cargo/registry/src/github.com-1ecc6299db9ec823/bevy_app-0.6.0/src/plugin_group.rs:118:21
   6: bevy_app::app::App::add_plugins
             at /Users/chholcombe/.cargo/registry/src/github.com-1ecc6299db9ec823/bevy_app-0.6.0/src/app.rs:797:9
   7: krabmaga::visualization::visualization::Visualization::setup
             at /Users/chholcombe/.cargo/git/checkouts/krabmaga-cbc93ab53f330fa1/19ebdb1/src/visualization/visualization.rs:111:17
   8: krabmaga::visualization::visualization::Visualization::start
             at /Users/chholcombe/.cargo/git/checkouts/krabmaga-cbc93ab53f330fa1/19ebdb1/src/visualization/visualization.rs:78:39
   9: craq_sim::main
             at ./src/main.rs:113:5
  10: core::ops::function::FnOnce::call_once
             at /rustc/bd39bbb4bb92df439bf6d85470e296cc6a47ffbd/library/core/src/ops/function.rs:250:5

The krabmaga version I'm using is:

[[package]]
name = "krabmaga"
version = "0.2.0"
source = "git+https://github.com/krABMaga/krABMaga#19ebdb1b727a5f51d5d4a0e21333ba26c5038711"

I did some lldb debugging and traced this down to the LogPlugin in bevy crashing with an unwrap() during init. It says that the log was already initialized and can't be done again. I'm not using tracing anywhere else. Just simple_logger.

I made a small patch to the krabmaga source where I just disable the logging plugin and that seems to fix the issue:

                app.insert_resource(window_descriptor)
                    .add_plugins_with(DefaultPlugins, |group| group.disable::<LogPlugin>())
                    .add_plugin(EguiPlugin);

inside visualization.rs line 114.
I looked into bevy and it looks like there is 4 newer versions that have been released and one of them fixed this issue with the unwrap. I tried updating the dependency myself in a fork of the krabmaga repo but I'm running into issues with the conditional compilation flags. Would anyone be interested in updating bevy to the latest version on this crate? I think it's pretty far out of sync at this point.

GIS integration

Dear authors,
thanks for sharing this great toolkit! I'm very interested in using it for city simulations, and for that I would need a sort of GIS integration like loading (and visualizing) shapefiles and fast spatial index (for collisions).

In my past experience with mesa and mesa-gis this would not scale well.

I was wondering if you could advice on that

Thanks and regards

Copy trait limitations for the agent

Hi team, good work with the simulator and thanks for sharing it with the community. I am developing a simulation using the tool and I have a question regarding the agent's implementation.

All the agents are required to implement Copy trait. This prevents me from assigning dynamic properties to an agent.

For example, I have a time series data of varying lengths and each agent will be randomly assigned a series. Since the length of the time series can vary, I tried defining it as a vector. However, vector has no copy trait.

The only way I could think of is the simulation state holding this data and assigning each agent with a piece of data based on the current time step. That feels hacky. Since I am new to the tool, I wanted to check with you if there is a better way of providing Agent with dynamic sized information.

Travis build failing due to missing Amethyst dependencies

There are two issues right now:

  • The mac build is failing to compile gfx_backend_vulkan. The easiest approach would be to make it use metal as a graphics platform instead;

  • The linux build is failing to compile the custom build command for alsa-sys, due to missing dependencies (in particular, libasound2-dev libudev-dev pkg-config)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.