<?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 Flavia M on Medium]]></title>
        <description><![CDATA[Stories by Flavia M on Medium]]></description>
        <link>https://medium.com/@flavia-m?source=rss-56799d1a98a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*karY189oNo2939EOd0wwVw.png</url>
            <title>Stories by Flavia M on Medium</title>
            <link>https://medium.com/@flavia-m?source=rss-56799d1a98a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:35:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@flavia-m/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[Analysing a Crowd in Unity]]></title>
            <link>https://medium.com/@flavia-m/analysing-a-crowd-in-unity-cf2fd9d9f2ed?source=rss-56799d1a98a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf2fd9d9f2ed</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Flavia M]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 11:35:28 GMT</pubDate>
            <atom:updated>2026-10-17T11:35:28.610Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Vector field analysis</h4><p><a href="https://medium.com/@flavia-m/simulating-a-crowd-in-unity-d79255ba3fd6">Last time</a> I wrote an algorithmic simulation for crowd movement. The agents in this simulation are an abstraction of real people moving through a real space, which is why we get an unrealistic effect: they sometimes get blocked together in a rigid structure that moves as a whole. If the user-controlled player is stuck in one of those grids, there’s nothing it can do (or learn). So, the player has to go.</p><p>What I have to do now is use the data train left by the remaining agents to identify optimal strategies for navigating a crowd.</p><h3>Prep work: Recording data from the simulation</h3><p>Probably one of the easier ways to analyse crowd flow is by interpreting plots in the shape of the boundary, showing some measure as a function of the 2d position. A vector field.</p><p>For the parameters that make up these plots, I decided to record the following for every agent <em>i</em> for every frame:</p><ul><li>position vector <em>p⁽ⁱ⁾</em></li><li>direction vector <em>d⁽ⁱ⁾</em></li><li>effective speed <em>s⁽ⁱ⁾</em></li></ul><p>If the simulation contained a single agent and no walls, <em>s⁽ⁱ⁾</em> would simply be the length of <em>d⁽ⁱ⁾</em>. But in an environment where interaction exists, the instruction to move <em>d⁽ⁱ⁾</em> is merely an instruction to <em>attempt</em> moving that way. If the agent meets some collision, or gets pushed off its course, the actual movement differs from the intended one. This discrepancy gets recorded by reserving a separate parameter <em>s⁽ⁱ⁾</em> for the actual speed.</p><p>Next up is recording and storing all this data. Directly writing to disk on every frame is too expensive for a real-time simulation, this needs to be stored in memory.</p><p>Let’s say I run simulations with a maximum of 512 agents. If I make the boundary big enough to accommodate about that many, it takes no more than 10,000 frames until the last one has exited. The parameters need the space of five floating point values (two 2-dimensional, one 1-dimensional), which is five times 4B. Putting it all together the database should need an estimated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*c_kW3IOXiXPQ2LF9GHG_6A.png" /></figure><p>of space. Very comfortable on a RAM. Once the simulation is finished, I save the numbers to a csv for later processing in Python.</p><h3>Varying the boundary</h3><p>The environment in which I built the simulation now appears too dull for meaningful analysis. Instead, I’m going to run the simulation in six distinct shapes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*ivoWFrQZBCEnkBJTWlOzoQ.png" /></figure><p>I read somewhere that a single exit can cause congestion and adding a pole right in front of it breaks up the crowd and keeps the flow intact. So this is one thing to test. Next up, I lead the crowd through an hourglass shape to explore the potential of used and unused space on the other side of the bottleneck. The Q-shaped and maze boundaries test the limit of my movement algorithm when the path to the exit isn’t straightforward. And from a flow analysis perspective, these can also give information about using empty space.</p><h3>Results</h3><p>All plots shown here are obtained by aggregating some feature or combination thereof over all frames per position.</p><h4>Density</h4><p>This measures how many agents pass each position, summed up over all the frames of the simulation. If one agent doesn’t move from one frame to the next, that gets counted as 2 instances for that position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*780CrgrKOiDvu7h7uR5W3A.png" /></figure><p>If we compare the two boundaries on the left, it seems that the pole breaks up the density around the exit ever so slightly. But, it also adds another dense area just behind the pole.</p><p>In the hourglass boundary, the highest density lies before the bottleneck. The agents spend more time right on the corners to the tunnel entrance, than around the exit. They also form two channels around the sides of the tunnel and tend to avoid the centre. When they get to the exit, they once again enter a high density area, since the flow coming from the tunnel is too wide, and they have to wait. But most of the waiting was already done at the tunnel entrance, so the exit is looser.</p><p>A similar behaviour can be observed in the Q-shaped boundary: While the area around the exit shows higher density compared to its local neighbourhood, the maximum lies to the top left of the obstacle. This is where the agents spend the most time in one spot. Their destination vector points exactly through the obstacle, so only the other targets can get them out of this position. Until those forces are strong enough, the agents are stuck.</p><p>Stuck is also the right word to describe the maze boundary. It is safe to say that most agents did not reach the exit in this scenario. Actually, the purple low-density zones delineate something like the reach of the exit influence. Once agents enter those, they get out with little difficulty. But outside of them, they’re kind of trapped.</p><h4>Speed</h4><p>Now let’s take a look at the speed <strong><em>s⁽ⁱ⁾</em></strong>, averaged over the whole simulation. The unit of measurement is a little odd, since this is the length of the actual movement vector. So, Unity’s unit size per frame. But I’m mainly interested in relative analysis anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*GnZYHN7A6ScrC9GjgXXjaA.png" /></figure><p>As expected, the highest speed in each case is reached right at the exit line, where there is no obstruction.</p><p>Compared to the density, here we can see more of a difference between the base and pole boundaries: Without the pole, the total speed in the immediate area of influence around the exit seems higher. So does this mean that the pole actually makes it worse? Not sure yet.</p><p>The hourglass speed tells a similar story as its density. There’s trouble getting in the tunnel and getting out the exit. But inside the tunnel the flow stays constant.</p><p>Same for the Q boundary, the speed looks like a mirror image of the density. Wherever there are many agents packed tightly, they move slowly. Where they have enough space around them, they pick up speed.</p><p>Now the maze, what a mess. High-ish speed near the exits but then also in some areas scattered around the plan. Still, the high density regions from above seem to be slow. And for the seemingly random high speed zones, I suppose that at the start of the simulation, the agent can move somewhat freely and only get stuck later on. So these areas get vacated at the start and then not visited again. Making the average speed, when occupancy is recorded, rather high.</p><h4>Volume</h4><p>In traffic analysis, the volume is understood as the density times speed, as per the <a href="https://austroads.gov.au/__data/assets/pdf_file/0019/392050/Module_2-2_Fundamental_Speed-Flow-Density_Relationships.pdf">continuity equation</a>. This can give us some sense for the quality of flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*wrKmxGKUUiji3VWLgimmqg.png" /></figure><p>Once again, the base and pole boundaries seem to reach similar max volumes, only in the base case the area of high volume is larger. This also suggests that the pole may be doing more harm than good.</p><p>In the case of the hourglass, we can now see a steady beam from the start of the tunnel to the boundary exit. Even though the density graph shows us some stagnation around the exit, it is not enough to seriously obstruct the flow.</p><p>The volume in the Q shape is exactly what you’d expect. Low in the North-West corner and getting better as you approach the exit. So, the density and speed graphs aren’t <em>exact</em> mirror images. Where they are, one of the factors is close to zero and the volume graph shows zero. But a clear path becomes apparent around the obstacle and grows in strength towards the exit. Makes sense that the less obstructed the agents’ path, the better the flow.</p><p>And the maze, yeah. Not much going on here. High density means low speed. High speed means low density. All in all not a lot of movement.</p><h3>What does this mean?</h3><p>First, we can assume that in this particular scenario, the pole did not help as expected. Still, you could probably play around with its size and position to find a case where it does. These two boundaries are also the most restrictive among the ones shown. Once the agents get into the dense area around the exit, there’s not much room for clever strategies.</p><p>For the hourglass shape, I made the conscious decision to have the exit narrower than the tunnel, creating two bottlenecks. The first one is clearly a bigger problem for the flow. Once the agents get past that, they stick to the sides of the tunnel. It stands to reason that using the tunnel centre means avoiding the denser areas and therefore moving quicker. But if we look at the speed graph, there is no apparent difference between the sides and the centre. The agents’ behaviour is a direct consequence of the programming but it’s by no means a <em>bad</em> choice. The secret lies in keeping that momentum once the second bottleneck is reached. If there’s backlog and this isn’t immediately possible, the density graph shows that most agents deviate to the side and try to get back in from there. But a look at the volume graph reveals that it would likely be better to stick to the original path, where the flow is stronger.</p><p>One of two destinies awaits the agents in the Q-shaped boundary: they either get to the path that leads towards the exit, or they get stuck. A simple better strategy is to detect when you haven’t moved in a while and do a random step.</p><p>Same goes for the maze, although here, the chances of reaching the exit are quite slim. A random move might get you out of a corner if you’re alone in there, but if many agents are stuck together, they would need to coordinate — which is something that this simulation wasn’t designed for.</p><h3>Conclusion</h3><p>So there we have it, the analysis for the selected boundaries. I was able to find some smarter strategies in some of the cases, but there’s a limit to what a single piece of the flow can do without a bird’s eye view. I definitely learned that navigating a flow is a tricky business, and that if there’s trouble, the root cause is most likely a poorly laid out floor plan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2fd9d9f2ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating a Crowd in Unity]]></title>
            <link>https://medium.com/@flavia-m/simulating-a-crowd-in-unity-d79255ba3fd6?source=rss-56799d1a98a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79255ba3fd6</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[collision-avoidance]]></category>
            <category><![CDATA[crowd-simulation]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Flavia M]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 11:55:37 GMT</pubDate>
            <atom:updated>2026-08-14T11:55:37.082Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: algorithmic simulation using DOTS</h4><p>This project started out as a reinforcement learning environment. I wanted to train an agent to find the optimal strategy for navigating a tightly-packed crowd, mostly because I wanted to know if there was one. You don’t spend every morning rushing through the central train station at peak times and <em>not</em> think that there must be some way to outsmart the masses.</p><p>The plan was: simulate a simple crowd environment → train an RL agent to reach its goal fast → shave aeons off my commute by not being stuck behind slow walkers!</p><p>Unfortunately I never got to the training part but more on that later.</p><h3>Step 1: Setting up</h3><p>It made sense to use Unity for the simulation since I’m moderately familiar with it and I know it can be used as an RL environment.</p><p>First, we need the setting. In its simplest form, we’re talking about a confined space with one exit. In two dimensions, we can just specify white and black pixels on a texture and transform this into a sprite. I exposed the width, height, exit size, and relative exit position as modifiable parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*taPH4Gqg4XyCVvshCFdIVg.png" /></figure><h3>Step 2: Creating the crowd</h3><p>If this is going to be an RL environment, I need two types of agents: NPCs which form a crowd and which follow a simple ish algorithm to reach the exit, and a unique player that operates on user input.</p><p>I couldn’t use simple game objects with rigid-body colliders and a movement script attached, if I wanted a framerate faster than 1 per second. Particles are fast, but there’s no way to make them collide with each other, so they were no option either.</p><p>I ended up using Unity DOTS, a fairly recent technology that requires a step away from comfy object orientation and into data-oriented design but which after a quick introduction is really easy to use and has lots of teaching material online. And best of all: it’s fast! I could specify the desired behaviour per agent and let Unity handle the simulation.</p><p>For spawning, there’s a beautiful algorithm explained <a href="https://www.youtube.com/watch?v=7WcmyxyFO7o">here</a> for randomly generating positions. I selected one of them for the player and the rest for the NPCs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*bFDgN3dHc1NIMUMxPrfuxA.png" /></figure><h3>Step 3: Animating the crowd</h3><p>This is where it got interesting. The idea was to have a straightforward, deterministic algorithm that controls the NPCs so that my smart little RL agent can learn to outmaneuver them. Of course, the concept of a mindless mass of people and only one independent thinker is far from realistic, but this little act of arrogance was a necessary abstraction given the reduced complexity of this project. To make it fair, everyone gets the same information:</p><ul><li>the position of the closest point on the exit line</li><li>positions and velocities of the neighbours within a short radius (obtained through an overlap sphere check)</li></ul><h4>if path free: move</h4><p>Naive choice. Each agent looks forward a certain distance in the direction of the exit and only moves if that space is free.</p><p>Here’s why this approach doesn’t work: The agents tend to get stuck near the sides of the exit because even if the colliders allow for partial movement in the desired direction, sometimes they just get in their own way. Not realistic behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*exlAn1Nml7GbtnMz_a5quA.gif" /></figure><p>But even before this phenomenon takes place, such a model is clearly too simple to represent realistic crowd movement. It’s missing the very important component of interaction with the other agents.</p><h4>Reynolds’ behavioural model</h4><p><a href="https://arxiv.org/abs/cond-mat/9804180">This model</a> was originally developed to describe flocks of birds or school of fish, where each individual chooses their own direction, yet the overall movement looks cohesive. Decisions are made only based on a locally observed neighbourhood, so it fits right into the constraints I set for this simulation.</p><p>For each agent, the model prescribes three goals:</p><p><strong>1.</strong> Separation: don’t collide with your neighbours</p><p><strong>2.</strong> Alignment: move at a similar speed as your neighbours</p><p><strong>3.</strong> Cohesion: stay close to your neighbours</p><p>Qualitative analysis shows that following these rules creates realistic-looking behaviours.</p><p>In the present case, we must also specify another goal:</p><p><strong>4.</strong> Destination: move towards the exit</p><p>Once the direction vector has been calculated for each goal, they are arbitrated in the following way:</p><ul><li>sort the vectors by a predefined list of priorities</li><li>weight each vector by its deviation from the mean magnitude:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*tJBUp7fMkQTnVHKozN01rw.png" /></figure><ul><li>add the weighted directions by priority to an accumulator up to a specified maximum magnitude</li></ul><p>This way of merging the different goals respects predefined priorities but can still assign sufficient weight to a large vector in an emergency. It also ensures different goals don’t cancel each other out, which a simple (weighted) sum might do.</p><p>Going through the goals, it is clear that three of the four are relatively easy to compute. For an agent <em>i</em> with position <em>p⁽ⁱ⁾</em>, velocity <em>v⁽ⁱ⁾</em>, and <em>N</em> neighbours, we get:</p><p><strong>2.</strong> Alignment: mean of neighbouring velocities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*m0uhQ0s05lLDIBdNl4CdoA.png" /></figure><p><strong>3.</strong> Cohesion: mean of neighbouring positions, weighted by squared distance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*8nlvEZqThS9EKOn4bVygRQ.png" /></figure><p><strong>4.</strong> Destination: vector to the closest point on exit line <em>(s, t)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ugchBHWtz6yo5IjkmojZQw.png" /></figure><p>(side note: I ended up scaling this vector to a minimum length to maintain its importance even close to the exit)</p><p>The one direction vector that’s not at all straightforward to find is <em>d</em>ₛₑₚₐᵣₐₜᵢₒₙ. There exist many collision avoidance strategies, each tailored to slightly different problems than this one. In Reynolds’ paper, the exact algorithm isn’t detailed so I had to make do with what I could find in the literature.</p><h4>(R)VO</h4><p>Velocity obstacle is an analytical approach to collision avoidance and works like this: define a cone starting from your position and encapsulating the obstacle plus your own radius <em>r</em> around it. Then pick the best velocity that lies outside of that cone. When using <em>reciprocal</em> VO, the cone is only half as wide, because we expect the obstacle to be employing the same strategy and dodge the other half of the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*l8IuA9xM4nOGZt1enc1lfQ.png" /></figure><p>For each obstacle <em>n</em>, we must now make sure that the direction <em>v⁽ⁱ⁾</em> of agent <em>i</em> does not lie within the cone, in other words:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*YP28RP80MJXXyHqg-mStMA.png" /></figure><p>Note that there are still infinitely many valid directions to choose from. One selection mechanism is described <a href="https://jasonfantl.com/posts/Collision-Avoidance/">here</a>: uniformly sample points around <em>p⁽ⁱ⁾</em>, give them a score, then select the direction with the highest score that lies in the permitted zone.</p><p>In the standard collision avoidance setting, say two robots driving towards each other, it makes sense to have a target direction / position. Then, you can just score the sampled directions by how well they align with that.</p><p>So should we use the exit direction as the target? I wouldn’t be too sure. Steering the agent toward the exit is already taken care of by the fourth goal. Embedding it additionally into the collision avoidance mechanism would place disproportionate importance on the destination, not to mention tightly coupling what was previously nice and loose.</p><p>Instead, let’s assume that the current direction is kind of on track, and aim to maintain it. The score for a sampled velocity <em>v</em> is then a function of the current velocity <em>v⁽ⁱ⁾</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*X0Nrm2GcplgncRPx3QGxTA.png" /></figure><p>Then we simply select the <em>v</em> with the highest score that lies outside of all VO cones.</p><p>So does this work? Unfortunately no. The velocity score introduces an improper bias towards the current direction and the agents get stuck once they stop moving. They can still be pulled out of a standstill by the influence of their moving neighbours. But as areas of stagnant agents grow larger, this becomes more and more difficult and the end of my simulation once again looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*lQLC1B-zZ2YDcrhi1-IAVA.gif" /></figure><p>Besides, this method doesn’t compute an “avoidance vector” in the intuitive sense. We want something that points in the direction of separation and whose magnitude correlates to the emergency of avoiding the obstacle.</p><h4>Fast obstacle avoidance</h4><p>After some more research I found <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=9999335">this article</a> which seems to be exactly the separation vector I was looking for! It’s easy to implement by raycasting from each agent at regular angle intervals and using this formula to compute the avoidance direction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*EwIqathFgQ3YkJPiPo0Kuw.png" /></figure><p>with hyperparameters <em>D</em> and <em>s</em> and where the <em>p⁽ⁿ⁾</em>s are all the hit points of the raycasts.</p><p>Casting multiple rays per agent is expensive and may slow down even a DOTS simulation, so instead I’m using the neighbour <em>p⁽ⁿ⁾</em>s already present in the neighbourhood sphere.</p><h3>The result</h3><p>So here we have it, the final crowd simulation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*WGkbHf5PygNfKN-t5O564Q.gif" /><figcaption>(2x speed)</figcaption></figure><p>It’s fast and it’s realistic, the agents find the exit but also follow the general flow.</p><p>Two observations:</p><ul><li>sometimes, the agents overlap with each other. This really shouldn’t happen with Unity rigid-bodies and I’ve tried a few things but can’t really get rid of it. I suppose it’s because pressure builds up from the outside in and they’ve got nowhere to go — I’ve accidentally created a crowd crush.</li><li>because the agents are all circles, they tend to form very dense structures that move as a whole and no individual movement is possible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*_EQVgG4YFnxsj4HX0rKxmA.png" /></figure><p>This makes it so there’s nothing to learn and I rather think that my RL algorithm will fail. So there goes my plan of learning the optimal strategy.</p><h3>S̶t̶e̶p̶ ̶4̶:̶ ̶T̶r̶a̶i̶n̶i̶n̶g̶</h3><p>After a short crash out, I started looking for solutions.</p><p>I could of course make the agents more varied: give them different sizes, use ovals instead of circles and make them face the movement direction. But do I really want all this added complexity? Plus it’s by no means certain that these adjustments are enough to create an environment suitable for reinforcement learning.</p><p>Instead, I’m going to skip the learning part and go straight to analysing the flow. My plan is to remove the player and visualise vector fields of average direction per position, duration until exit, etc. And then interpret them manually.</p><p>But all of this needs to first be implemented and I’ll put it in another article so .. stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79255ba3fd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>