<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aayush Sabharwal on Medium]]></title>
        <description><![CDATA[Stories by Aayush Sabharwal on Medium]]></description>
        <link>https://medium.com/@aayush-sabharwal?source=rss-a51cc4832838------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vUhmAMo6x52yYihLHo8vow.jpeg</url>
            <title>Stories by Aayush Sabharwal on Medium</title>
            <link>https://medium.com/@aayush-sabharwal?source=rss-a51cc4832838------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:53:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aayush-sabharwal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My GSOC Journey #4: The code, and beyond]]></title>
            <link>https://aayush-sabharwal.medium.com/my-gsoc-journey-4-the-code-and-beyond-94bba8b1fe5f?source=rss-a51cc4832838------2</link>
            <guid isPermaLink="false">https://medium.com/p/94bba8b1fe5f</guid>
            <category><![CDATA[julialang]]></category>
            <category><![CDATA[gsoc]]></category>
            <category><![CDATA[agent-based-modeling]]></category>
            <dc:creator><![CDATA[Aayush Sabharwal]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 15:40:33 GMT</pubDate>
            <atom:updated>2021-08-20T15:40:33.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5RBYeGe0VLB6t_ZsvO_wQ.png" /></figure><p>My GSOC’21 proposal was a two-part project, aimed at adding features to Agents.jl. The first proposal was adding the capability to save and load agent-based models to and from files. This enables models to be restarted from any point easily, and also enables transferring the entire model state to any other system. The second part of the proposal focused on improving path-finding functionality in Agents.jl. It improved flexibility by reworking the user API to allow granular control over pathfinding parameters, and support multiple different profiles for pathfinding. Additionally, it also added path-finding support to ContinuousSpace, allowing it to be used in a wider variety of scenarios.</p><p>The multiple pull-requests implementing this functionality have already been merged into the main repository, and released as new version(s) of the library. Throughout this process, my mentors, <a href="https://github.com/Libbum">Tim DuBois</a> and <a href="https://github.com/Datseris">George Datseris</a>, and I regularly communicated to ensure we were moving in the right direction. They constantly ensured my work was up to the mark, and I learned a great deal from them.</p><h3>What <em>is</em> Agents.jl?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*89ot9CF-WvbL6sh7XYQL3g.gif" /></figure><p>Agents.jl is an agent-based modeling library. As stated in <a href="https://juliadynamics.github.io/Agents.jl/stable/">the documentation</a> it enables performant, flexible, and scalable agent-based models to be created easily. Agent-based models (ABMs in short) are used to simulate a variety of phenomena, from epidemic spread to chemical processes, in a bottom-up manner. The user creates independently acting entities (agents) whose behaviour is determined by a predefined set of rules. The agents interact with and respond to changes in their environment, including other agents. For an excellent further explanation of agent-based modeling, and the capabilities of Agents.jl, refer to <a href="https://www.youtube.com/watch?v=Iaco6v6TVXk">Tim’s amazing talk</a> at JuliaCon’21.</p><h3>The project</h3><p>All the pull-requests (PRs) involving my work and the issues opened during this period can be searched for in <a href="https://github.com/JuliaDynamics/Agents.jl">Agents.jl</a> and <a href="https://github.com/JuliaDynamics/InteractiveDynamics.jl/">InteractiveDynamics.jl</a> using the GSOC tag as a filter.</p><h4>Before the coding period: CSV Integration</h4><p>My project started two weeks before the official coding period began. Tim, George and I decided that it would be good to get a head-start on the project while participating in The Julia Language’s excellent community interaction period.</p><p>We decided to add the capability of loading and saving agent properties to and from CSV files. This involved using <a href="https://github.com/JuliaData/CSV.jl">CSV.jl</a> to serialize and deserialize agent data. The relevant work can be found in <a href="https://github.com/JuliaDynamics/Agents.jl/pull/499">this PR</a> and <a href="https://github.com/JuliaDynamics/Agents.jl/issues/403">the issue it closed</a>. The result added two new functions: populate_from_csv! (to populate a model using agent data in a CSV file) and dump_to_csv (to dump agent data to a CSV file). These functions are designed to be flexible enough for a wide range of scenarios. They also make use of metaprogramming to reduce verbosity, automatically inferring several details about the data to be saved/loaded.</p><p>To know more about this part of my project, check out <a href="https://aayush-sabharwal.medium.com/my-gsoc-journey-1-so-it-begins-8e26c8cc16df">this blog post</a>!</p><h4>Phase 1: Model (De)Serialization</h4><p>This phase involved implementing model (de)serialization, as in the proposal. The relevant work can be found in the following PRs:</p><ul><li><a href="https://github.com/JuliaDynamics/Agents.jl/pull/505">#505:JLD2 Integration</a></li><li><a href="https://github.com/JuliaDynamics/Agents.jl/pull/509">#509:Fix Schelling Example</a></li><li><a href="https://github.com/JuliaDynamics/Agents.jl/pull/511">#511:OSMSpace Serialization</a></li></ul><p>as well as the following issues they closed:</p><ul><li><a href="https://github.com/JuliaDynamics/Agents.jl/issues/496">#496:Model (De)Serialization</a></li><li><a href="https://github.com/JuliaDynamics/Agents.jl/issues/508">#508:JLD2 integration doesn’t work with Documenter builds</a></li><li><a href="https://github.com/JuliaDynamics/Agents.jl/issues/513">#513:OSM.random_road_position and OSM.random_route! are not reproducible</a></li></ul><p>We decided to use <a href="https://github.com/JuliaIO/JLD2.jl">JLD2.jl</a> for the serialization and deserialization functionality. It provided an easy to use format that can handle complex types and nested data structures, which served our purposed perfectly. Although JLD2.jl provides its own custom serialization functionality, it proved to be too limiting for our purposes. Models also contain some non-serializable data, notably functions, which needed to be provided during model reconstruction at deserialization time. To enable passing this data as keywords during deserialization, a simple type conversion functionality was added. It recursively converts all relevant types to their serializable versions and vice-versa. This functionality, along with the CSV integration mentioned above, is extensively documented and tested. Writing tests for model serialization (referred to in the documentation as “checkpointing”) proved to be a complicated endeavour since it had to account for a large variety of models and spaces. This, however, revealed several bugs that were resolved as soon as they were found.</p><p>As an additional feature, we also decided to use Scratch.jl for keeping track of update messages printed in the REPL. The feature was merged in <a href="https://github.com/JuliaDynamics/Agents.jl/pull/514">this PR</a> and closed <a href="https://github.com/JuliaDynamics/Agents.jl/issues/493">this issue</a>.</p><p>To know more about this phase of my project, check out <a href="https://aayush-sabharwal.medium.com/my-gsoc-journey-2-a-lot-of-code-and-a-lot-more-tests-6ea8ade6c715">this blog post</a>!</p><h4>Phase 2: Pathfinding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dUmAkPeKcIen-FRF0OueKw.gif" /></figure><p>The final phase of the project was improving pathfinding and adding it to ContinuousSpace. The relevant work can be found in the following PRs:</p><ul><li><a href="https://github.com/JuliaDynamics/Agents.jl/issues/520">#520:Pathfinding rework</a></li><li><a href="https://github.com/JuliaDynamics/Agents.jl/pull/531">#531:Continuous Space Pathfinding</a></li></ul><p>and <a href="https://github.com/JuliaDynamics/Agents.jl/issues/515">this issue</a>.</p><p>This was by far the longest and toughest set of features to implement. After a long discussion, we decided to completely and breakingly rework the pathfinding API. This allowed the AStar struct holding all the relevant data to be entirely separate from the model, and also allow multiple different structs with different parameters (representing different profiles) to be used. The changes provide a framework for future additions to the pathfinding API, including new algorithms. Using this framework, pathfinding support was added to ContinuousSpace. This helped to test the extensibility and scalability of the framework. <a href="https://juliadynamics.github.io/Agents.jl/stable/examples/rabbit_fox_hawk/">An example</a> to document the new capabilities of the pathfinding system was also created. It went through several revisions, transitioning from 2D to 3D and from GridSpace to ContinuousSpace.</p><p>To know more about this phase of my project, check out <a href="https://aayush-sabharwal.medium.com/my-gsoc-journey-3-the-great-rework-b37ab0b1733c">this blog post</a>!</p><h4>Stretch goals</h4><p>After completing my proposed changes, Tim, George and I decided I should work on some stretch goals to further improve the new features. These include:</p><ul><li>Benchmarking and improving upon the performance of the A* pathfinding functionality. (<a href="https://github.com/JuliaDynamics/Agents.jl/issues/537">issue</a>) (<a href="https://github.com/JuliaDynamics/Agents.jl/pull/540">PR</a>)</li><li>Adding compression support to the checkpointing API. (<a href="https://github.com/JuliaDynamics/Agents.jl/issues/522">issue</a>)</li></ul><h3>Beyond the code</h3><p>GSOC is not just about the code you write. It creates a platform for open-source enthusiasts to interact, both within and across organisations. I had the opportunity to meet a great number of people, working with different organizations, using different technologies, and with vastly different interests.</p><p>During the community bonding period, The Julia Language created a slack channel for all of us to interact. They also created a custom <a href="https://www.gather.town/">gather.town</a>, where we could all meet as virtual avatars of ourselves. Several of us used this extensively to talk about each others’ projects, and more. Meeting people from all over the world, working on all sorts of projects, was a great learning experience.</p><p>Most importantly, though, I would really like to thank my mentors Tim and George for being the best mentors I could have asked for. Both of them were extremely responsive with all my ideas, issues and changes. They considered every idea (and there were <em>a lot</em>), and were very helpful with every problem I faced, large or small. I also value that they took time out of their busy schedules for our weekly video calls, discussing the progress made and the plan for the next week. They were very prompt in their feedback to any changes made, constantly providing helpful reviews. Both of them also provided interesting and useful insights about their own work, the Julia ecosystem as a whole, and various aspects of academia.</p><p>I am extremely grateful that they showed confidence in my abilities to find solutions to difficult problems. Tim and George involved me in matters even beyond the scope of my project, including things such as the direction of Agents.jl as a whole moving forward and the talk at JuliaCon’21.</p><p>I will definitely continue to contribute to the Julia community in the future. I look forward to working more on Agents.jl alongside Tim and George, to make it the premier agent-based modeling library (if <em>somehow</em> it isn’t already).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94bba8b1fe5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My GSOC Journey #3: The Great Rework]]></title>
            <link>https://aayush-sabharwal.medium.com/my-gsoc-journey-3-the-great-rework-b37ab0b1733c?source=rss-a51cc4832838------2</link>
            <guid isPermaLink="false">https://medium.com/p/b37ab0b1733c</guid>
            <category><![CDATA[gsoc]]></category>
            <category><![CDATA[agent-based-modeling]]></category>
            <category><![CDATA[julialang]]></category>
            <dc:creator><![CDATA[Aayush Sabharwal]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 14:13:49 GMT</pubDate>
            <atom:updated>2021-08-11T14:13:49.119Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a while, hasn’t it? I recently completed the last part of my GSOC proposal! Check out my previous blog posts <a href="https://aayush-sabharwal.medium.com/my-gsoc-journey-1-so-it-begins-8e26c8cc16df">here</a> and <a href="https://aayush-sabharwal.medium.com/my-gsoc-journey-2-a-lot-of-code-and-a-lot-more-tests-6ea8ade6c715">here</a>. The last part of my proposal was making the existing pathfinding functionality in <a href="https://github.com/JuliaDynamics/Agents.jl">Agents.jl</a> more flexible, and extending it to ContinuousSpace. While a fairly straightforward idea, this was an undoubtedly long and complicated set of changes. Much more than I, and dare-I-say my mentors <a href="https://github.com/Datseris">George</a> and <a href="https://github.com/Libbum">Tim</a>, expected it to be.</p><h3>The problem</h3><p>The way pathfinding worked at the time involved passing a Pathfinder struct to the GridSpace constructor, which used it to create <em>another</em> struct, which was stored in the space. Not only did this tie an optional functionality to the space unnecessarily, it also necessitated an extra field and type parameter in the struct that wasn’t used most of the time. One of my goals of making pathfinding more flexible was to allow multiple “profiles”. What if you want to simulate both birds and rabbits? They don’t move around the same way, necessitating different pathfinding parameters: in other words, different profiles.</p><h4>The solution</h4><p>After <a href="https://github.com/JuliaDynamics/Agents.jl/issues/515">a lot of deliberation</a> and many ideas, we finally converged upon the best solution: The current implementation is too closely tied to the space, isn’t scalable or flexible. A complete, breaking, rework was required. The core code would remain largely the same, but the pathfinding struct (AStar) would be separate from the space. This also eliminated the need for the intermediary Pathfinder struct, since it only facilitated creating AStar inside GridSpace anyway. The user creates and stores AStar structs as they see fit, and pass them into any method that requires it. This has two major advantages:</p><ul><li>It directly leads to multiple profiles, since the user can choose which struct to pass into the pathfinding functions.</li><li>It is scalable to other types of pathfinding algorithms and other spaces without polluting any of the core code, since all that is required is defining new methods and/or structs</li></ul><p>While this would be breaking, which is definitely something to avoid where possible, the benefits outweigh the costs. Since pathfinding itself was also very new, it was highly unlikely this would annoy many users.</p><p>The key takeaway from all of this discussion was that I need to spend more time before adding new features. In addition to considering how to make new features easy to use, one should also consider scalability and flexibility of the implementation, and how it impacts the overall maintainability of the codebase.</p><h3>Pretty pictures</h3><p>The rework itself didn’t take much time, since all that was necessary was adding a more convenient AStar constructor and refactoring the pathfinding-related methods. To showcase the new capabilities, I made a modified predator-prey simulation involving 3 species of animals (rabbits, foxes, and hawks) on mountainous terrain. This needed two profiles, one for land animals and one for airborne ones. The initial implementation used a height-map on a 2D grid. Here’s a GIF of it running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*i3UIevaSpTi2vpwp23uS6g.gif" /><figcaption>Rabbits are brown circles, Foxes are yellow squares, and Hawks are blue triangles</figcaption></figure><p>Over a video call, Tim, George and I decided this could be an excellent demonstration of a 3D model, which we didn’t have any examples of. For this, I also ended up implementing visualisation support for 3D models in <a href="https://github.com/JuliaDynamics/InteractiveDynamics.jl/">InteractiveDynamics.jl</a>, which contains visualization functions for several <a href="https://github.com/JuliaDynamics">JuliaDynamics</a> packages. It ended up looking like <a href="https://juliadynamics.github.io/Agents.jl/stable/examples/rabbit_fox_hawk/#Rabbit,-Fox,-Hawk">this</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*UIB-ktNP-FcpbqEVIIOh8Q.gif" /><figcaption>The agents follow the same colour scheme. It’s a bit fast, but much prettier, don’t you think?</figcaption></figure><p>To ensure our new pathfinding API was everything we wanted it to be, it was decided that I would branch off the current pathfinding_rework branch to extend pathfinding to ContinuousSpace first. Once that was merged back into pathfinding_rework, we would be sure that the new API is robust.x</p><p>The idea for adding pathfinding to ContinuousSpace was simple enough: use the exact same code, and simply divide the space into a discrete grid. Having discrete properties distributed over a ContinuousSpace is something I’ve had to deal with in my models too. Since it would be used in pathfinding as well, I opened an <a href="https://github.com/JuliaDynamics/Agents.jl/issues/524">issue</a> about this.</p><h3>Devil’s Advocate</h3><blockquote>A lot of features might sound nice, but in the end each one should have a robust reason to exist</blockquote><p>George closed this through a PR, but before discussing the problem, he posed a simple question: Why do we need pathfinding in ContinuousSpace anyway? What does it accomplish that can’t happen in GridSpace?</p><p><em>This</em> wasn’t something I was expecting. Why <em>wouldn’t</em> you want continuous pathfinding? In my mind, it was a logical extension of the existing functionality. Nevertheless, I had to come up with a strong reason and this forced me to question the underlying premise of my proposal. I concluded (with the agreement of both George and Tim) that it allows the concept of speed to exist, which is not possible in GridSpace. For example, foxes can move at 1.3 times the speed of rabbits.</p><p>George, by playing devil’s advocate, forced me to justify my proposed changes. This is something I definitely plan to do for myself from now on. A lot of features might sound nice, but in the end each one should have a robust reason to exist, or else end up bloating the library unnecessarily.</p><h3>Continuous complexities</h3><p>Although adding pathfinding to ContinuousSpace was fairly easy, there were a lot of small intricacies and edge cases to be addressed. For starters, there would need to be repeated conversion between coordinates in ContinuousSpace, and indexes of the underlying grid on which A* is run. I decided to store the final path in the coordinates of the space, since it would only need to be computed once and would simplify other functions.</p><p>Moving along a path in GridSpace is straightforward: just move to each successive grid index in each successive iteration. ContinuousSpace, however, has to interpolate between each point on the path. This requires accounting for floating-point error, fast-moving agents overshooting the target, and some vector math. Additionally, the space can be periodic, so going off one side of the space wraps around to the opposite side. This implies that the vector from point A to point B isn’t just B-A but instead this absurdity (in Julia code):</p><pre>best = to .- from<br>for offset in Iterators.product([-1:1 for _ in 1:D]...)<br>    dir = to .+ offset .* size(space) .- from<br>    if sum(dir .^ 2) &lt; sum(best .^ 2)<br>        best = dir<br>    end<br>end</pre><p>As usual, tests came to the rescue here. After implementing (what I thought were) working continuous pathfinding methods, I added tests for them. Needless to say, it took several iterations of finding and eradicating edge cases to finally get it right.</p><p>Agents.jl has the pre-existing functions random_position (to get a random position in a discrete space) and nearby_positions (to iterate over valid positions surrounding an agent). Since pathfinding has a concept of whether or not a position can be walked on, we decided to add versions of these methods that take such conditions into account. Consequently, random_walkable and nearby_walkable were added. The former returns a random walkable position (in both GridSpace and ContinuousSpace) and the latter returns an iterator over walkable positions surrounding an agent (in GridSpace only).</p><p>Note how in GridSpace, an agent can be instructed to move to a nearby position using nearby_walkable. However, this isn’t really possible with ContinuousSpace. To combat this, I also added a method for random_walkable that returns a random walkable position within a given radius of a given position. Since ContinuousSpace has theoretically infinite positions, implementing nearby_walkable for it isn’t possible and doesn’t make sense anyway.</p><h3>Prettier pictures</h3><p>With this implemented and merged, we decided to shift the example I made to ContinuousSpace. Besides showing off the new features, it also made sense to be able to give different animals different speeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*hM5jwkpSnZmLFsJ--jTV9w.gif" /><figcaption>All animals are spheres now, which is <a href="https://en.wikipedia.org/wiki/Spherical_cow">anecdotally appropriate</a></figcaption></figure><h3>In conclusion</h3><p>This completes all of the changes in my proposal. Since I still have two weeks left before evaluations, we decided I should work on some other smaller issues, such as adding compression to my checkpointing system and improving the performance of the A* implementation.</p><p>Google Summer of Code turned out to be an amazing experience. I learned a lot from it, and met many incredible people in the Julia and Open Source communities from all over the world. Agents.jl is more than a GSOC project for me, though. I use it often for my own models, and definitely will continue to contribute to it in the future.</p><h3>Stay tuned!</h3><p>I have another post coming up summarising all my work, as well about the GSOC journey beyond the code, including the incredible people I met and worked with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b37ab0b1733c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My GSOC Journey #2: A lot of code, and a lot more tests]]></title>
            <link>https://aayush-sabharwal.medium.com/my-gsoc-journey-2-a-lot-of-code-and-a-lot-more-tests-6ea8ade6c715?source=rss-a51cc4832838------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea8ade6c715</guid>
            <category><![CDATA[agent-based-modeling]]></category>
            <category><![CDATA[gsoc]]></category>
            <category><![CDATA[julialang]]></category>
            <dc:creator><![CDATA[Aayush Sabharwal]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 13:47:21 GMT</pubDate>
            <atom:updated>2021-06-22T13:47:21.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5RBYeGe0VLB6t_ZsvO_wQ.png" /></figure><p>It’s just over two weeks into the <em>official</em> coding period now! I just finished the first half of my project, involving a few more PRs. For a summary of my first PR of GSOC, refer to <a href="https://aayush-sabharwal.medium.com/my-gsoc-journey-1-so-it-begins-8e26c8cc16df">my previous post</a>.</p><p>For this PR, I worked on adding the capability to save an entire agent-based model to a file. It’s a pretty useful feature to have, since it allows persisting the state of a model even after the REPL is closed. It also enables running the model for some time, then simulate various branching scenarios from that point on. It’s as simple as saving the model, then loading it up once for each scenario from the same file. The serialization capability is enabled by <a href="https://github.com/JuliaIO/JLD2.jl">JLD2.jl</a>. In its own words, JLD2.jl “saves and loads Julia data structures in a format comprising a subset of HDF5”. Basically, it can serialize most things thrown at it. Perfect for saving the model.</p><p>Initially, the plan was to use JLD2’s custom serialization capability. What this allows me to do is specify that the ABM struct should be saved instead as SerializableABM, and define conversions between the two. This is necessary since the struct contains both non-serializable data (functions) and data that can be saved in a much nicer/more compact format (flattening dictionaries to a list of pairs). Anything that isn’t set to be converted is just saved as-is, which is perfect for not having to rewrite any code if more functionality is added.</p><p>Unfortunately, this approach turned out to have a major issue. Take the example of ABM.scheduler. It’s a function, so it can’t be serialized, so I omit it from SerializableABM. The scheduler can then just be taken as a parameter during deserialization. The issue comes up when the actual ABM struct is reconstructed from SerializableABM. Since JLD2 handles deserialization, it doesn’t allow passing extra parameters to the reconstruction function. I can’t change it after reconstruction since the ABM struct is immutable. In our weekly meet, Tim, George and I decided the best solution would be to effectively re-implement the custom (de)serialization functionality and allow passing keyword arguments to the functions that reconstruct.</p><p>This actually turns out to be a lot easier than it looks. All I needed to do was define two functions:</p><pre>to_serializable(t) = t</pre><pre>from_serializable(t; kwargs…) = t</pre><p>The to_serializable function takes something as input, and returns the serializable version of it. The from_serializable function does exactly the opposite, except it also takes keyword arguments. Since Julia uses <a href="https://en.wikipedia.org/wiki/Multiple_dispatch">multiple-dispatch</a> (one of my favourite features of the language), and the default implementation of these functions isn’t type-specific, they both return whatever was passed in. To define a custom serialization format for a type, I just have to create a more specific method. For example, the model struct is of type ABM, so all I have to do is create a SerializableABM struct and define methods with the following signatures:</p><pre>to_serializable(t::ABM)</pre><pre>from_serializable(t::SerializableABM{S,A}; kwargs…) where {S,A}</pre><p>Since these are more specific than the defaults, they will be used when an ABM/SerializedABM is passed in. To save a model, I pass it into to_serializable and let JLD2 serialize the result to a file. To load it back in, JLD2 gives me the SerializableABM from the file and I can just chuck it into from_serializable to get back the model. Additionally, I can pass any keyword arguments to from_serializable and use them wherever necessary. Of course, the user doesn’t have to do all this. They can just use the save_checkpoint and load_checkpoint functions, which do the heavy-lifting. Pretty cool, isn’t it? Anyway, after this it was just a matter of defining serializable formats for any struct that needed it.</p><p>No new feature is complete without tests. In this case they were <em>really </em>extensive. Models are complex data structures: each model contains a single space, each space has it’s own data (ContinuousSpace even contains an instance of GridSpace), not to mention several other complexities. Every combination needed a testset, and each testset checked <em>every single saved parameter</em>. This resulted in nearly 300 new tests, which ironically is more than the lines of code they test. All these tests payed off pretty much instantly, since they revealed several bugs that took a while to fix.</p><p>Arguably one of the more underappreciated aspects of writing any open-source software is writing documentation. Writing documentation is easy. Writing <em>good </em>documentation takes thought. As someone who wrote the functionality, I’m well aware of exactly what it can and can’t do, and how it does whatever it does. The user isn’t aware of any of this, so conveying all the necessary information without going into too much detail, and doing so in a succinct, unambiguous manner takes skill. My first attempt explained most of what was necessary, but also had some unnecessary details. Some of it could be rephrased better. After several review comments on GitHub and a discussion over video call later, I managed to write good documentation.</p><p>The <a href="https://juliadynamics.github.io/Agents.jl/stable">Agents.jl docs</a> contain examples to illustrate how the library should be used. Particularly, the <a href="https://juliadynamics.github.io/Agents.jl/stable/examples/schelling/">Schelling’s segregation example</a> is used to show several general-purpose features of the library applicable to all models. We decided to add a section there for saving/loading models. The example was simple enough to write, but for some reason it refused to cooperate with the docs build. While loading back the model, JLD2 was unable to find the SchellingAgent type, and reconstructed a temporary type with the same data. This issue turned out to be isolated to documentation builds, and couldn’t be replicated otherwise. After a <em>lot</em> of local doc builds, we decided over a video call that the PR should be merged without this section of the example. Meanwhile, the section was put in a tracking issue to resolve later and an issue was filed in JLD2.jl. This turned out to be an issue relating to how Documenter.jl builds docs, and the local modules it creates for the code blocks. The fix was a single line of code to identify the temporary module that Documenter creates, and everything worked perfectly.</p><p>There was a surprising amount to learn during all of this, from little things such as the fact that kwargs... is an iterator over NamedTuple and not just a NamedTuple, to much more significant things such as how to approach designing a relatively complex system with a very simple API. I learnt how useful tests are, and also how to write and organize them efficiently. I also learnt to write good documentation, the things to avoid and what I should ask myself while writing it.</p><p>This concludes the first two weeks of the official coding period, and the first month of my GSOC contributions. It’s been a roller-coaster ride, and I don’t think I’d have it any other way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea8ade6c715" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My GSOC Journey #1: So it begins…]]></title>
            <link>https://aayush-sabharwal.medium.com/my-gsoc-journey-1-so-it-begins-8e26c8cc16df?source=rss-a51cc4832838------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e26c8cc16df</guid>
            <category><![CDATA[agent-based-modeling]]></category>
            <category><![CDATA[gsoc]]></category>
            <category><![CDATA[julialang]]></category>
            <dc:creator><![CDATA[Aayush Sabharwal]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 06:51:41 GMT</pubDate>
            <atom:updated>2021-06-15T06:51:41.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5RBYeGe0VLB6t_ZsvO_wQ.png" /></figure><p>The coding period of Google Summer of Code 2021 (GSOC) began on the 7th of June! It isn’t some sort of hard line, however. I had been writing code for almost two weeks beforehand. In a discussion with my mentors, we decided there really isn’t any point in waiting. At worst, I need the time. At best, I do more than I planned. Win-win.</p><p>I should mention, I’m contributing to <a href="https://github.com/JuliaDynamics/Agents.jl">Agents.jl</a>, an <a href="https://en.wikipedia.org/wiki/Agent-based_model">agent-based modeling</a> library written in <a href="https://julialang.org/">Julia</a>. My mentors are George Datseris (<a href="https://github.com/Datseris">Datseris</a>) and Tim DuBois (<a href="https://github.com/Libbum">Libbum</a>). My proposal is to add model serialization capability, as well as extending path-finding functionality. Model serialization basically means entire models can be saved to disk as a file, and loaded back. Pretty useful in a bunch of scenarios. Path-finding refers to enabling agents to find their way around obstacles.</p><p>In a discussion with my mentors, we decided it would be appropriate to also resolve a related issue as part of my GSOC. For this, I added the functionality to read/write agent data from/to CSV files. Agent data can be dumped to a CSV file, and CSV files containing agent data can be loaded into the model. This comes in handy for initializing models, since it’s fairly easy to generate a CSV with the required data.</p><p>The idea seemed pretty easy to implement. Then again, aren’t those famous last words? I started off by experimenting with <a href="https://github.com/JuliaData/CSV.jl/">CSV.jl</a>.</p><p>I quickly wrote up the basic functionality, and a CSV file to test it. Unsurprisingly, the first error was that CSV.jl can’t parse columns containing Tuples. CSV.jl allows specifying what type a column is, and uses Base.parseto convert it to that type. It doesn’t allow specifying any other parsing function. Since Base.parse isn’t defined for parsing Tuples, it threw an error. Being able to parse tuples would be a useful feature since, for example, agent positions are specified that way. To attempt this, I defined a new method for Base.parse (a function I don’t own) to Tuple{Int,Int} (a type I don’t own).</p><p>Some of you might already have noticed what I’ve done, and are staring with horrified expressions. I can’t describe the gravity of the situation better than George did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6b-VumfmfIq615hI6sXHQ.png" /></figure><p>I didn’t know what <a href="https://docs.julialang.org/en/v1/manual/style-guide/#Avoid-type-piracy">type piracy</a> was at the time. In short, I overloaded a function a don’t own for a type I also don’t own. Since I don’t own the type (and it’s a feature of the language), it’s highly likely (read: guaranteed) that someone using the library will use the type. It’s also highly likely someone will use the function too. Like me, they might accidentally use it on that (Tuple) type. If I didn’t define a new method, they would get the same error I did. However, with my new method, the function runs somewhere it shouldn’t, and returns a possibly erroneous output. The error could be anything from a nice error message with a stack trace, to crashing Julia. Either way, the debug process likely wouldn’t be fun.</p><p>Over a video call with George and Tim, we decided it’s better to follow the standard convention of splitting such non-scalar values over multiple columns (such as pos_1 and pos_2 for a field pos::Tuple{Int,Int}). Since the CSV files could have their columns in an arbitrary order, there needs to be a way to map each field of the agent struct to any column. To this end, the function allows specifying col_map, a dictionary that maps keyword argument to column number. Through this, the user can specify any column number for a keyword argument to the agent constructor. It’s also likely that the columns would be in the same order as the corresponding arguments to the constructor, without needing to be passed as keywords. If col_map isn’t specified, the entire row is provided as positional arguments. Another convenience is the ability to let row number correspond to the ID field of the agent, so the CSV file may not need an explicit ID column.</p><p>The final bit of flexibility happens through the magic that is metaprogramming. Wouldn’t it be annoying to have to specify types for all your columns, if they’re named the same as the fields in your struct anyway? To solve this, if the types aren’t explicitly provided the function automatically generates a mapping from field name to it’s type. This takes into account splitting tuples across multiple columns, so a field foo::Tuple{String,Int} maps foo_1 to String and foo_2 to Int. Personally, I think this is the coolest feature of the three.</p><p>The merging of this PR concluded the first two weeks of coding which, ironically enough, ended right on time for the coding period to officially begin. I’ve done a lot since then, but that deserves its own post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e26c8cc16df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Evolution through ABM]]></title>
            <link>https://aayush-sabharwal.medium.com/exploring-evolution-through-abm-b4da7531f4af?source=rss-a51cc4832838------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4da7531f4af</guid>
            <category><![CDATA[evolution]]></category>
            <category><![CDATA[julialang]]></category>
            <category><![CDATA[agent-based-modeling]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Aayush Sabharwal]]></dc:creator>
            <pubDate>Wed, 19 May 2021 16:04:05 GMT</pubDate>
            <atom:updated>2021-05-19T17:51:04.565Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all heard of Darwin’s theory of evolution. Species slowly change in their physical characteristics in response to their environment, and the modifications (mutations) that offer an edge are the ones that survive. This phenomenon goes by the name of natural selection, or survival of the fittest. Wouldn’t it be great to see this happen before our eyes? Sadly, natural evolution often takes centuries and humans don’t stick around long enough to see it happen. What we <em>can</em> do, however, is simulate this. How? Through agent-based modelling of course!</p><h4>So, what is Agent-based modelling?</h4><p>Agent-based models (ABMs) are simulations that consist of many agents, all acting based on a predefined set of rules, and are simulated in discrete steps. Each agent acts independently based on its environment including the other agents around it. This allows us to analyse the effect of individual agent behaviour on the model as a whole.</p><p>Why not just formulate this mathematically, then? Well, it’s often easier to lay down rules for how agents should behave, rather than formulate sensible relationships between an arbitrary set of variables that define our model. This becomes even more relevant when there are a relatively large number of such variables.</p><h4>Alright. How to go about making an ABM then?</h4><p>For scientific and numerical applications, I prefer to use <a href="https://julialang.org/">Julia</a>. In the words of Wikipedia:</p><blockquote>Julia is a high-level, high-performance, dynamic programming language.</blockquote><p>What this means, is that Julia is easy to write, like Python, and runs fast, unlike Python. It’s also particularly geared towards number crunching and scientific applications. Indeed, Julia has an exceedingly advanced scientific machine learning and numerical modelling framework, courtesy of the code-magicians at <a href="https://sciml.ai/">SciML</a>.</p><p>For my purposes, however, I turned to <a href="https://juliadynamics.github.io/Agents.jl/stable/">Agents.jl</a>, a pure-Julia library for agent-based modelling. It has an extensive set of features, an easy-to-use API and is exceedingly fast.</p><h4>So what does my model do?</h4><p>My model consist of bacteria acting as agents, on a two-dimensional grid. The bacteria eat food in the grid cells to survive, and reproduce through binary fission, with a random variation in their parameters.</p><p>Each bacterium has the following properties:</p><ul><li>age : How old the bacterium is.</li><li>energy : The current amount of energy a bacterium has.</li><li>sensory_radius : How far away the bacterium can spot food.</li><li>reproduction_threshold : How much energy a bacterium needs to reproduce through binary fission.</li><li>speed : How fast the bacterium can move, measured as the maximum number of steps it can take in any direction. The amount a bacterium eats in one iteration is also proportional to this parameter.</li><li>food_target : The location of the food source that a bacterium is moving toward.</li></ul><p>The food is a regenerating resource at each grid tile. A tile with no food is an “empty tile”, and does not regenerate food. Any cell with non-zero food is a “food tile” and regenerates its food every iteration, up to a parameterised cap. The growth of food can be thought of like a fungus. The food tiles can spread to neighbouring empty tiles, causing them to start regenerating food. The probability for this spread is proportional to the amount of food the food tile has. This is like how a fungus grows around itself. Any empty tile can also become a food tile with a small, random probability. Think of this like a fungus spreading spores far away.</p><p>The rules governing the behaviour of the bacteria are simple:</p><ul><li>If a bacterium grows too old (as determined by a global cap on lifetime), or runs out of energy, it dies.</li><li>If it has energy above its reproduction_threshold, it reproduces through binary fission. In this process, each child inherits the parent’s sensory_radius, reproduction_threshold and speed with some genetic variation. Additionally, the energy of the parent is distributed between the two children, after removing a fixed cost of reproduction.</li><li>If the bacterium is currently on a cell with some food, it will eat some food and gain energy. The amount of food it eats is proportional to its speed.</li><li>The bacterium will look for food. If it sees food, it will move toward it. Otherwise, it will move around randomly.</li><li>Each iteration, if not eating, the bacterium loses some energy proportional to its sensory radius and distance moved that iteration</li></ul><p>The expectation is that the bacteria will show random variation in their parameters over time, and the more successful combinations will survive. This would demonstrate the process of natural selection.</p><h4>What happens when the model runs?</h4><p>For the food concentrations, I used a 100 x 100 image, where each pixel corresponds to a grid tile, and the RGB value of a pixel determines the amount of food in the tile. This heatmap shows how the food is distributed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*vqRVQm7rHSFayhcLUwo6Cg.png" /><figcaption>Heatmap showing distribution of food on a 100 x 100 grid</figcaption></figure><p>There are four relatively small but concentrated spots of food, and one large area with less food per tile.</p><p>I configured the model to start with 10 identical bacteria distributed randomly on the map, and ran the simulation. The exact configuration corresponds to the config.bson config file, run using the runconfig function. Data from the simulation is constantly logged, and the following two visualisations capture a lot of what’s going on:</p><p>First, I made a video of how the food distribution changes over time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFq_yW6qJGcI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFq_yW6qJGcI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFq_yW6qJGcI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8448676d1b4d3fc047155829ab6a51dd/href">https://medium.com/media/8448676d1b4d3fc047155829ab6a51dd/href</a></iframe><p>This video shows 250 steps of a simulation that I run for 10,000 steps. The pattern continues for the rest of the duration. What’s interesting is how the bacteria finish the initial food distribution rapidly, and for the rest of the simulation it appears almost like ripples repeatedly sweeping across the grid, eating everything. The bacteria eat all the food faster than it regenerates. This is supported by the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSuS_QsF9iKGBBCLJ2wvNA.png" /><figcaption>The topmost plot is variation of population during the simulation. Below that, plots show the variation of sensory radius, reproduction threshold and speed of the bacteria with time. The line is the average value for each parameter, and around it is the standard deviation band.</figcaption></figure><p>The population spikes at first. This is due to the large amount of food available initially. Once the food is finished, the population drops steeply. After that, the population seems to oscillate, from nearly extinct to around 1000 bacteria. This corresponds to the “ripples” observed in the food distribution animation. Every time a ripple occurs, the bacteria eat a lot of food, thus reproducing more. Once the food finishes, a lot of the bacteria die due to starvation. As the number of bacteria decrease, the food demand decreases and the amount of food increases. Hence, the cycle continues.</p><p>It’s interesting to note that the average speed value is somewhat in-sync with the population. During a population boom, bacteria with higher speed survive. This can be explained by the fact that population rises when food is abundant, and bacteria are rewarded for being able to get to food faster and eat more. Once food becomes scarce, the bacteria that consume less energy roaming around looking for food are more likely to survive.</p><p>Reproduction threshold increases fairly steadily over time. This implies that over time it becomes more difficult to reproduce, but the two child bacteria have more energy to start off with. This is interesting, since it means that despite periodic and frequent “famines”, it’s still more advantageous to wait longer and eat more. This could be due to the fact that children that start with less energy also don’t survive long enough to get food. Another possibility is that the bacteria reach their threshold long before they become too old, so it’s beneficial to exploit the longer lifetime further.</p><p>Sensory radius has a less steady, yet still marked growth during the course of the simulation. A larger sensory radius allows bacteria to see food further away, at the expense of a greater energy cost each iteration. Consequently, bacteria that can see further can take more advantage of their higher speed. What’s more interesting to me, however, is that the sensory radius appears to settle at around 6 for most of the simulation, and only increases near the end. I’m yet to explain this, and would love inputs.</p><h4>My thoughts</h4><p>This model was fun to make, and even more fun to explore. I expected the population and parameters to stabilise to “ideal” values, and the oscillatory behaviour was a surprise. However, what fun is a simulation if it does what you expect it to? Analysing the graphs for this proved much more of a challenge than if they simply converged.</p><p>A great deal of thought went into figuring out how energy should be gained and expended, and I still think there’s a more appropriate alternative I haven’t yet arrived at. Additionally, I tried adding multiple species of bacteria, each of which start off with a different combination of parameters. Every time, all but one species died off within a few hundred iterations, and the other species behaved similarly to the above analysis. It would’ve been nice to see coexistence, if it’s even possible through this model.</p><p>All of the code for this simulation, including data collection and plotting, is available in <a href="https://github.com/AayushSabharwal/SimpleEvolution">this GitHub repository</a>. If anyone makes any interesting modifications, or finds a configuration that leads to interesting results, I’d love to see the results. If you have any suggestions, drop a comment below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4da7531f4af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>