Simulation with PythonDevelop Simulation and Modelingin Natural Sciences, Engineering,and Social SciencesRongpeng LiAiichiro NakanoSimulation with Python: Develop Simulation and Modeling in Natural Sciences,Engineering, and Social Sciences Rongpeng Li Aiichiro Nakano Los Angeles, CA, USA Los Angeles, CA, USA ISBN-13 (pbk): 978-1-4842-8184-0 ISBN-13 (electronic): 978-1-4842-8185-7 https://doi.org/10.1007/978-1-4842-8185-7 Copyright 2022 by Rongpeng Li and Aiichiro Nakano This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made.
The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Development Editor: Laura Berendson Coordinating Editor: Aditee Mirashi Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@ springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub (Github.com/apress). For more detailed information, please visit http://www.apress. com/source-code.
Printed on acid-free paper To Yan, for everything.RonTable of Contents About the Authors ix About the Technical Reviewer xi Acknowledgments xiii Introduction xv Chapter 1: Calculating Pi with Monte Carlo Simulation 1 Background 1 The Wise Persons Competition 1 Estimating Pi by Sprinkling Grains 2 Exercise 10 Contain the Goat! 10 What Randomness? 11 Exercise 18 Summary 18 Chapter 2: Markov Chain, a Peek into the Future 19 Weather Forecasting 19 Eigenstates of Markov Chains 25 Exercise 27 Markov Chain Applications 27 A Random Walk That Has an End 28 Sonnet Written by Drunk Shakespeare 31 Exercise 36 Summary 37 v Table of ConTenTs Chapter 3: Multi-armed Bandits, Probability Simulation, and Bayesian Statistics 39 Random Pick and Naive Greedy Approach 40 Greedy-Epsilon: Greedy but Not Always 44 An Improved Greedy-Epsilon Algorithm 45 Exercise 46 The Bayesian Way, a Primer on Bayesian Statistics 47 Exercise 53 Summary 54 Chapter 4: Balls in a 2-D Box, a Simple Physics Engine 55 One Ball in a 2-D Box 55 Physics Law of Motion 57 Collision Detection 60 Exercise 65 Multiple Balls in a 2-D Box 65 Update of Positions and Velocity upon Collision 65 Collision Detection in Multiple-Ball Scenario 74 Exercise 75 Summary 76 Chapter 5: Percolation, Threshold, and Phase Change 77 Problem Introduction 78 Percolation and the Critical Probability 82 An Analytical Solution for the 1-D Case 82 A Simulation for the 2-D Case 83 Exercise 90 Another Interesting Statistic in 2-D Grid Percolation 90 Exercise 93 Summary 94 vi Table of ConTenTs Chapter 6: Queuing System: How Stock Trades Are Made 95 Trading Process Fundamentals 95 The Order Book 96 Create the Interfaces and Determine the Data Schema 98 Implement Order Book Logic 102 Hook the Bots and Engine Together 107 Exercises and Extension Ideas 109 Multiple Bots 109 An Informed Bot 110 Order Book Visualization 110 Order Cancellation Support 110 Stop Orders Support 110 Summary 110 Chapter 7: Rock, Scissors, and Paper: Multi-agent Simulation 111 Community Formation on a Street 112 Exercise 116 How to Win a Global Rock, Paper, and Scissors Contest 116 Exercise 125 Summary 126 Chapter 8: Disease Spreading, Simulating COVID-19 Outbreak 127 Simplifying the Real World 127 The SI Model 129 Exercise 133 The SIR Model 133 Exercise 137 Summary 137 vii Table of ConTenTs Chapter 9: Misinformation Spreading and Simulations on a Graph 139 Model the Social Network 139 Simulate Misinformation Spreading 143 Simple Cases 144 Misinformation Spreading on Different Networks 152 Exercise 161 Summary 161 Index 163 viii About the AuthorsRongpeng Li is the business intelligence team lead at Unit21. He was a senior data scientist and data science instructor at Unit21. Rongpeng Li graduated from USC with two masters, one in physics and another in electrical engineering. He is a keen educator. He authored one statistics book derived from his voluntary services in the data community. Aiichiro Nakano (advisory author) is a professor of computer science and physics and astronomy with joint appointments in quantitative and computational biology and collaboratory for advanced computing and simulations at the University of Southern California.
He received a PhD in physics from the University of Tokyo, Japan. His research areas are scalable scientific algorithms, high-end parallel supercomputing, scientific visualization and informatics, and computational materials science. He is a Fellow of the American Physical Society. ix About the Technical ReviewerKacie Webster is currently a data analyst in the telecommunications industry. After graduating from San Diego State University with a degree in statistics and economics, she completed a data science bootcamp where she gained the skills to become a data professional. xi Acknowledgments Rongpeng Li would like to thank all his previous students for the inspiration of this book, from readers at local libraries to learners in his Zoom classroom. xiii Introduction This book is a small gift to a younger me, probably in high school or even earlier. xiii
Next page