├── img └── .gitignore ├── img_dark └── .gitignore ├── .vscode ├── settings.json └── launch.json ├── .gitignore ├── .travis.yml ├── .github └── workflows │ └── rust.yml ├── .gitlab-ci.yml ├── Cargo.toml ├── LICENSE ├── README.md └── src └── main.rs /img/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img_dark/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "dataset", 4 | "ffreport", 5 | "loglevel" 6 | ] 7 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ~$* 2 | *~ 3 | /target 4 | **/*.rs.bk 5 | Cargo.lock 6 | *.csv 7 | *.diff 8 | *.log 9 | *.mkv 10 | *.patch 11 | *.png 12 | *.tmp 13 | *.tmp.rs 14 | *.wbk 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | jobs: 7 | allow_failures: 8 | - rust: nightly 9 | fast_finish: true 10 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Build 13 | run: cargo build --verbose 14 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: 'rust:latest' 2 | 3 | stages: 4 | - test 5 | 6 | variables: 7 | CARGO_HOME: $CI_PROJECT_DIR/cargo 8 | APT_CACHE_DIR: $CI_PROJECT_DIR/apt 9 | 10 | test: 11 | stage: test 12 | script: 13 | - rustc --version 14 | - cargo --version 15 | - cargo build --verbose 16 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "(Windows) Launch", 9 | "type": "cppvsdbg", 10 | "request": "launch", 11 | "program": "${workspaceRoot}/target/debug/rust-agent-based-models.exe", 12 | "args": [], 13 | "stopAtEntry": false, 14 | "cwd": "${workspaceFolder}", 15 | "environment": [], 16 | "externalConsole": false 17 | } 18 | ] 19 | } -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # This file is part of rust-agent-based-models: 2 | # Reliable and efficient agent-based models in Rust 3 | # 4 | # Copyright 2020 Fabio A. Correa Duran facorread@gmail.com 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | [package] 19 | name = "rust-agent-based-models" 20 | version = "0.1.0" 21 | authors = ["Fabio A. Correa Duran "] 22 | description = "Reliable and efficient agent-based models in Rust" 23 | edition = "2018" 24 | license = "Apache-2.0" 25 | repository = "https://github.com/facorread/rust-agent-based-models" 26 | 27 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 28 | 29 | [features] 30 | default = ["all-graphics", "csv-output"] # This sofware comes with all features activated: landscape and networks with figures and csv output 31 | example = ["landscape-graphics", "net"] # This example differs in that there are no figures or csv output for networks; the model has networks, tough 32 | all-graphics = ["landscape-graphics", "net-graphics"] 33 | csv-output = ["agent-metrics", "landscape-csv", "net-csv"] # csv outputs describe agents by default. List additional outputs here. 34 | 35 | landscape-graphics = ["landscape-metrics", "graphics"] 36 | net-graphics = ["net-metrics", "graphics"] 37 | 38 | landscape-csv = ["landscape-metrics"] 39 | net-csv = ["net-metrics"] 40 | 41 | # The following features use memory; enable those that are strictly necessary. 42 | graphics = ["agent-metrics"] # Enable figures; by default, figures describe agents only. 43 | agent-metrics = [] # Accumulate metrics from agents 44 | landscape-metrics = ["landscape"] # Accumulate metrics from the landscape 45 | net-metrics = ["net"] # Accumulate metrics from the social network 46 | 47 | # The following features consume CPU time; enable those that are strictly necessary. 48 | landscape = [] # Enable the landscape 49 | net = [] # Enable social networks 50 | 51 | #[cfg(any(feature = "landscape-graphics", all(feature = "csv-output", feature = "landscape")))] 52 | # Consider this use case: Duplicate the above line to apply it to a new member of struct TimeStepResults; this new member is an outcome 53 | # of the net feature, so you change "landscape" to "net" by hand. You thought that the word "landscape" occurs only once in the line, 54 | # so you have inadvertedly caused an error. The landscape-csv feature exists to prevent this error. 55 | 56 | [dependencies] 57 | plotters = "0.3.0" 58 | rand = "0.8.1" 59 | rand_distr = "0.4.0" 60 | rand_pcg = "0.3.0" 61 | rayon = "1.5.0" 62 | slotmap = "1.0.2" 63 | wrapping_coords2d = "0.1.9" 64 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rust-agent-based-models 2 | 3 | Reliable and efficient agent-based models in Rust 4 | 5 | Copyright (C) 2020 Fabio Correa facorread@gmail.com 6 | 7 | https://github.com/facorread/rust-agent-based-models 8 | 9 | https://gitlab.com/facorread/rust-agent-based-models 10 | 11 | ## What is an agent-based model? 12 | 13 | Agent-based models (ABM) are computer programs that define agents, virtual entities that imitate the decision-making processes and interactions of real people, animals, neurons, computers, or other individuals. ABMs have a wide range of applications. For example, an ABM can study a flock of birds. The behavior of each virtual bird can be as simple as just trying to fly in close proximity to the nearest neighbor; the software can show that this birds combine their behavior to generate the complex, adaptive patterns of flight of real flocks. An ABM can also study economic behavior: in a virtual society, sellers of goods set a price based on limited information they have about the market, and buyers may bargain based on their own limited information about the market. Even with simple rules, an economic ABM can generate complex patterns that can be useful to understand real macroeconomic trends. 14 | 15 | ABMs are computational tools of complexity science. There is a wide range of scholarly literature using ABMs to explore collective behavior of humans, animals, companies, and other complex systems on many scales, from individual to global. ABMs are particularly useful to understand complex adaptive systems; they help social and ecological scientists test hypotheses about human behavior by building artificial societies and virtual human-natural systems. Numerous software suites exist to develop ABMs, such as [NetLogo] and [Repast]. There is also a wide range of video games and board games that are agent-based models. 16 | 17 | ## Why rust-agent-based-models? 18 | 19 | [Rust] is useful to write reliable and efficient software for a wide range of applications such as operating systems, high-performance computing, embedded systems, and the Web. Rust does not rely on complicated tools like interpreters or garbage collectors. Rust encourages a data-driven coding discipline informed by the borrow checker, a compile-time tool to maintain memory integrity. Fighting with the borrow checker for a little while is a good strategy to learn good coding practices. 20 | 21 | [Entity-Component-System (ECS)](https://en.wikipedia.org/wiki/Entity_component_system) is a software architecture to define agents in computer memory. Here is a quick example: a vector of `n` health state variables, a vector of `n` energy levels, a vector of `n` body sizes, and a vector of `n` geographic coordinates exist as four independent data structures implementing `n` entities or agents. The first agent in the system has an index 0, and its four components are `health[0]`, `energy[0]`, `volume[0]`, `coord[0]`. Each agent consists of four components maintained in separate memory regions. The program performs better by processing agent decisions and interactions independently, focusing on just one or two of the four vectors at a time; this is a significant memory speedup. The ECS architecture stands in contrast to the more popular [Object-Oriented Programming (OOP)](https://en.wikipedia.org/wiki/Object-oriented_programming) paradigm, which defines only one vector of `n` agents, where each agent has its four components in the same region of memory. 22 | 23 | ECS is a popular design in video games, based on its superior performance and its capacity to adapt to the dynamics of engineering such complicated pieces of software. Catherine West's presentation, ["Using Rust for Game Development,"](https://kyren.github.io/2018/09/14/rustconf-talk.html) provides the rationale and the broad strokes of an ECS architecture in Rust. 24 | 25 | The ECS architecture can give your ABM the flexibility to help you focus on discovery and innovation. This repository implements an agent-based model as an entity-component system that defines a group of agents, a landscape, and an infectious disease. This ABM makes the most of the borrow checker and keeps complications to a minimum. The ABM does not encapsulate or hide model components; instead, all model code resides at ```main()```. As the model grows and evolves, you want to focus on complexity science as opposed to writing and deleting modules, interfaces, or traits to neatly "organize" the model. I have years of experience with the OOP paradigm on C++ and I never managed to get it right. Take a look at ```main.rs``` and ask the question, what proportion of this software is about the science, and what proportion is about managing memory and other housekeeping? 26 | 27 | After you have prototyped your ABM on [NetLogo], [Repast], or other popular framework, consider using an ECS design for your high-performance ABM on Rust. Why not use Rust for your whole workflow? 28 | 29 | ## Getting started 30 | 31 | Consider installing the [Chocolatey] package manager to set up a streamlined upgrade experience. After installing Chocolatey, use the following command: 32 | 33 | ```powershell 34 | choco install git jpegview visualstudio-installer visualstudio2019buildtools vscode 35 | ``` 36 | 37 | This should set you up with [Visual Studio Code], the [FFmpeg] binaries, [git], and [jpegview]. Follow the [Rust] standard installation procedure and then use `rustup` to install the [Rust Clippy tool]. Use Visual Studio Code to install the [Better TOML extension] and the [Rust (rls) extension]. 38 | 39 | [Clone this repository] (`https://github.com/facorread/rust-agent-based-models.git`) and use your favorite terminal to run `cargo run --release`. Follow the instructions on screen. 40 | 41 | The code is an exaggerated example of an infectious model; it implements an infectious disease transmitting between agents, between agents and cells, and across cells. 42 | 43 | See an [example video here](https://youtu.be/oYeHyFl1-HY) 44 | 45 | Consider using the [wasm-agent-based-models] repository to create interactive versions of your model. 46 | 47 | ## What can I do with this software? 48 | 49 | Ideally you would fork this repository to build your own model; this would give you easy access to bug fixes and enhancements via `git pull` and `git merge`. As an alternative, you can just copy this code and start an ABM in your own repository. Finally, you can implement the ideas in this repository as part of your own design. 50 | 51 | If you want to reuse code, for example, to generate links at several stages within a time step, you will need to store the state variables in a `world` struct; see Catherine's presentation. 52 | 53 | Use statistical software such as R, Julia, or SPSS to analyze and visualize the output files. 54 | 55 | Please send me a short email to let me know if you find any of these ideas useful for your own research or if you believe a different approach or software architecture is necessary. 56 | 57 | ## Advanced usage 58 | 59 | This software uses [Cargo's features] and [Rust's conditional compilation] to enable and disable graphics, the social network, and the landscape. By default, `cargo.toml` activates the `all-graphics` feature. This default is the best option for most cases. This is also the only configuration that undergoes automated testing at GitHub and GitLab. 60 | 61 | The selections made at `cargo.toml` enable or disable code at `main.rs` through the `#[cfg(feature = )]` attributes. For example, `#[cfg(feature = "net")]` in `main.rs` enables the social network, including the `links` container and the network dynamics. It is useful to be able to turn the network off when development focuses on the landscape or other aspect of the model. By turning the network on or off, and re-running the program, it is possible to catch errors, compare component dynamics, and visualize different component outcomes. Turning off unnecessary components can also speed up the model. For example, activating `default = ["no-graphics"]` in `Cargo.toml` is useful to perform a parameter sweep on thousands of scenarios and save simulated data in `csv` format without producing numerous `png` images. 62 | 63 | The features at Cargo.toml, namely landscape and net, are arbitrary examples based on the structure of the model. Take finer control of development, memory, and performance of your model by introducing features you can disable or enable with just a line of code. 64 | 65 | ## Why not make a crate? 66 | 67 | Generally speaking, the code for an ABM is tightly integrated; take a NetLogo model for example: turtles, patches, and links have no privacy or encapsulation. In this repository, model variables such as ```health```, ```next_health```, ```cell_health```, and ```links``` are integrated as well; it is not worth it to try encapsulate them or restrict access. But this also means that separating the code into library and client is not very practical. 68 | 69 | Some individual components of an ABM can exist in independent crates. One of them is Orson Peters' [`slotmap`](https://github.com/orlp/slotmap), an efficient memory manager that reuses space left behind by dying agents. The other is my [`wrapping_coords2d`](https://crates.io/crates/wrapping_coords2d) crate, a utility to manage the landscape by mapping a 2D grid of cells into a vector. Both x and y coordinates wrap around the limits of the grid. As an alternative, you can use [`ameda`](https://docs.rs/ameda/latest/ameda) to manage the landscape without wrapping. 70 | 71 | ## Why is this software so slow? 72 | 73 | By default, [Visual Studio Code] runs the program using the `debug` profile. The profile provides vscode with the essential information to examine and step into model code and memory; in this profile, the [`plotters`] crate conducts a multitude of checks for memory and data safety to carefully produce the model figures; this takes significant time and makes the software slow. To improve development time, model protoypes should use very few scenarios and a short time span. Alternatively, a `return()` instruction can exit the program before producing any figures. Finally, the `no-graphics` feature can be activated in `cargo.toml`. See the *Advanced usage* section above for more details. 74 | 75 | When the model is ready to work with more scenarios and long time spans, the best option is to use the `release` profile. For this, the command `cargo run --release` can run on the Command Prompt, PowerShell, or the [Visual Studio Code] console. This profile produces figures and output data significantly faster than the `debug` profile. 76 | 77 | ## Does this software use `unsafe` code? 78 | 79 | Not explicitly. 80 | 81 | ## The scenarios and time_series data structure does not seem to conform to the ECS design. 82 | 83 | That is okay. These object-oriented structures are useful for parallel computation using the [`rayon`] crate. These structures represent just a small portion of execution time. 84 | 85 | ## Other ABM designs and links 86 | 87 | AJ (Jay, Zencodes, ajjaic), [`ameda` - Manipulate 2D grid indices](https://docs.rs/ameda/latest/ameda) 88 | 89 | Carmine Spanguolo, [Rust-AB -- An Agent Based Simulation engine in Rust](https://github.com/spagnuolocarmine/abm) 90 | 91 | Diggory Hardy, [`rand` - A Rust library for random number generation](https://github.com/rust-random/rand) 92 | 93 | Francis Tseng, [`rust-sim`- Sketches for rust agent-based modeling framework](https://github.com/frnsys/rust-sim) 94 | 95 | Hao Hou, [`plotters`] - A Rust drawing library 96 | 97 | Josh Stone, Niko Matsakis, [`Rayon`] - A data parallelism library for Rust 98 | 99 | Nikolay Kim, [`actix` - Actor framework for Rust](https://github.com/actix/actix) 100 | 101 | Orson Peters, [`slotmap` - Data structure for Rust](https://github.com/orlp/slotmap) 102 | 103 | Wilensky, U. 1999. [NetLogo]. Center for Connected Learning and Computer-Based Modeling, Northwestern University. Evanston, IL. 104 | 105 | ## References 106 | 107 | North, MJ, NT Collier, J Ozik, E Tatara, M Altaweel, CM Macal, M Bragen, and P Sydelko, "Complex Adaptive Systems Modeling with [Repast] Simphony", Complex Adaptive Systems Modeling, Springer, Heidelberg, FRG (2013). https://doi.org/10.1186/2194-3206-1-3 108 | 109 | West, Catherine (2018), ["Using Rust for Game Development,"](https://kyren.github.io/2018/09/14/rustconf-talk.html), RustConf 2018 closing keynote. 110 | 111 | Antelmi A., Cordasco G., D’Auria M., De Vinco D., Negro A., Spagnuolo C. (2019, October) On Evaluating Rust as a Programming Language for the Future of Massive Agent-Based Simulations. In: Tan G., Lehmann A., Teo Y., Cai W. (eds) Methods and Applications for Modeling and Simulation of Complex Systems. In Asian Simulation Conference AsiaSim 2019 (pp. 15-28). Communications in Computer and Information Science, vol 1094. Springer, Singapore. https://doi.org/10.1007/978-981-15-1078-6_2 112 | 113 | [Better TOML extension]:https://marketplace.visualstudio.com/items?itemName=bungcip.better-toml 114 | [Cargo's features]:https://doc.rust-lang.org/cargo/reference/features.html 115 | [Chocolatey]:https://chocolatey.org/ 116 | [Clone this repository]:https://code.visualstudio.com/docs/editor/versioncontrol#_cloning-a-repository 117 | [FFmpeg]:https://www.ffmpeg.org/download.html 118 | [git]:http://git-scm.com 119 | [jpegview]:https://sourceforge.net/projects/jpegview 120 | [NetLogo]:http://ccl.northwestern.edu/netlogo 121 | [`plotters`]:https://crates.io/crates/plotters 122 | [`rayon`]:https://github.com/rayon-rs/rayon 123 | [Repast]:https://repast.github.io/ 124 | [Rust]:https://www.rust-lang.org 125 | [Rust (rls) extension]:https://marketplace.visualstudio.com/items?itemName=rust-lang.rust 126 | [Rust Clippy tool]:https://github.com/rust-lang/rust-clippy 127 | [Rust's conditional compilation]:https://doc.rust-lang.org/reference/conditional-compilation.html 128 | [Visual Studio Code]:https://code.visualstudio.com/ 129 | [wasm-agent-based-models]:https://github.com/facorread/wasm-agent-based-models 130 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | /* This file is part of rust-agent-based-models: 2 | Reliable and efficient agent-based models in Rust 3 | 4 | Copyright 2020 Fabio A. Correa Duran facorread@gmail.com 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | */ 18 | 19 | // Use the tags begin-similar-code and end-similar-code to mark a block of code that is similar between rust-agent-based-models and wasm-agent-based-models. 20 | // begin-similar-code 0 21 | 22 | ///! This software uses the Entity-Component-System (ECS) architecture and other principles discussed at https://kyren.github.io/2018/09/14/rustconf-talk.html 23 | #[cfg(feature = "graphics")] 24 | use plotters::prelude::*; 25 | #[cfg(feature = "net")] 26 | use rand::distributions::weighted::{WeightedError, WeightedIndex}; 27 | use rand::distributions::{Bernoulli, Distribution}; 28 | #[cfg(feature = "landscape")] 29 | use rand_distr::Normal; 30 | use rayon::prelude::*; 31 | use slotmap::{SecondaryMap, SlotMap}; 32 | #[cfg(feature = "net-graphics")] 33 | use std::collections::{BTreeMap, BTreeSet}; 34 | use std::fs; 35 | // use std::fmt::Write as FmtWrite; // See https://doc.rust-lang.org/std/macro.writeln.html 36 | #[cfg(feature = "csv-output")] 37 | use std::io::Write as IoWrite; // See https://doc.rust-lang.org/std/macro.writeln.html 38 | #[cfg(feature = "landscape")] 39 | use wrapping_coords2d::WrappingCoords2d; 40 | 41 | // Model properties 42 | #[derive(Clone, Copy, PartialEq)] 43 | enum Health { 44 | S, 45 | I, 46 | } 47 | 48 | // Housekeeping 49 | slotmap::new_key_type! { 50 | struct AgentKey; 51 | struct LinkKey; 52 | } 53 | 54 | /// Simulation results for a time step 55 | #[derive(Clone, Default)] 56 | struct TimeStepResults { 57 | /// Time step 58 | time_step: u32, 59 | /// Number of agents 60 | #[cfg(feature = "agent-metrics")] 61 | n: u32, 62 | /// Susceptibles 63 | #[cfg(feature = "agent-metrics")] 64 | s: u32, 65 | /// Infected 66 | #[cfg(feature = "agent-metrics")] 67 | i: u32, 68 | /// Maximum network degree of susceptibles 69 | #[cfg(feature = "net-metrics")] 70 | d_s: i32, 71 | /// Maximum network degree of infectious 72 | #[cfg(feature = "net-metrics")] 73 | d_i: i32, 74 | /// Infected cells 75 | #[cfg(feature = "landscape-metrics")] 76 | c_i: u32, 77 | /// Histogram of network degrees 78 | #[cfg(feature = "net-graphics")] 79 | degree_histogram: BTreeMap, 80 | /// Health status 81 | #[cfg(feature = "landscape-graphics")] 82 | cell_health: Vec, 83 | } 84 | 85 | /// Simulation scenario, including parameters and results 86 | #[derive(Clone, Default)] 87 | struct Scenario { 88 | /// Sequential scenario number 89 | id: u32, 90 | /// Model parameter: Infection probability 91 | infection_probability: f64, 92 | /// Simulation results: Set of network degrees that ever ocurred in this scenario 93 | #[cfg(feature = "net-graphics")] 94 | histogram_degrees_set: BTreeSet, 95 | /// Simulation results: Maximum network degree that ever ocurred in this scenario 96 | #[cfg(feature = "net-graphics")] 97 | histogram_max_degree: i32, 98 | /// Simulation results: Height of the network degree histogram for this scenario 99 | #[cfg(feature = "net-graphics")] 100 | histogram_height: u32, 101 | /// Simulation results: Height of the time series figure for agents for this scenario 102 | #[cfg(feature = "graphics")] 103 | agent_time_series_height: u32, 104 | /// Simulation results: Height of the time series figure for agents for this scenario 105 | #[cfg(feature = "landscape-graphics")] 106 | cell_time_series_height: u32, 107 | /// Simulation results for all time steps 108 | time_series: std::vec::Vec, 109 | } 110 | 111 | // end-similar-code 0 112 | 113 | fn main() { 114 | // Only use one thread to facilitate debugging. One thread makes the program sequential. 115 | #[cfg(debug_assertions)] // Only when debugging should this instruction happen. 116 | #[rustfmt::skip] // Prevent rustfmt (and thus vscode) from splitting this long line. 117 | rayon::ThreadPoolBuilder::new().num_threads(1).build_global().unwrap(); 118 | // Delete any png, csv, and mkv files from previous simulations. 119 | for dir in &[".", "img", "img_dark"] { 120 | for res in std::fs::read_dir(dir).unwrap() { 121 | if let Ok(entry) = res { 122 | let path = entry.path(); 123 | if let Some(extension) = path.extension() { 124 | if extension == "csv" 125 | || extension == "log" 126 | || extension == "mkv" 127 | || extension == "png" 128 | { 129 | if let Some(file_name_os_str) = path.file_name() { 130 | if let Some(file_name) = file_name_os_str.to_str() { 131 | if let Err(e) = fs::remove_file(path.clone()) { 132 | panic!( 133 | "Could not remove file {} from a previous simulation: {}", 134 | file_name, e 135 | ); 136 | } 137 | } 138 | } 139 | } 140 | } 141 | } 142 | } 143 | } 144 | // begin-similar-code 1 145 | // Model parameter: Initial number of agents 146 | let n0: usize = 1000; 147 | // Model parameter: Scale-free network parameter: new links per agent 148 | #[cfg(feature = "net")] 149 | let net_k: usize = 7; 150 | // Model parameter: Dimensions of the virtual landscape, in number of cells 151 | #[cfg(feature = "landscape")] 152 | let coord = WrappingCoords2d::new(100, 100).unwrap(); 153 | let birth_distro = Bernoulli::new(0.01).unwrap(); 154 | let initial_infection_distro = Bernoulli::new(0.3).unwrap(); 155 | // Model parameter: probability of infection 156 | let infection_probabilities = [0.2f64, 0.4, 0.6]; 157 | // Normal distribution to choose cells in the landscape 158 | #[cfg(feature = "landscape")] 159 | let visit_distro = Normal::new(50.0f32, 10f32).unwrap(); 160 | #[cfg(feature = "net")] 161 | let link_distro = Bernoulli::new(0.01).unwrap(); 162 | let recovery_distro = Bernoulli::new(0.8).unwrap(); 163 | let survival_distro = Bernoulli::new(0.8).unwrap(); 164 | // end-similar-code 1 165 | // Model parameter: Last time step of the simulation in each scenario 166 | let last_time_step = 100u32; 167 | let time_series_len = last_time_step as usize + 1; 168 | let mut scenarios = vec![ 169 | { 170 | let mut scenario = Scenario::default(); 171 | scenario 172 | .time_series 173 | .resize_with(time_series_len, Default::default); 174 | scenario 175 | }; 176 | infection_probabilities.len() 177 | ]; 178 | { 179 | let mut scenarios_iter = scenarios.iter_mut(); 180 | let mut id = 0; 181 | #[allow(clippy::explicit_counter_loop)] 182 | for &infection_probability in infection_probabilities.iter() { 183 | let scenario: &mut Scenario = scenarios_iter.next().unwrap(); 184 | scenario.id = id; 185 | scenario.infection_probability = infection_probability; 186 | id += 1; 187 | } 188 | assert!( 189 | scenarios_iter.next().is_none(), 190 | "checking that all scenarios are initialized" 191 | ) 192 | } 193 | let clean_term = 194 | "\r \r"; 195 | #[cfg(feature = "net-graphics")] 196 | let compress_histogram = true; 197 | scenarios 198 | .par_iter_mut() 199 | .for_each(|scenario: &mut Scenario| { 200 | // begin-similar-code 2 201 | // Use Pcg64 for reproducible random numbers; change to thread_rng for production 202 | // let mut rng = rand::thread_rng(); 203 | #[allow(clippy::unreadable_literal)] 204 | let mut rng = 205 | rand_pcg::Pcg64::new(0xcafef00dd15ea5e5, 0xa02bdbf7bb3c0a7ac28fa16a64abf96); 206 | // Model state: Agent health 207 | let mut health = SlotMap::with_capacity_and_key(2 * n0); 208 | // Model state: Bidirectional links between agents 209 | #[cfg(feature = "net")] 210 | let mut links = slotmap::SlotMap::with_capacity_and_key(n0 * n0); 211 | // Model state: Health status of each cell in the landscape 212 | #[cfg(feature = "landscape")] 213 | let mut cell_health = vec![Health::S; coord.size()]; 214 | // Model state: Cell health storage for the next time step. This implements parallel updating of cells. 215 | #[cfg(feature = "landscape")] 216 | let mut next_cell_health = cell_health.clone(); 217 | // Model initialization: Agents 218 | while health.len() < n0 { 219 | let _k: AgentKey = health.insert(Health::S); 220 | } 221 | let infection_distro = Bernoulli::new(scenario.infection_probability).unwrap(); 222 | // end-similar-code 2 223 | for (time_step, time_step_results) in scenario.time_series.iter_mut().enumerate() { 224 | // Simple, fast models do not need to print the time_step. Printing is slow. 225 | if time_step % 50 == 0 { 226 | eprint!( 227 | "{}infection_probability = {}, time_step = {}", 228 | clean_term, scenario.infection_probability, time_step 229 | ); 230 | } 231 | // begin-similar-code 3 232 | // Initialization of this time step: Network seed 233 | #[cfg(feature = "net")] 234 | { 235 | if links.is_empty() && health.len() > 1 { 236 | let mut h_it = health.iter(); 237 | let (key0, _value) = h_it.next().unwrap(); 238 | let (key1, _value) = h_it.next().unwrap(); 239 | let _link_id: LinkKey = links.insert((key0, key1)); 240 | } 241 | // Initialization of this time step: Network 242 | let keys_vec: Vec = health.keys().collect(); 243 | let mut idx_map = SecondaryMap::with_capacity(health.capacity()); 244 | let mut weights_vec: Vec = { 245 | let mut weights_map = SecondaryMap::with_capacity(health.capacity()); 246 | keys_vec.iter().enumerate().for_each(|(idx, &k)| { 247 | weights_map.insert(k, 0); 248 | idx_map.insert(k, idx); 249 | }); 250 | links.values().for_each(|&(key0, key1)| { 251 | weights_map[key0] += 1; 252 | weights_map[key1] += 1; 253 | }); 254 | keys_vec.iter().map(|&k| weights_map[k]).collect() 255 | }; 256 | keys_vec 257 | .iter() 258 | .enumerate() 259 | .for_each(|(agent_idx, &agent_key)| { 260 | let new_links = if weights_vec[agent_idx] == 0 { 261 | net_k 262 | } else if link_distro.sample(&mut rng) { 263 | 1 264 | } else { 265 | 0 266 | }; 267 | if new_links > 0 { 268 | let mut weights_tmp = weights_vec.clone(); 269 | // This agent cannot make a link to itself; set its weight to 0. 270 | weights_tmp[agent_idx] = 0; 271 | // Friends are ineligible for a new link; set friends' weights to 0. 272 | links.values().for_each(|&(key0, key1)| { 273 | if key0 == agent_key { 274 | weights_tmp[idx_map[key1]] = 0; 275 | } 276 | if key1 == agent_key { 277 | weights_tmp[idx_map[key0]] = 0; 278 | } 279 | }); 280 | match WeightedIndex::new(weights_tmp) { 281 | Ok(mut dist) => { 282 | let mut k = 0; 283 | loop { 284 | let friend_idx = dist.sample(&mut rng); 285 | links.insert((agent_key, keys_vec[friend_idx])); 286 | weights_vec[agent_idx] += 1; 287 | weights_vec[friend_idx] += 1; 288 | k += 1; 289 | if k == new_links { 290 | break; 291 | } 292 | // Make friend ineligible for a new link; set its weight to 0. 293 | if dist.update_weights(&[(friend_idx, &0)]).is_err() { 294 | break; 295 | } 296 | } 297 | } 298 | Err(WeightedError::AllWeightsZero) => {} 299 | Err(e) => { 300 | panic!("Internal error OsXJWc0sHx: {}. Please debug.", e) 301 | } 302 | } 303 | } 304 | }); 305 | // Model measurements: Network 306 | #[cfg(feature = "net-metrics")] 307 | { 308 | time_step_results.d_s = match keys_vec 309 | .iter() 310 | .zip(weights_vec.iter()) 311 | .filter(|(&k, _w)| health[k] == Health::S) 312 | .max_by_key(|(_k, &w)| w) 313 | { 314 | Some((_k, &w)) => w, 315 | None => 0, 316 | }; 317 | time_step_results.d_i = match keys_vec 318 | .iter() 319 | .zip(weights_vec.iter()) 320 | .filter(|(&k, _w)| health[k] == Health::I) 321 | .max_by_key(|(_k, &w)| w) 322 | { 323 | Some((_k, &w)) => w, 324 | None => 0, 325 | }; 326 | } 327 | #[cfg(feature = "net-graphics")] 328 | { 329 | for weight in weights_vec { 330 | *time_step_results 331 | .degree_histogram 332 | .entry(weight) 333 | .or_insert(0) += 1; 334 | } 335 | for (&weight, &frequency) in &time_step_results.degree_histogram { 336 | if compress_histogram { 337 | scenario.histogram_degrees_set.insert(weight); 338 | } else if scenario.histogram_max_degree < weight { 339 | scenario.histogram_max_degree = weight; 340 | } 341 | if scenario.histogram_height < frequency { 342 | scenario.histogram_height = frequency; 343 | } 344 | } 345 | } 346 | } 347 | // Model measurements: agents 348 | { 349 | time_step_results.time_step = time_step as u32; 350 | #[cfg(feature = "agent-metrics")] 351 | { 352 | time_step_results.n = health.len() as u32; 353 | health.values().for_each(|h| match h { 354 | Health::S => time_step_results.s += 1, 355 | Health::I => time_step_results.i += 1, 356 | }); 357 | } 358 | #[cfg(feature = "landscape-metrics")] 359 | { 360 | time_step_results.c_i = 361 | cell_health.iter().filter(|&&h| h == Health::I).count() as u32; 362 | } 363 | #[cfg(feature = "graphics")] 364 | { 365 | if scenario.agent_time_series_height < time_step_results.n { 366 | scenario.agent_time_series_height = time_step_results.n; 367 | } 368 | } 369 | #[cfg(feature = "landscape-graphics")] 370 | { 371 | if scenario.cell_time_series_height < time_step_results.c_i { 372 | scenario.cell_time_series_height = time_step_results.c_i; 373 | } 374 | time_step_results.cell_health = cell_health.clone(); 375 | } 376 | } 377 | // Dynamics: infection spreads 378 | { 379 | // Model state: Agent health the next time step 380 | let mut next_health = SecondaryMap::with_capacity(health.capacity()); 381 | #[cfg(feature = "net")] 382 | links.values().for_each(|&(key0, key1)| { 383 | let h0 = health[key0]; 384 | let h1 = health[key1]; 385 | if h0 == Health::S && h1 == Health::I && infection_distro.sample(&mut rng) { 386 | next_health.insert(key0, Health::I); 387 | } 388 | if h1 == Health::S && h0 == Health::I && infection_distro.sample(&mut rng) { 389 | next_health.insert(key1, Health::I); 390 | } 391 | }); 392 | if time_step == 0 { 393 | health.iter().for_each(|(k, &h)| { 394 | if h == Health::S && initial_infection_distro.sample(&mut rng) { 395 | next_health.insert(k, Health::I); 396 | } 397 | }); 398 | } 399 | health.iter().for_each(|(k, &h)| { 400 | // Choose a random cell to visit 401 | #[cfg(feature = "landscape")] 402 | let x = visit_distro.sample(&mut rng) as i32; 403 | #[cfg(feature = "landscape")] 404 | let y = visit_distro.sample(&mut rng) as i32; 405 | #[cfg(feature = "landscape")] 406 | let idx = coord.index(x, y); 407 | match h { 408 | Health::S => { 409 | #[cfg(feature = "landscape")] 410 | { 411 | if cell_health[idx] == Health::I 412 | && infection_distro.sample(&mut rng) 413 | { 414 | // Cell infects agent 415 | next_health.insert(k, Health::I); 416 | } 417 | } 418 | } 419 | Health::I => { 420 | #[cfg(feature = "landscape")] 421 | { 422 | if cell_health[idx] == Health::S 423 | && infection_distro.sample(&mut rng) 424 | { 425 | // Agent infects cell 426 | next_cell_health[idx] = Health::I; 427 | } 428 | } 429 | if recovery_distro.sample(&mut rng) { 430 | next_health.insert(k, Health::S); 431 | } 432 | } 433 | }; 434 | }); 435 | // Dynamics: Disease spreads across cells and infectious cells recover 436 | #[cfg(feature = "landscape")] 437 | coord.for_each8(|this_cell_index, neighbors| { 438 | match cell_health[this_cell_index] { 439 | Health::S => { 440 | for neighbor_index in neighbors { 441 | if cell_health[*neighbor_index] == Health::I 442 | && infection_distro.sample(&mut rng) 443 | { 444 | next_cell_health[this_cell_index] = Health::I; 445 | break; 446 | } 447 | } 448 | } 449 | Health::I => { 450 | if recovery_distro.sample(&mut rng) { 451 | next_cell_health[this_cell_index] = Health::S; 452 | } 453 | } 454 | } 455 | }); 456 | // Dynamics: After spreading the infection, some infectious agents die 457 | health.retain(|_agent_key, h| match h { 458 | Health::S => true, 459 | Health::I => survival_distro.sample(&mut rng), 460 | }); 461 | // Dynamics: Remaining agents update in parallel 462 | next_health.iter().for_each(|(k, &next_h)| { 463 | if let Some(h) = health.get_mut(k) { 464 | *h = next_h; 465 | } 466 | }); 467 | // Dynamics: cells update in parallel 468 | #[cfg(feature = "landscape")] 469 | { 470 | cell_health = next_cell_health.clone(); 471 | } 472 | } 473 | // Dynamics: Prune network 474 | #[cfg(feature = "net")] 475 | links.retain(|_link_key, (key0, key1)| { 476 | health.contains_key(*key0) && health.contains_key(*key1) 477 | }); 478 | // Dynamics: New agents emerge 479 | let nb = health 480 | .values() 481 | .filter(|&&h| h == Health::S && birth_distro.sample(&mut rng)) 482 | .count(); 483 | for _ in 0..nb { 484 | health.insert(Health::S); 485 | } 486 | // end-similar-code 3 487 | } 488 | }); 489 | eprint!("{}Simulation complete. Saving to disk... ", clean_term); 490 | // begin-similar-code 4 491 | #[cfg(feature = "graphics")] 492 | let mut agent_time_series_height = 0; 493 | #[cfg(feature = "landscape-graphics")] 494 | let mut cell_time_series_height = 0; 495 | #[cfg(feature = "net-graphics")] 496 | let mut histogram_degrees_set = BTreeSet::new(); 497 | #[cfg(feature = "net-graphics")] 498 | let mut histogram_max_degree = 0; 499 | #[cfg(feature = "net-graphics")] 500 | let mut histogram_height = 0; 501 | // end-similar-code 4 502 | #[cfg(feature = "csv-output")] 503 | let ts_name = "ts.csv"; 504 | #[cfg(feature = "csv-output")] 505 | let ts_err = &*format!("Error writing time series output file {}", ts_name); 506 | #[cfg(feature = "csv-output")] 507 | let ts_path = std::path::Path::new(ts_name); 508 | #[cfg(feature = "csv-output")] 509 | if ts_path.exists() { 510 | panic!( 511 | "This program just tried to rewrite {}; please debug", 512 | ts_name 513 | ); 514 | } 515 | #[cfg(feature = "csv-output")] 516 | let mut ts_file = fs::File::create(ts_path).expect(ts_err); 517 | #[cfg(feature = "csv-output")] 518 | { 519 | write!(&mut ts_file, "Infection Probability").expect(ts_err); 520 | write!(&mut ts_file, ",Time step").expect(ts_err); 521 | #[cfg(feature = "net-csv")] 522 | { 523 | write!(&mut ts_file, ",d_s Maximum network degree of susceptibles").expect(ts_err); 524 | write!(&mut ts_file, ",d_i Maximum network degree of infectious").expect(ts_err); 525 | } 526 | #[cfg(feature = "landscape-csv")] 527 | write!(&mut ts_file, ",c_i Infected cells").expect(ts_err); 528 | write!(&mut ts_file, ",n Number of agents").expect(ts_err); 529 | write!(&mut ts_file, ",s Susceptibles").expect(ts_err); 530 | writeln!(&mut ts_file, ",i Infected").expect(ts_err); 531 | } 532 | scenarios.iter().for_each(|scenario| { 533 | #[cfg(feature = "csv-output")] 534 | scenario.time_series.iter().for_each(|time_step_results| { 535 | write!(&mut ts_file, "{}", scenario.infection_probability).expect(ts_err); 536 | write!(&mut ts_file, ",{}", time_step_results.time_step).expect(ts_err); 537 | #[cfg(feature = "net-csv")] 538 | { 539 | write!(&mut ts_file, ",{}", time_step_results.d_s).expect(ts_err); 540 | write!(&mut ts_file, ",{}", time_step_results.d_i).expect(ts_err); 541 | } 542 | #[cfg(feature = "landscape-csv")] 543 | write!(&mut ts_file, ",{}", time_step_results.c_i).expect(ts_err); 544 | write!(&mut ts_file, ",{}", time_step_results.n).expect(ts_err); 545 | write!(&mut ts_file, ",{}", time_step_results.s).expect(ts_err); 546 | writeln!(&mut ts_file, ",{}", time_step_results.i).expect(ts_err); 547 | }); 548 | // begin-similar-code 5 549 | #[cfg(feature = "graphics")] 550 | { 551 | #[cfg(feature = "net-graphics")] 552 | { 553 | if compress_histogram { 554 | for degree in scenario.histogram_degrees_set.iter() { 555 | histogram_degrees_set.insert(degree); 556 | } 557 | } else if histogram_max_degree < scenario.histogram_max_degree { 558 | histogram_max_degree = scenario.histogram_max_degree; 559 | } 560 | if histogram_height < scenario.histogram_height { 561 | histogram_height = scenario.histogram_height; 562 | } 563 | } 564 | if agent_time_series_height < scenario.agent_time_series_height { 565 | agent_time_series_height = scenario.agent_time_series_height; 566 | } 567 | } 568 | #[cfg(feature = "landscape-graphics")] 569 | { 570 | if cell_time_series_height < scenario.cell_time_series_height { 571 | cell_time_series_height = scenario.cell_time_series_height; 572 | } 573 | } 574 | // end-similar-code 5 575 | }); 576 | #[cfg(feature = "csv-output")] 577 | eprintln!("{}Time series saved to {}.", clean_term, ts_name); 578 | #[cfg(feature = "graphics")] 579 | #[allow(unused_variables)] 580 | { 581 | // begin-similar-code 6 582 | #[cfg(feature = "net-graphics")] 583 | { 584 | if compress_histogram { 585 | assert!(!histogram_degrees_set.is_empty()); 586 | } 587 | assert!(histogram_height > 0); 588 | } 589 | assert!(agent_time_series_height > 0); 590 | #[cfg(feature = "landscape-graphics")] 591 | assert!(cell_time_series_height > 0); 592 | #[cfg(feature = "net-graphics")] 593 | { 594 | // A little extra space in the chart: 595 | histogram_height += 1; 596 | histogram_max_degree += 1; 597 | } 598 | agent_time_series_height += 1; 599 | #[cfg(feature = "landscape-graphics")] 600 | { 601 | cell_time_series_height += 1; 602 | } 603 | #[cfg(feature = "net-graphics")] 604 | let x_degree: std::vec::Vec<_> = histogram_degrees_set.iter().enumerate().collect(); 605 | let figure_margin = 5; 606 | #[cfg(feature = "net-graphics")] 607 | let bar_margin = 3; 608 | let thick_stroke = 4; 609 | let text_size0 = 30; 610 | let text_size1 = 17; 611 | let x_label_area_size = 40; 612 | #[cfg(feature = "net-graphics")] 613 | let x_label_offset = 1; 614 | let y_label_area_size = 60; 615 | // end-similar-code 6 616 | scenarios.iter().for_each(|scenario| { 617 | eprint!( 618 | "{}Creating figures for scenario {}/{}... ", 619 | clean_term, 620 | scenario.id, 621 | scenarios.len() 622 | ); 623 | let figure_scenario_counter = scenario.id * time_series_len as u32; 624 | scenario 625 | .time_series 626 | .par_iter() 627 | .for_each(|time_step_results| { 628 | let file_number = figure_scenario_counter + time_step_results.time_step + 1; 629 | for &dark_figures in &[false, true] { 630 | let figure_prefix = "img"; 631 | let figure_file_name = format!( 632 | "{}{}/{}.png", 633 | figure_prefix, 634 | if dark_figures { "_dark" } else { "" }, 635 | file_number 636 | ); 637 | let figure_path = std::path::Path::new(&figure_file_name); 638 | if figure_path.exists() { 639 | panic!( 640 | "This program just tried to rewrite {}; please debug", 641 | figure_path.to_str().unwrap() 642 | ); 643 | } 644 | let drawing_area = 645 | BitMapBackend::new(figure_path, (1920, 1080)).into_drawing_area(); 646 | // begin-similar-code 7 647 | let background_color = if dark_figures { &BLACK } else { &WHITE }; 648 | let transparent_color = background_color.mix(0.); 649 | let color0 = if dark_figures { &WHITE } else { &BLACK }; 650 | let color01 = color0.mix(0.1); 651 | let color02 = color0.mix(0.2); 652 | let color1 = if dark_figures { 653 | &plotters::style::RGBColor(255, 192, 0) 654 | } else { 655 | &RED 656 | }; 657 | let color2 = &plotters::style::RGBColor(0, 176, 80); 658 | let color3 = &plotters::style::RGBColor(32, 56, 100); 659 | let color_s = color2; 660 | let color_i = color3; 661 | let color0t = color0.stroke_width(thick_stroke); 662 | let color1t = color1.stroke_width(thick_stroke); 663 | let color2t = color2.stroke_width(thick_stroke); 664 | let color3t = color3.stroke_width(thick_stroke); 665 | let color_st = color2t; 666 | let color_it = color3t; 667 | let fill0 = color0.filled(); 668 | let fill01 = color01.filled(); 669 | let fill02 = color02.filled(); 670 | let fill1 = color1.filled(); 671 | let fill2 = color2.filled(); 672 | let fill3 = color3.filled(); 673 | let text0 = ("Calibri", text_size0).into_font().color(color0); 674 | let text1 = ("Calibri", text_size1).into_font().color(color0); 675 | drawing_area.fill(background_color).unwrap(); 676 | let (left_area, right_area) = drawing_area.split_horizontally(1920 - 1080); 677 | let left_panels = left_area.split_evenly((4, 1)); 678 | left_panels[0] 679 | .draw_text( 680 | &format!( 681 | "infection_probability = {}", 682 | scenario.infection_probability 683 | ), 684 | &text0, 685 | (50, 10), 686 | ) 687 | .unwrap(); 688 | #[cfg(feature = "net-graphics")] 689 | { 690 | left_panels[0] 691 | .draw_text( 692 | &format!( 693 | "d_s Max degree of susceptibles: {}", 694 | time_step_results.d_s 695 | ), 696 | &text0, 697 | (50, 100), 698 | ) 699 | .unwrap(); 700 | left_panels[0] 701 | .draw_text( 702 | &format!( 703 | "d_i Max degree of infectious agents: {}", 704 | time_step_results.d_i 705 | ), 706 | &text0, 707 | (50, 140), 708 | ) 709 | .unwrap(); 710 | } 711 | left_panels[0] 712 | .draw_text( 713 | &format!("time: {}", time_step_results.time_step), 714 | &text0, 715 | (500, 10), 716 | ) 717 | .unwrap(); 718 | #[cfg(feature = "net-graphics")] 719 | { 720 | let x_range = if compress_histogram { 721 | 0..x_degree.len() as i32 722 | } else { 723 | 0..histogram_max_degree 724 | }; 725 | let mut chart = ChartBuilder::on(&left_panels[1]) 726 | .x_label_area_size(x_label_area_size) 727 | .y_label_area_size(y_label_area_size) 728 | .margin(figure_margin) 729 | .caption("Network degree of agents", text0.clone()) 730 | .build_cartesian_2d(x_range, 0..histogram_height) 731 | .unwrap(); 732 | chart 733 | .configure_mesh() 734 | .light_line_style(&color01) 735 | .bold_line_style(&color02) 736 | .y_desc("Number of agents") 737 | .x_desc(if compress_histogram { 738 | "Network degree (removing zeroes)" 739 | } else { 740 | "Network degree" 741 | }) 742 | .axis_style(color0) 743 | .axis_desc_style(text1.clone()) 744 | .label_style(text1.clone()) 745 | .x_label_offset(x_label_offset) 746 | .x_label_formatter(&|x_position| { 747 | if compress_histogram { 748 | match x_degree.get(*x_position as usize) { 749 | Some(x_deg) => format!("{}", x_deg.1), 750 | None => format!(""), 751 | } 752 | } else { 753 | format!("{}", x_position) 754 | } 755 | }) 756 | .draw() 757 | .unwrap(); 758 | chart 759 | .draw_series( 760 | Histogram::vertical(&chart) 761 | .style(background_color.filled()) 762 | .margin(bar_margin) 763 | .data(time_step_results.degree_histogram.iter().map( 764 | |(degree, weight)| { 765 | ( 766 | if compress_histogram { 767 | x_degree 768 | .iter() 769 | .find(|&(_, °)| deg == degree) 770 | .unwrap() 771 | .0 772 | as i32 773 | } else { 774 | *degree 775 | }, 776 | *weight, 777 | ) 778 | }, 779 | )), 780 | ) 781 | .unwrap(); 782 | chart 783 | .draw_series( 784 | Histogram::vertical(&chart) 785 | .style(color0) 786 | .margin(bar_margin) 787 | .data(time_step_results.degree_histogram.iter().map( 788 | |(degree, weight)| { 789 | ( 790 | if compress_histogram { 791 | x_degree 792 | .iter() 793 | .find(|&(_, °)| deg == degree) 794 | .unwrap() 795 | .0 796 | as i32 797 | } else { 798 | *degree 799 | }, 800 | *weight, 801 | ) 802 | }, 803 | )), 804 | ) 805 | .unwrap(); 806 | } 807 | { 808 | let mut chart = ChartBuilder::on(&left_panels[2]) 809 | .x_label_area_size(x_label_area_size) 810 | .y_label_area_size(y_label_area_size) 811 | .margin(figure_margin) 812 | .caption("Populations of agents", text0.clone()) 813 | .build_cartesian_2d( 814 | 0..(time_series_len as u32), 815 | 0..agent_time_series_height, 816 | ) 817 | .unwrap(); 818 | chart 819 | .configure_mesh() 820 | .light_line_style(&color01) 821 | .bold_line_style(&color02) 822 | .y_desc("Number of agents") 823 | .x_desc("Time") 824 | .axis_style(color0) 825 | .axis_desc_style(text1.clone()) 826 | .label_style(text1.clone()) 827 | .draw() 828 | .unwrap(); 829 | chart 830 | .draw_series(LineSeries::new( 831 | scenario 832 | .time_series 833 | .iter() 834 | .skip_while(|tsr| { 835 | tsr.time_step < time_step_results.time_step 836 | }) 837 | .map(|time_step_results| { 838 | (time_step_results.time_step, time_step_results.n) 839 | }), 840 | color0, 841 | )) 842 | .unwrap(); 843 | chart 844 | .draw_series(LineSeries::new( 845 | scenario 846 | .time_series 847 | .iter() 848 | .take_while(|tsr| { 849 | tsr.time_step <= time_step_results.time_step 850 | }) 851 | .map(|time_step_results| { 852 | (time_step_results.time_step, time_step_results.n) 853 | }), 854 | color0t.clone(), 855 | )) 856 | .unwrap() 857 | .label("n Number of agents") 858 | .legend(|(x, y)| { 859 | PathElement::new(vec![(x, y), (x + 20, y)], color0t.clone()) 860 | }); 861 | chart 862 | .draw_series(LineSeries::new( 863 | scenario 864 | .time_series 865 | .iter() 866 | .skip_while(|tsr| { 867 | tsr.time_step < time_step_results.time_step 868 | }) 869 | .map(|time_step_results| { 870 | (time_step_results.time_step, time_step_results.i) 871 | }), 872 | color_i, 873 | )) 874 | .unwrap(); 875 | chart 876 | .draw_series(LineSeries::new( 877 | scenario 878 | .time_series 879 | .iter() 880 | .take_while(|tsr| { 881 | tsr.time_step <= time_step_results.time_step 882 | }) 883 | .map(|time_step_results| { 884 | (time_step_results.time_step, time_step_results.i) 885 | }), 886 | color_it.clone(), 887 | )) 888 | .unwrap() 889 | .label("i Infected agents") 890 | .legend(|(x, y)| { 891 | PathElement::new(vec![(x, y), (x + 20, y)], color_it.clone()) 892 | }); 893 | chart 894 | .configure_series_labels() 895 | .label_font(text1.clone()) 896 | .border_style(color0) 897 | .draw() 898 | .unwrap(); 899 | } 900 | #[cfg(feature = "landscape")] 901 | { 902 | let mut chart = ChartBuilder::on(&left_panels[3]) 903 | .x_label_area_size(x_label_area_size) 904 | .y_label_area_size(y_label_area_size) 905 | .margin(figure_margin) 906 | .caption("Infection of cells", text0.clone()) 907 | .build_cartesian_2d( 908 | 0..(time_series_len as u32), 909 | 0..cell_time_series_height, 910 | ) 911 | .unwrap(); 912 | chart 913 | .configure_mesh() 914 | .light_line_style(&color01) 915 | .bold_line_style(&color02) 916 | .y_desc("Number of infected cells") 917 | .x_desc("Time") 918 | .axis_style(color0) 919 | .axis_desc_style(text1.clone()) 920 | .label_style(text1) 921 | .draw() 922 | .unwrap(); 923 | chart 924 | .draw_series(LineSeries::new( 925 | scenario 926 | .time_series 927 | .iter() 928 | .skip_while(|tsr| { 929 | tsr.time_step < time_step_results.time_step 930 | }) 931 | .map(|time_step_results| { 932 | (time_step_results.time_step, time_step_results.c_i) 933 | }), 934 | color_i, 935 | )) 936 | .unwrap(); 937 | chart 938 | .draw_series(LineSeries::new( 939 | scenario 940 | .time_series 941 | .iter() 942 | .take_while(|tsr| { 943 | tsr.time_step <= time_step_results.time_step 944 | }) 945 | .map(|time_step_results| { 946 | (time_step_results.time_step, time_step_results.c_i) 947 | }), 948 | color_it, 949 | )) 950 | .unwrap(); 951 | } 952 | #[cfg(feature = "landscape")] 953 | { 954 | let landscape = right_area.margin(10, 10, 10, 10); 955 | let cells = landscape 956 | .split_evenly((coord.height() as usize, coord.width() as usize)); 957 | cells 958 | .iter() 959 | .zip(time_step_results.cell_health.iter()) 960 | .for_each(|(cell, health)| { 961 | cell.fill(match health { 962 | Health::S => color_s, 963 | Health::I => color_i, 964 | }) 965 | .unwrap(); 966 | }); 967 | } 968 | // end-similar-code 7 969 | } 970 | }); 971 | }); 972 | eprint!("{}Figures saved to the img and img_dark directories.\nWriting video.mkv; open log file video.log to follow progress.", clean_term); 973 | // Debug levels for the "level" variable: warning 24, info 32, verbose 40 974 | match std::process::Command::new("ffmpeg") 975 | .env("FFREPORT", "file=video.log:level=32") 976 | .args(&[ 977 | "-r", 978 | "20", 979 | "-i", 980 | "img_dark/%d.png", 981 | "-loglevel", 982 | "warning", 983 | "-hide_banner", 984 | "video_dark.mkv", 985 | ]) 986 | .status() 987 | { 988 | Ok(ffmpeg_status) => eprintln!( 989 | "{}Created video.mkv; {}. Learn more by reviewing video.log.", 990 | clean_term, ffmpeg_status 991 | ), 992 | Err(e) => eprintln!( 993 | "{}Could not create video.mkv: {}.\nPlease review file video.log, if it exists, to learn more.", 994 | clean_term, e 995 | ), 996 | } 997 | eprintln!("Move important output files to a safe location.\nAny csv, png, and mkv files will be removed next time you run this program."); 998 | } 999 | } 1000 | --------------------------------------------------------------------------------