<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/discrete-event-simulation-in-r-and-why-r-is-different/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://matloff.wordpress.com/2017/04/05/discrete-event-simulation-in-r-and-why-r-is-different/"> Mad (Data) Scientist</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I was pleased to see <a target="_blank" rel="nofollow" href="https://www.r-bloggers.com/simmer-3-6-1/">the announcement yesterday</a> of <strong>simmer 3.61</strong>. a discrete-event simulation (DES) package for R. I’ve long had an interest in DES, and as I will explain below, implementing DES in R brings up interesting issues about R that transcend the field of DES. I had been planning to discuss them in the context of <a target="_blank" rel="nofollow" href="https://github.com/matloff/des">my own DES package for R</a>, and the above announcement will make a good springboard for that.</p>
<p>First, what is DES? It is simulation of stochastic processes with discrete state space. Consider for instance the classic M/M/1 queue: exponential interarrival and service times, with a single server. The state space can be defined as the queue length, which is integer-valued and thus “discrete.” This contrasts to, say, simulating a weather system, where state such as temperature is continuous.</p>
<p>The key component of such a simulator, no matter which programmer world view the software takes (see below) is the <em>event list</em>.  At any simulated time <strong>t</strong>, the event list records all the events that are supposed to happen after time <strong>t</strong>. In the M/M/1 queue example, for instance, at time 168.0, there might be a service completion scheduled for time 169.1, and an arrival at 182.2.</p>
<p>The main loop of a DES program then consists of:</p>
<ul>
<li>Remove the earliest event <strong>e</strong> in the event list; <strong>e</strong> will be represented as some kind of data structure, including event time, event type and so on.</li>
<li>Update the current simulated time to the time in <strong>e</strong>.</li>
<li>Simulate the execution of<strong> e</strong>.</li>
</ul>
<p>The looping continues until the user-specified maximum simulation time is exceeded.</p>
<p>The M/M/1 case is simple (not to mention having a closed-form theoretical solution), but in complex systems the event list can be quite large, say thousands of events. In such cases, good performance means executing the first of the above three bulleted items efficiently. Classically, there has been much research on this (including theoretical models using renewal theory and the like). <strong>But what about doing this in R?</strong></p>
<p>The <strong>simmer</strong> package handles this by…NOT doing it in R. <img alt="🙂" class="wp-smiley" src="https://i0.wp.com/s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png?w=456&ssl=1" data-recalc-dims="1"> If one needs the performance, this is the obvious route to take. (This is not quite true in a certain sense, also explained below.)</p>
<p>I developed my <strong>DES</strong> package entirely in R, mainly because I aimed it only as proof-of-concept. It’s been around for a few years, first on my own Web page then more recently on GitHub. I did it for use by my students, and because it seemed that periodically there have been questions on r-help along the lines of “Is there a DES package available for R?”</p>
<p>Most algorithms for handling event lists use some kind of <em>priority queue</em>, implemented a a binary tree. Since R lacks pointers, it is not easy to develop such thing, much less do it efficiently. So I just chose to implement the event list in <strong>DES</strong> as straight R vector, maintained in sorted order. But when a new event is inserted, a time-consuming operation ensues, due to the need to keep the event list in ascending order. Originally, I implemented this as binary search.</p>
<p><strong>Later I realized that this was anti-R</strong>. I knew it would be slow, of course, but didn’t think much about alternatives. Then later it occurred to me:</p>
<ul>
<li>Just add new events at the tail end.</li>
<li>Don’t keep the event list in sorted order.</li>
<li>In first bullet above in the event loop, simply find the earliest event by calling R’s <strong>which.min()</strong>.</li>
</ul>
<p>True, <strong>which.min() </strong>does an inefficient linear search. But it does it at C (not sea) level! Unless the event list is larger than any one I know of in practice, this will be a win.</p>
<p>Now, what about my pure-R <strong>DES</strong> package vs. <strong>simmer</strong>, which does its core operations in C++? The <strong>simmer</strong> package ought to be faster, right? Actually, yes, but one must first understand that they actually are not comparable, as follows.</p>
<p>There are two main programming paradigms (“world views”) in DES. Let’s illustrate that with M/M/1:</p>
<ul>
<li><em>Event-oriented:</em> Here the code explictly recognizes how one event triggers others. For a job arrival in M/M/1, the code to react to that arrival will see whether to add the job to the server queue, vs. starting it now if the queue is empty, and that same code will schedule the next job arrival.</li>
<li><em>Process-oriented. </em>Here each entity more or less “minds its own business,” with fewer lines of code that explicitly show interactions between entities. In M/M/1 we might have an arrival process function and a server process function. The latter function might watch the queue continually to see when it becomes nonempty, and the former function might add the newly-arriving job to the queue, but NOT start service for the job in the case of an empty queue, as would be the case for the event-oriented approach.</li>
</ul>
<p>The pros and cons are: The event-oriented approach is much easier to implement, but arguably less clear. The process-oriented approach requires threading of some kind (not necessarily the “classical” kind), but most people, including me, consider it clearer and more elegant.</p>
<p>The <strong>simmer</strong> package is process-oriented, and in fact is modeled on <a target="_blank" rel="nofollow" href="http://heather.cs.ucdavis.edu/~matloff/simpy.html">SimPy,</a> a popular DES library written in Python. I’m a big fan of SimPy, which is another reason why I like <strong>simmer</strong>.</p>
<p><strong>HOWEVER</strong>, the process-oriented approach, <em>ceteris paribus</em>, tends to be slow. This is due to various reasons related to the threading, but at any rate, the event-oriented approach, for all its inelegance, does tend to excel somewhat in this regard.</p>
<p>My <strong>DES</strong> package is event-oriented. So, I was curious which package would be faster, the pure-R event-oriented code or the R-calls-C++ process-oriented code. So I did a small experiment. (Disclaimer: Not claimed to generalize.) Both packages include M/M/1 examples, so I ran them for various values of the mean interarrival and service rates. I won’t enumerate the results here, but generally the C++/process-oriented runs were about 25-50% faster than the R/event-oriented ones.</p>
<p>There may be many issues here. For instance, DES’ deletion of an event involves code like</p>
<pre><code> simlist$evnts &lt;- simlist$evnts[-i,,drop=F]</code></pre>
<p>This may involve reallocating memory for the entire matrix.</p>
<p>I will leave all this as an exercise for the reader. <img alt="🙂" class="wp-smiley" src="https://i0.wp.com/s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p> </p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matloff.wordpress.com/1696/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/matloff.wordpress.com/1696/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://matloff.wordpress.com/2017/04/05/discrete-event-simulation-in-r-and-why-r-is-different/"> Mad (Data) Scientist</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/9GobhKuxoN4"></a></div>