<?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 Vikram Setty on Medium]]></title>
        <description><![CDATA[Stories by Vikram Setty on Medium]]></description>
        <link>https://medium.com/@vikramsetty169?source=rss-d56bd0023172------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3cUmoHqw2rJW1gZZUpMs_A@2x.jpeg</url>
            <title>Stories by Vikram Setty on Medium</title>
            <link>https://medium.com/@vikramsetty169?source=rss-d56bd0023172------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:15:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikramsetty169/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[Generative AI in Reinforcement Learning]]></title>
            <link>https://medium.com/@vikramsetty169/generative-ai-in-reinforcement-learning-37055946924c?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/37055946924c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 20:55:13 GMT</pubDate>
            <atom:updated>2024-10-10T21:46:00.675Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Though Generative AI (GenAI) is usually associated with fields like Natural Language Processing (NLP) and Computer Vision (CV), its relevance in Reinforcement Learning (RL) is nothing less than profound. Beyond making deep fakes or summarizing articles, GenAI has immense scope in enhancing RL through various techniques, including (but not limited to) methods like Variational Inference, Adversarial Inverse RL, and high-level prompting. This blog reviews the major ways GenAI complements RL and a couple of popular algorithms based on such ideas.</em></p><h3>Introduction</h3><p>Generative AI (GenAI) is a branch of artificial intelligence that deals with generating new content. Going beyond tasks like regression and classification, GenAI focuses on creating new data, usually following distributions close to what it&#39;s trained on. From uses like noise modeling in audio and images to ChatGPT-like applications, GenAI has completely changed the way we use AI. It has created a transition from using AI to <em>understand</em> data to using it to <em>generate</em> data.</p><p>Reinforcement Learning (RL) is a field that optimizes agents to act intelligently by taking actions that maximize the reward they receive from their environment. Model-free RL (a subset of RL that doesn’t learn how the environment is modeled) is broadly divided into two types of algorithms, Value-based (like Q-Learning and SARSA), and Policy-based (like REINFORCE, A2C, and PPO). Out of the two, policy-based methods are usually more stable and are more explicit about the agent’s policy i.e. how it should act in a given state. By using neural networks (and by extension, other deep learning architectures) as function approximators for value metrics and policies, RL can model intelligent behavior even in complex and high-dimensional environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYL4OslQzi9iul5jojogRg.png" /><figcaption>Figure 1: State-Action Loop for an Agent in an Environment in a Classical RL Setting [1]</figcaption></figure><p>So how does GenAI make sense in RL? How can we move beyond using neural networks as just a function approximator and do more? Can GenAI help model state information better? Can it help give high-level instructions to the agent? Could it output trajectories in one go instead of just a single action according to a policy? Is it possible to model the noise in the state measurement readings? All of these are valid ideas and just the surface of what GenAI can do. The next section briefly goes over some popular GenAI architectures and further sections talk in detail about some specific ways how such techniques are used in RL settings.</p><h3>A Quick Recap of Generative AI Techniques</h3><p>Generative AI has come a long way. Starting from autoencoder-based models and moving on to GANs, diffusion models, and LLMs, better-performing and more efficient architectures have replaced older ones. However, foundational algorithms never become obsolete. With that very intuition, almost all GenAI algorithms find their way into RL, and each method has a different advantage that they bring. The following subsections give a quick overview of some of the popular GenAI algorithms throughout the years, hoping to form a basis for the techniques discussed in the later sections.</p><h4><strong>1. Variational Autoencoders (VAEs)</strong></h4><p>Variational autoencoders are used in various applications, mostly in areas like representation learning where the high-dimensional input <em>(X)</em> gets encoded to the lower-dimension latent space <em>(Z)</em>. The model is usually trained to reconstruct accurate representations of a given input even when it is occluded, covered with noise, or has other defects. The output of the architecture, <em>X_hat</em> is a whole new generated data sample, making VAEs a GenAI architecture.</p><p>Variational autoencoders basically have the same structure as regular autoencoders (encoder-decoder structure) but with a slight twist. The latent space <em>(Z)</em>, i.e. the output of the encoder is represented as a distribution (of mean <em>mu</em>, and standard deviation <em>sigma</em>) instead of as a regular vector. The advantage of this representation is being able to model the latent space probabilistically, giving more meaning to the encodings. The architecture of a standard VAE is shown in Figure 2 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*6bhqN8i-ZBL0QyaSYggk_w.png" /><figcaption>Figure 2: Variational Autoencoder Architecture [2]</figcaption></figure><p>The input to the decoder is a sample from the distribution encoded in the latent space, <em>Z</em>. To make this sampling a differentiable operation, the reparameterization trick (shown in Figure 3 below) is applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*YbBJRw5-cCkSn_XPgjHx5g.png" /><figcaption>Figure 3: Reparmetrization Trick in VAEs [2]</figcaption></figure><p>The loss function for a standard VAE includes a combination of the reconstruction likelihood (to make the output converge to the input) and the KL-Divergence (to keep the latent space distribution i.e. <em>Z</em> close to a desired distribution like <em>N(0,1)</em>). The expression for the same is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*YTx0br1ZpGcliVjSbd-N0Q.png" /><figcaption>Figure 4: Loss Function in a VAE [2]</figcaption></figure><h4><strong>2. Generative Adversarial Networks (GANs)</strong></h4><p>General Adversarial Networks are a type of GenAI architecture that uses a generator-discriminator model as shown in Figure 5 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnNMO6A2OUyr1S4iG9LmkA.png" /><figcaption>Figure 5: GAN Architecture [3]</figcaption></figure><p>The generator is the network that outputs new data (the GenAI part of GANs). The rest of the network facilitates training. In the context of popular GAN applications like computer vision, the input to the generator is usually random noise and the output is a 2D image. This output, along with a real image (not a generator output) is fed to the discriminator. The discriminator output (usually a classification) has two losses, one for the generator, and one for the discriminator. The main training objective is to get the generator to fool the discriminator while simultaneously training the generator to produce better output data. To enable such training, the generator and discriminator are usually trained in different epochs. The standard minimax loss for a GAN using discriminator output <em>(x)</em> and generator output <em>(z)</em> is shown in Figure 6 below. Better and more sophisticated losses like the Wasserstein Loss have also come up in recent years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*sAPXx71rpu5apWbWBm3vtg.png" /><figcaption>Figure 6: Minimax Loss for a GAN [3]</figcaption></figure><p>Though elegant, training GANs is not stable. It&#39;s very easy for GANs to get stuck and not make any progress. Very specific conditions must be met for GANs to work well, making them a less-chosen choice as of late.</p><h4><strong>3. Diffusion Models</strong></h4><p>Diffusion models are a type of GenAI formulation that works on the basis of modeling the noise to reveal the underlying meaningful data in the input. It consists of a forward and backward diffusion process. In the context of computer vision and image generation, the forward diffusion process can be imagined as destroying an image by continuously adding noise over many timesteps. Reverse diffusion is the opposite i.e. obtaining a meaningful image from noise by subtracting noise (the same noise added in forward diffusion) over many timesteps. A visual depiction of forward and reverse diffusion is shown in Figures 7 and 8 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-NJR-BhcAeyo67Eo_QG9Q.png" /><figcaption>Figure 7: Discerete Noise Addition in Forward Diffusion [4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCLC4CdAxB-LAf-wZhRm_Q.png" /><figcaption>Figure 8: Discrete Noise Subtraction in Reverse Diffusion [4]</figcaption></figure><p>The equation shown in Figure 9 below depicts how an image at timestep <em>t</em> and the initial timestep <em>(0)</em> are related by the addition of noise. <em>alpha</em> is a timestep-varying parameter that can be modeled. It is an expression based on another parameter <em>beta</em>, called the <em>schedule</em>. The takeaway from this equation is that the entire noise between two timesteps can be modeled in one shot, i.e. noise computation does not need to be done sequentially for every timestep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*g91wIx1RGepuboxHSIi3wg.png" /><figcaption>Figure 9: Equation Describing Forward Diffusion [4]</figcaption></figure><p>Figure 10 displays the equation for a reverse diffusion step, i.e. how the noise to be removed from a later timestep to regain the image at the earlier timestep can be recovered. This expression, however, unlike forward diffusion, needs to be done sequentially and cannot be written between two random timesteps, and only between consecutive ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*GdnmlhHlzm9cv7rZVYw9tw.png" /><figcaption>Figure 10: Equation Describing Reverse Diffusion [4]</figcaption></figure><p>The role of a diffusion model is to predict the entire noise to be removed at a given timestep. This means, given an image at a particular timestep and the timestep number as the input to a diffusion model network, it would model the entire noise to be removed to get the original image started out with at the beginning of forward diffusion <em>(t=0)</em>. Such a model would be trained against the equations for reverse diffusion shown earlier. Diffusion models usually have a U-Net type of architecture and sometimes use ResNet/Self-Attention blocks within it. They also use sinusoidal and text embeddings to encode timestep and other possible text prompt information (based on the specific application it is being used in).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ccTkwYZtklhYy3QBhR9KA.png" /><figcaption>Figure 11: Using a U-Net type of Architecture to Model a Single Step of Reverse Diffusion [4]</figcaption></figure><h4><strong>4. Large Language Models (LLMs)</strong></h4><p>A large language model is a transformer-based NLP model, with billions of parameters, trained on immense data, capable of modeling language with great performance. Beyond tasks like sentiment analysis or language translation, LLMs are great at generative tasks like document summarization and even more complex problems like solving math problems or programming, and in general, tasks involving logical reasoning. The building block of an LLM is the transformer architecture, which is shown below in Figure 12. The transformer is a parallelizable encoder-decoder model based on multi-head attention, used to model long-term dependencies in sequences, used in a variety of tasks, especially in natural language processing (NLP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*73XXiLilnzQwVg_-FX09mg.png" /><figcaption>Figure 12: Original Encoder-Decoder Transformer Block Architecture [5]</figcaption></figure><h3>How Does GenAI Make Sense in Robotics, RL, and Decision Making?</h3><p>In the previous section, the context in which each GenAI model was introduced may have given the impression that each technique is specific to a certain task. for example, VAEs, GANs, and Diffusion Models to Computer Vision, and LLMs to NLP. Though this may be a reflection of the biggest application of each model, it doesn&#39;t at all imply that they are not well-suited to be used in other fields. Each of these models has a great scope in robotics, particularly for policy optimization in reinforcement learning. Policy optimization refers to improving the quality of actions an agent takes when present in a particular state, in an attempt to maximize future returns. A high-level overview of how GenAI can be used to enhance reinforcement learning and robot decision-making is described below.</p><ol><li><strong>Enhancing Model-based RL</strong>: In model-based RL, which involves learning how the environment/world is modeled, GenAI can be used to assist the policy by predicting/generating the next possible state, given a certain action taken in the current state.</li><li><strong>Data Augmentation and Better Exploration</strong>: Lots of generative models, like VAEs, GANs, and Diffusion Models, that generate data from latent space/noise, can be tuned or used specifically to generate states that would normally be less common during regular episode rollouts. For example, by smartly manipulating the latent space vector or input noise, particular states of interest to explore can be generated on demand.</li><li><strong>Handling Partial Observability</strong>: In some scenarios where only partial observability is possible, GenAI models can help by reconstructing predictions for the entire state (similar to image impainting), leading to more robust policy training and optimization.</li></ol><p>The following sections go over a few key methods that use each of the earlier discussed architectures (VAEs, GANs, Diffusion Models, and LLMs) in the context of reinforcement learning.</p><h3>VAEs in RL</h3><p>The main advantage of using VAEs in RL can be closely linked to representation learning, i.e. learning good representations of high-dimensional states. With the latent space in VAEs being a great way to model representations/encodings, they offer a great way to learn policies directly from more efficient representations instead of larger data sources like entire images. In general, even if directly using a variational autoencoder isn&#39;t desired, it is still worth exploring using variational inference. Variational inference refers to the technique of approximating complex probabilistic distributions. Using VAE latent states to model environment state representations is one way of using variational inference in RL but not the only way.</p><p>In the paper <em>World Models</em> by Ha et al. [6], the use of VAEs, similar to what was discussed above can be seen. The authors use an agent model comprising three main components, a vision model to encode images to a latent space using a VAE, a memory RNN to account for historical observations, and a controller to implement the agent’s policy. In this, the vision model is pre-trained using random rollouts of the environment to learn good latent space representations. The high-level overview of this model is shown in Figure 13 below. This paper was one of the foundations for using learned representations in RL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*y4ZeHOI9T1JJJe61CWpdAQ.png" /><figcaption>Figure 13: Model Architecture in World Models [6]</figcaption></figure><p>A similar variational inference paradigm is introduced in the paper <em>Latent Space Policies for Hierarchical Reinforcement Learning</em> by Haarnoja et. al [7]. In this paper, an application of variational inference by learning latent space representations for hierarchical reinforcement learning models is discussed. Hierarchical Reinforcement Learning is an RL approach that uses multiple layers of policies, in which each layer focuses on a different aspect of the overall policy. For example, in an RL agent aimed at planning trajectories, one layer may predict high-level actions like where to go, whereas another layer may predict lower-level actions like velocity and acceleration. In such a hierarchical formulation, the authors propose that each policy layer maps states <em>(s)</em> and latent variables <em>(h)</em> through layers by using an invertible transformation, with an aim to effectively treat each layer as a separate agent. The authors subsequently observe better use of the hierarchical structure as higher levels can more easily control the lower layers using the latent spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*cOi8j9lQ7_4T2P-bJPBbHw.png" /><figcaption>Figure 14: Hierarchical Policy that Shares States Latent Vectors Between Levels [7]</figcaption></figure><p>Apart from these two papers, there are many more popular methods that try to make use of latent spaces, with or without VAEs. Variational inference using VAEs is very well-studied and also frequently used to deal with partially observable states as described earlier. Another variation of VAEs, called Conditional Variational Autoencoders (CVAEs) is also popularly used in the context of reinforcement learning.</p><h3>GANs in RL</h3><p>One of the biggest breakthroughs for GANs in reinforcement learning was actually in imitation learning, a branch of RL where the agent learns to mimic expert behavior. The famous papers, <em>General Adversarial Imitation Learning (GAIL)</em> by Ho et al. [8] and <em>Learning Robust Rewards with Adversarial Inverse Reinforcement Learning</em> by Fu et al. [9] use a GAN-like architecture to perform imitation learning. It’s actually interesting to also draw parallels between components of the GAN and an actor-critic RL method. The generator part of GAN acts like the actor and produces the policy. The discriminator, on the other hand, acts like a critic, i.e. it learns to distinguish an expert policy from the one produced by the generator. Overall, this method works well but suffers training stability problems just like other GANs used in different applications.</p><p>Sometimes, the formulation of RL algorithms isn’t exactly a GAN, but on looking closely, is very similar. One such method is illustrated in the paper <em>Diversity is All You Need: Learning Skills without a Reward Function (DIAYN) </em>by Eysenbach et al. [10]. The main crux of DIAYN is shown in Figure 15 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Y0UlppHI657RMUZutq8fig.png" /><figcaption>Figure 15: DIAYN Algorithm [10]</figcaption></figure><p>In DIAYN, the agent is focused on learning useful skills without the help of a reward function. Instead, the agent tries to learn a diversity of skills through exploration. By representing skills as maximum entropy policies, the authors propose that by maximizing the discriminability of skills, the agent will inherently learn useful behaviors, all without the use of reward functions. Though there is no generator and the discriminator is also not distinguishing an agent’s choice from that of an expert, it is interesting to note how this formulation parallels a similar idea of sampling and discriminating in a sequence, similar to that of a GAN.</p><h3>Diffusion Models in RL</h3><p>Like other generative models, diffusion models too intertwine into RL algorithms with objectives like generating future trajectories and policies, representing action distributions, and augmenting datasets with synthetic data. Diffusion models are also great for aggregating different skills and implementing constraints based on the task.</p><p>One interesting work in the intersection of diffusion models and reinforcement learning is the work done in the paper <em>Planning with Diffusion for Flexible Behavior Synthesis</em> by Janner et al. [11]. In this work, the authors identify <em>Diffuser</em>, a model that primarily uses diffusion models in sequential decision-making tasks, particularly in offline RL. They emphasize its approach of fitting a diffusion model for trajectory generation and using guided sampling to plan desired trajectories. Figure 16, shown below, shows how <em>Diffuser</em> samples plans by iteratively denoising two-dimensional arrays consisting of a variable number of state-action pairs, in an attempt for the optimal guide function <em>(J)</em> to bias the planning to optimize a test-time objective or satisfy a set of conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*g0LXqawLUVtRx7_C9A9j0A.png" /><figcaption>Figure 16: The Optimal Guide Function Biasing Planning in Diffuser [11]</figcaption></figure><p>Another paper by Wang et al. [12] introduces the idea of Diffusion Q-Learning (Diffusion-QL). The authors describe how integrating a diffusion policy with the Q-Learning framework allowed them to model complex, multi-modal behavior policies, and address the limitations of conventional Gaussian policies in offline RL. The way Diffusion-QL is shown in more detail in the pseudocode for the algorithm is displayed in Figure 17 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*BH4j-F2Np0M8AEDu6yEvCA.png" /><figcaption>Figure 17: Pseudocode for Diffusion Q-Learning [12]</figcaption></figure><p>In order to address the problems with distribution shifts in office RL, Ajay et al. [13] present a formulation using conditional diffusion models to mitigate their effect. They do so by generating state sequences (as shown in Figure 18 below) with a diffusion model. They then employ inverse dynamics to derive executable actions and observe better performance and generalization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*2N-35Y9gUxznqdP9DROw9w.png" /><figcaption>Figure 18: Planning with a Decision Diffuser [13]</figcaption></figure><p>The survey paper, <em>Diffusion Models for Reinforcement Learning: A Survey</em> by Zhu et al. [14] is a great resource to dive deep into a lot more applications and research done in the intersection of diffusion models and reinforcement learning.</p><h3>LLMs in RL</h3><p>LLMs complement RL algorithms in ways a little different from the other GenAI algorithms talked about in the previous sections. Instead of directly interacting with the agent or policy, LLMs are usually used as a layer of abstraction to interact with the RL model using natural language. This can be done in several ways. Some well-explored ideas include the following.</p><ol><li><strong>Learning Policies in the Language Space</strong>: By learning policies that are language instructions like “Drive to the end of the road,” “Wait till the signal turns green,” or maybe “Move randomly till you notice a blue line,” the policy can be executed through regular low-level planners. Such learning becomes easier to visualize and allows for humans to understand the policy using language too.</li><li><strong>Reward Shaping and Feedback via Natural Language</strong>: Sometimes, when the reward function is hard to design, or not working well, using natural language feedback can be a great option. By letting an LLM give feedback, the manual reward function design gets simplified. Feedback like “Nice work,” “If only you went past the finish line,” or “That was a close call” not only provides objective information for rewards but also policy feedback, allowing for greater policy optimization in general.</li><li><strong>Transfer Learning through Language</strong>: By using an LLM fine-tuned to perform well using natural language on one particular task, it is quite simple to use the same model for a similar task and fine-tune/modify accordingly. Since the abstraction of the LLM is very clear, they provide a great way to transfer and share knowledge between various problems and tasks.</li><li><strong>Meta-RL: Language as a Meta-Controller</strong>: LLMs can also be used to change the policy of the model on demand via language instructions. For example, an LLM can provide instructions/feedback like “For the next five miles, don’t go too fast,” “Drive so we get the best view of the ocean,” or “Be more cautious while turning.” Such instructions can directly change the reward structure, policy, and exploration strategy.</li></ol><p>Working in the intersection of LLMs and reinforcement learning for robotics and path planning is one of the most researched fields right now. There is immense scope for mimicking human approaches to planning and the progress made in that direction every year is mind-blowing!</p><h3>Other GenAI Applications in RL</h3><p>Beyond the ideas and techniques listed in the previous sections, there are obviously a lot of other ways to use VAEs, GANs, Diffusion Models, and LLMs for reinforcement learning problems. Having been an active area of research for quite a few years now, various methods targeting almost every different type of approach have been experimented with. There’s a lot that goes on using even the other generative models not discussed here, like autoregressive models, flow-based models, and energy-based models. Even much older techniques like RNNs, LSTMs, and basic transformers show great scope in being applied to robot decision-making. There are a plethora of research papers, conference workshops, blogs, and videos that go over all these different ideas and I encourage you to take a deeper look!</p><h3>How can we do Better?</h3><p>GenAI models in RL settings bring both the advantages and disadvantages they have to offer. While the previous sections talked extensively about how certain GenAI formulations can solve specific problems that RL algorithms face, this section sheds some light on the common problems across all types of GenAI-RL formulations that need to be worked on in order to bridge important gaps. These also include some areas of active research. Some of these ideas include the following.</p><ol><li>Improving the quality of the generated samples is frequently an issue faced in GenAI-based RL. Problems like training instability, lack of data, and poor convergence often cause problems for the models to generate good samples.</li><li>GenAI models also sometimes fail to scale and generate quality, high-dimensional data samples. Though this an extension of the previous point, this sheds light on the additional complexity of dealing with high-dimensional action spaces that reinforcement learning problems often go hand-in-hand with.</li><li>Another major problem, especially when dealing with LLM/transformer-based prompting, is the inability to properly understand natural language instructions. Though the LLM may give high-quality instructions/prompts, RL models usually don’t understand/process the instruction from text to policy as well as expected.</li><li>The other age-old problem in reinforcement learning, i.e. balancing exploration and exploitation comes up again and again in GenAI-related settings too. Though some methods (especially in fields like variational inference) are implemented with the very purpose of bridging this issue, it is often hard to completely cover the possible and meaningful part of the state-action space distribution.</li></ol><h3>Summary</h3><p>The power of using generative models in reinforcement learning settings is limitless. From representation learning to natural language prompting, GenAI is changing the way RL is formulated. As we move to more realistic robotic settings where the key idea to improve performance is taking inspiration from human behavior, GenAI-based approaches are racing ahead. The next couple of years will be amazing and I can’t wait to see how these models and algorithms evolve.</p><p>This blog started out by summarizing the main idea behind major generative AI techniques and later showed a couple of examples of how such architectures are used in RL settings to tackle and overcome specific problems. By wrapping up by discussing the challenges that lie ahead in the field, I encourage you to explore more about GenAI in RL, and hope you get involved in your own research if you find it interesting!</p><h3>References</h3><p>The sources for various references (research papers cited, articles quoted, and images used) include the following.</p><ol><li><a href="https://towardsdatascience.com/reinforcement-learning-101-e24b50e1d292">https://towardsdatascience.com/reinforcement-learning-101-e24b50e1d292</a></li><li><a href="https://www.jeremyjordan.me/variational-autoencoders/">https://www.jeremyjordan.me/variational-autoencoders/</a></li><li><a href="https://developers.google.com/machine-learning/gan">https://developers.google.com/machine-learning/gan</a></li><li><a href="https://erdem.pl/2023/11/step-by-step-visual-introduction-to-diffusion-models">https://erdem.pl/2023/11/step-by-step-visual-introduction-to-diffusion-models</a></li><li><a href="https://arxiv.org/pdf/1706.03762">https://arxiv.org/pdf/1706.03762</a></li><li><a href="https://arxiv.org/pdf/1803.10122">https://arxiv.org/pdf/1803.10122</a></li><li><a href="https://arxiv.org/pdf/1804.02808">https://arxiv.org/pdf/1804.02808</a></li><li><a href="https://arxiv.org/pdf/1606.03476">https://arxiv.org/pdf/1606.03476</a></li><li><a href="https://arxiv.org/pdf/1710.11248">https://arxiv.org/pdf/1710.11248</a></li><li><a href="https://arxiv.org/abs/1802.06070">https://arxiv.org/abs/1802.06070</a></li><li><a href="https://proceedings.mlr.press/v162/janner22a/janner22a.pdf">https://proceedings.mlr.press/v162/janner22a/janner22a.pdf</a></li><li><a href="https://arxiv.org/pdf/2208.06193">https://arxiv.org/pdf/2208.06193</a></li><li><a href="https://arxiv.org/pdf/2211.15657">https://arxiv.org/pdf/2211.15657</a></li><li><a href="https://arxiv.org/pdf/2311.01223">https://arxiv.org/pdf/2311.01223</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37055946924c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Cameras - Everything you need to know]]></title>
            <link>https://medium.com/@vikramsetty169/event-cameras-everything-you-need-to-know-c5dd4281eb9b?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5dd4281eb9b</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[perception]]></category>
            <category><![CDATA[event-camera]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 22:15:49 GMT</pubDate>
            <atom:updated>2024-09-25T22:15:49.428Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Event cameras are quickly becoming an integral part of most vision systems. From usage in self-driving cars to smartphones and even security systems, event cameras, either standalone or in complement with regular cameras are a vital part of addressing the gaps that regular vision systems fall short of. This article aims to provide a comprehensive guide to understanding and using event cameras for classical vision tasks.</em></p><h3>Introduction</h3><p>The strength of robust systems/applications has always been the versatility of using different types of data. In the context of vision and perception, cameras have always been the primary sensor used to collect data. Various time-of-flight (ToF) sensors like ultrasound, infrared, and lidar sensors are also used depending on the application along with the hardware and compute resources available.</p><p>Though using these sensors can prove effective, sometimes the best way to reach human-level performance on tasks like driving is to emulate the way humans perceive and process their surroundings. For vision tasks, this can be done by using bio-inspired sensors that mimic the working of the eye. This is one of the biggest motivations for using event cameras, also called event-based vision sensors (EVS). The power of using neuromorphic, low-latency, high dynamic range, and pixel-asynchronous sensors is immense. The following sections go over the foundations and theory behind event cameras, and then deep-dive into processing and using event camera data for interesting applications.</p><h3>What are Event Cameras?</h3><p>As mentioned in the previous section, an event camera is a bio-inspired sensor with a neuromorphic design that mimics the working of a human eye. At this point, the biggest question most people have is “Doesn’t a regular camera emulate the human eye?” The simple answer to this is “Only partially.”</p><p>A regular camera’s basic working principle is capturing the intensity of the light falling on the image sensor. The intensity of all the pixels of the sensor is measured near-simultaneously and the data produced is an image frame i.e. a set of intensity values measured by all the pixels of the image sensor at the same time. This implies that the pixels of a regular camera’s image sensor are synchronous, i.e. they produce an output at specific times together. The latency of measuring these intensity values is usually in the order of milliseconds, with most high-quality commercial cameras operating at a maximum of around 120 fps. In contrast, event cameras, instead of measuring the absolute intensity of the light falling on the image sensor, record the change in intensity (if it happens) of the light captured on a pixel (as binary measurements, +1 or -1 for a positive or negative change respectively). Further, each pixel in an event camera is asynchronous and independent, i.e. they don’t all fire at the same time. Each pixel records a change in intensity as and when it occurs. The latency is a lot lower too, with pixels being able to record intensity changes with times in the order of microseconds, making it almost continuous in time. In essence, if a regular camera outputs a frame of pixel intensities (F) at a specific timestamp (t), represented by {t,F}, an event camera outputs a stream of data {t,x,y,p} with t being the timestamp, x, and y describing the location/coordinate of the pixel on the sensor, and p showing the polarity, i.e. whether the change in intensity was positive or negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*7U8G15lbNxnqg0-H2iFP1w.jpeg" /><figcaption>Data Recorded by an Event Camera Against that of a Regular Camera [2]</figcaption></figure><p>The picture above shows the difference in the way data is collected in a regular (frames) and event camera (stream). Usually, blue denotes a positive change in polarity, and red denotes a negative change in polarity. Another notable feature of event cameras is that they have a high dynamic range (HDR). In a regular camera, if the sensor records extremely high and low intensities (bright and dark areas) in the same image, the image overall gets very low visibility. This is illustrated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*a_N_OiF-ATtm0WWtmZxncg.png" /><figcaption>Image Captured by a Low Dynamic Range (LDR) Camera vs a High Dynamic Range (HDR) Camera [5]</figcaption></figure><p>High-dynamic range cameras are usually expensive and still aren’t that good. Event cameras, however, are a cheap alternative to recording the change in intensity values even at extreme dynamic ranges. This means event cameras can usually capture intensity changes even in extremely dim and bright conditions, whereas most regular cameras fail from underexposure or overexposure. This makes EVS cameras great for security and ADAS systems, especially during the night when normal cameras wouldn’t be able to capture much. Event cameras also don&#39;t suffer from motion blur, unlike rolling shutter cameras in fast-moving scenes. Since each pixel in an EVS is asynchronous, there is no delay in recording information, and thus there is no motion blur.</p><p>Visually, an event camera doesn’t look too different from a regular camera. A popular event camera, DAVIS is shown below. Prophesee [6] is another company leading the race in event camera innovation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*Uc-jVT8h_eSYdjCJ2WEeHA.jpeg" /><figcaption>DAVIS Event Camera by IniLabs [3], [4]</figcaption></figure><p>A simplified circuit diagram of the DAVIS pixel (DVS pixel in red, APS pixel in blue) is shown on the left-hand side of the image below. Similarly, a schematic of the operation of a DVS pixel, converting light into events is shown on the right-hand side. I encourage you to go through the survey paper by Gallego et. al. [1] for more information about the electronic and hardware aspect of event cameras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*3dhBzhro7tlSV6qelCJBNQ.png" /><figcaption>DAVIS Pixel’s Circuit Diagram (left) and its Operation (right) [1]</figcaption></figure><p>Equations 1–3, as shown below, show the basic data interpretation of event camera output. Considering light of Intensity <em>I</em> to fall on a pixel of location <em>x_k</em> of the sensor at time <em>t_k</em>, <em>L(x_k,t_k)</em> represents the logarithmic intensity, i.e. <em>log(I)</em>. If the difference in this logarithmic intensity at time <em>t_k</em> changes by or more than the temporal constant threshold, <em>C</em>, an event is triggered for the pixel <em>x_k</em>. If a positive change in intensity is noted a positive polarity <em>p_k</em> is recorded, and a negative polarity in the opposite case. Thus <em>p_k</em> takes only either +1 or -1 as possible values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*6ERfLEOXiSQajphaEWboIA.png" /><figcaption>Equation 1: Logarithmic Representation of Light Intensity</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*laT9KcuE06MGxj4I4jUYwQ.png" /><figcaption>Equation 2: Difference in Logarithmic Intensity Measured for a Single Pixel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*vlEzTUkFsd_GMPrqPpDt2A.png" /><figcaption>Equation 3: Representing Difference of Logarithmic Intensity as a Fixed Quanta</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*MIOrfvL029c-TJJ_4JZm5Q.png" /><figcaption>Equation 4: Associating Events to when there is a Significant Temporal Derivative of Brightness</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*HWrQz0Jc9Ra3YtCiwXeRkQ.png" /><figcaption>Equation 5: Representing Events as Triggers of Moving Edges of a Regular Image</figcaption></figure><p>Equations 4 and 5 show different approximations that can be used to intuitively understand what events represent. Equation 4 shows that by using Taylor’s Expansion in Equation 3 for a very small <em>del_t</em> (considering latency in the order of microseconds), events can be approximated to be the trigger when there is a big temporal change in brightness/light intensity. It is important to remember, however, that events are measured by the absolute difference in brightness, not its derivative. Equation 5 shows how by assuming constant illumination and linearizing Equation 3, an event can be approximated as the brightness gradient multiplied by the velocity on the image plane. The significance of these intuitions is better understood in the following sections when events are represented in different forms and used in various applications. I encourage you to refer to the survey paper by Gallego et. al. [1] for more details about these equations.</p><p>To summarize, the major differences between event (EVS) cameras and regular (CIS) cameras are tabulated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8W8BS45kdv7vpc3w3vMc-A.png" /><figcaption>Major Differences Between EVS and CIS Cameras</figcaption></figure><h3>Where can we get Event Camera Data?</h3><p>Though the best way to use event camera data would be to purchase a real event camera and get hands-on experience, it&#39;s fairly easy to download EVS datasets available online and work with them. The Robotics and Perception Group (RPG) at ETH Zurich has been involved in extensive event camera research for a long time and they frequently upload publicly available datasets to their webpage linked below.</p><p><a href="https://rpg.ifi.uzh.ch/davis_data.html">The Event Camera Dataset and Simulator</a></p><p>These datasets are a great resource to get your hands dirty and play around with EVS data. Some of these datasets are also standard for testing and benchmarking new techniques/algorithms in academia and the industry. Most of the datasets on the page include both event and regular camera data, having the same resolution (<em>h*w</em>). One thing to keep in mind is that event cameras usually have a low resolution, with most RPG datasets on the webpage, collected from the DAVIS Camera having a resolution of (180,240). When a regular camera complements an event camera, it too usually has the same low resolution, though it could be different based on the hardware setup and use case. While events get triggered almost continuously, the normal camera produces frames at its regular frame rate.</p><p>To access an RPG EVS dataset, download a <em>Text (zip)</em> file from the dataset name of your choice. When unzipping the directory, you should see the files and directories listed below.</p><ol><li><em>events.txt</em>: A text file representing the stream of events sorted in ascending order by time. Each line contains <em>{t,x,y,p}</em> in a space-separated fashion. It is important to note that <em>p</em> takes values of <em>{1,0}</em>, and not <em>{1,-1}</em> in the notation used by RPG.</li><li><em>images.txt</em>: A text file containing the CIS image frame timestamps and paths, again space separated and sorted line-wise in ascending order of timestamp.</li><li><em>images/</em>: The directory of CIS images, each with paths specified as per <em>images.txt</em>.</li><li><em>calib.txt</em>: Calibration data of the EVS and CIS camera, in a <em>[fx fy cx cy k1 k2 p1 p2 k3]</em> space-separated format.</li></ol><p>Other files like <em>groundtruth.txt</em> and <em>imu.txt</em> are usually present in the datasets as well, and more information about these files can be found on the RPG webpage [7].</p><p>One of these datasets on the webpage, <em>slider_depth</em>, is a particularly famous dataset. It involves an event camera moving linearly and at a constant speed in a low-lit room. Due to being low-lit, the images from the camera are mostly dark, but events get triggered nonetheless. A sample frame from the dataset is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*9FSeH-TARZYzEKggJxoHaw.png" /><figcaption>A (180,240) CIS Image Frame RPG’s Slider Depth Dataset [7]</figcaption></figure><p>After downloading and unzipping the slider_depth dataset folder, the class structure below can be used to process the EVS and CIS data.</p><pre># Importing the Required Libraries<br>import numpy as np<br>import cv2<br>import bisect<br>import matplotlib.pyplot as plt<br><br><br># A Class to Represent a Stream of Events (t_i, x_i, y_i, p_i)<br>class Events():<br><br>    def __init__(self,events_file):<br>        self.t, self.x, self.y, self.p = self.extract_event_data(events_file)<br><br>    # Extracting the event data from the txt file provided<br>    def extract_event_data(self,events_file):<br>        t, x, y, p = [], [], [], []<br>        fileio = open(events_file,&#39;r&#39;)<br>        for line in fileio:<br>            words = line.split(&quot; &quot;)<br>            t.append(float(words[0]))<br>            x.append(int(words[1]))<br>            y.append(int(words[2]))<br>            p.append(int(words[3]))<br>        fileio.close()<br>        return t, x, y, p<br><br><br># A Class to Represent Image Data (t_i, F_i)<br>class Images():<br><br>    def __init__(self,images_file):<br>        self.t, self.frames_path, self.frames = self.extract_image_data(images_file)<br><br>    # Extracting the image data from the txt file provided<br>    def extract_image_data(self,images_file):<br>        t, frames_path, frames = [], [], []<br>        fileio = open(images_file,&#39;r&#39;)<br>        for line in fileio:<br>            words = line.split(&quot; &quot;)<br>            t.append(float(words[0]))<br>            frames_path.append(words[1])<br>            frames.append(None) # Use frames.append(cv2.imread(words[2],cv2.IMREAD_GRAYSCALE)) to save the frame instead<br>        fileio.close()<br>        return t, frames_path, frames<br><br><br># A Class for Dealing with Event and Image Data Together (they share a common timeline - t)<br>class EVSandCISDataset():<br><br>    def __init__(self,events_file,images_file):<br>        self.events = Events(events_file)<br>        self.images = Images(images_file)<br>        self.h = max(self.events.x) + 1<br>        self.w = max(self.events.y) + 1</pre><p>The RPG datasets and the format they come in are just one of many ways in which event data can be stored and presented. There are many other datasets in various other formats online. I encourage you to explore other representations yourself. Some popular data encoding methods include using <em>H5 files</em> and <em>rosbags</em> (if using a ROS package to process the data). Another great place you can look for EVS data online is Tonic [19], which I’ve linked below.</p><p><a href="https://tonic.readthedocs.io/en/latest/">Getting started</a></p><h3>How can we Process Event Camera Data?</h3><p>Events, unlike images, aren’t ready to be input to computer vision algorithms directly. The code provided in the previous section reads the data from the file into Python Lists, but it still really can’t be used anywhere. An initial amount of processing is required to truly make sense of the data the events represent. The following representations are some of the popular ways of making sense of event data.</p><h4>1. Raw Events in Spatio-Temporal Coordinates</h4><p>One of the easiest ways to represent and visualize events is using spatio-temporal coordinates, i.e. the x and y coordinate of the pixel along one axis each, and time along the third axis. By using a scatter plot for all the events color-coded by polarity, it is the most basic representation of event data. The image below [20] shows a sample 3D plotted spatio-temporal coordinate representation for an event camera dataset in a fixed time interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIxOyOar5GAQYpUzBh19vg.png" /><figcaption>Events Represented as Spatio-Temporal Coordinates in a 3D Grid [20]</figcaption></figure><p>Though easy to visualize and use, this representation doesn’t provide the best information, neither visually, nor in an abstract way. It is a great way to see the amount of events getting generated and where they are triggered, but it can&#39;t be used directly for computer vision tasks like deblurring, interpolation, and depth mapping.</p><h4>2. Event Frames/Images</h4><p>One intuitive way of representing events is just adding the polarities of all the events triggered for each pixel in a given time interval. That is precisely what an event frame/event image is. Since events are usually triggered around the edges of the corresponding CIS images (since those are areas of high-intensity change during movement) [refer to the equations in the previous section], a sparse edge map-type image is obtained by accumulating all the events in a slice of time. This representation is also called an event histogram. The following code block can be used (in extension to the event processing code, inside the <em>EventandCISDataset()</em> class) to create an event image.</p><pre># Creating an Event Image representation of a fixed time interval<br>    def make_event_image(self,start_time,end_time):<br>        if start_time &lt; self.events.t[0] or end_time &gt; self.events.t[-1]:<br>            print(&quot;Invalid Start/End Time Provided&quot;)<br>            return None<br>        event_img = np.zeros((self.w,self.h))<br>        idx = bisect.bisect_right(self.events.t,start_time)<br>        while self.events.t[idx] &lt;= end_time:<br>            x, y, p = self.events.x[idx], self.events.y[idx], self.events.p[idx]<br>            event_img[y,x] += 2*p - 1<br>            idx += 1<br>        return event_img # event_img can also be normalized based on the requirement and application</pre><p>The event frame produced by running the above function using a <em>start_time</em>=0.01 and <em>end_time</em>=0.1 on the slider depth dataset is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O99mbguTBVpd_7t2kmMLKQ.png" /><figcaption>Event Image/Frame/Histogram for the slider_depth dataser</figcaption></figure><h4>3. Time Surfaces</h4><p>Though effective, event frames don’t take temporal information into account. They just sum up the polarities of every event encountered. Considering this limitation, time surfaces are a great way to make use of temporal information by keeping track of the most recent timestep when an event was triggered for each pixel. By then applying a function that assigns higher intensities to pixels where events happened more recently, a time surface image is constructed. The following code block can be used (also an extension to the event processing code, inside the <em>EventandCISDataset()</em> class) to create a time surface.</p><pre># Creating a Time Surface Representation of a Fixed Time Interval<br>    def make_time_surface(self,start_time,end_time,tau=50e-3):<br>        if start_time &lt; self.events.t[0] or end_time &gt; self.events.t[-1]:<br>            print(&quot;Invalid Start/End Time Provided&quot;)<br>            return None<br>        time_surface = np.zeros((self.w,self.h))<br>        idx = bisect.bisect_right(self.events.t,start_time)<br>        while self.events.t[idx] &lt;= end_time:<br>            t, x, y, p = self.events.t[idx], self.events.x[idx], self.events.y[idx], self.events.p[idx]<br>            time_surface[y,x] = (2*p-1)*np.exp(-(end_time-t)/tau)<br>            idx += 1<br>        return time_surface # time_surface can also be normalized based on the requirement and application</pre><p>The time surface produced by running the above function using a <em>start_time</em>=0.01 and <em>end_time</em>=0.1 on the slider depth dataset is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgPumxUCdOGWjH1axE4dNg.png" /><figcaption>Event Time Surface for the slider_depth dataset</figcaption></figure><h4>4. Spatio-Temporal Voxel Grids</h4><p>The main problem with event frames and time surfaces is that they lose a dimension of information through representation i.e. three-dimensional information is represented through 2D images. While event frames lose the entire temporal dimension, time surfaces lose using multiple events as they only consider the most recent one. On the other hand, using raw events in a 3D spatio-temporal grid is unintuitive to understand. A good way to take advantage of all of these methods is by using spatio-temporal voxel grids which are nothing but a discretized/voxelized 3D spatio-temporal grid. All the events corresponding to the same voxel are accumulated i.e. their polarities are added up. In essence, this representation can be imagined to be a stack of event frames, each corresponding to a narrow slice in time. The number of event frames stacked represents the temporal resolution of the voxel grid and is also called the number of <em>bins</em> the voxel grid has.</p><p>The figure below [1] shows how a raw event stream can be discretized in time into bins to create a spatio-temporal voxel grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*EMeIVLGNhqiXhY6JKJPtZQ.png" /><figcaption>Spatio-Temporal Voxel Grid [1]</figcaption></figure><p>The following code block can be used (also an extension to the event processing code, inside the <em>EventandCISDataset()</em> class) to create a spatio-temporal voxel grid.</p><pre># Creating a Voxel Grid Representation of a Fixed Time Interval<br>    def make_spatio_temporal_voxel_grid(self,start_time,end_time,num_bins=5):<br>        if start_time &lt; self.events.t[0] or end_time &gt; self.events.t[-1]:<br>            print(&quot;Invalid Start/End Time Provided&quot;)<br>            return None<br>        event_imgs = []<br>        time_slice =  (end_time-start_time)/5<br>        voxel_ts = [start_time + i*time_slice for i in range(num_bins+1)]<br>        for i in range(num_bins):<br>            event_imgs.append(self.make_event_image(voxel_ts[i],voxel_ts[i+1]))<br>        voxel_grid = np.array(event_imgs)<br>        return voxel_grid</pre><p>By combining all the data processing and representation code blocks into a single file, the following code can be referenced for playing around with the dataset (and other datasets too). Make sure to execute the code with the unzipped <em>slider_depth</em> folder as the working directory.</p><pre># Importing the Required Libraries<br>import numpy as np<br>import cv2<br>import bisect<br>import matplotlib.pyplot as plt<br><br><br># A Class to Represent a Stream of Events (t_i, x_i, y_i, p_i)<br>class Events():<br><br>    def __init__(self,events_file):<br>        self.t, self.x, self.y, self.p = self.extract_event_data(events_file)<br><br>    # Extracting the event data from the txt file provided<br>    def extract_event_data(self,events_file):<br>        t, x, y, p = [], [], [], []<br>        fileio = open(events_file,&#39;r&#39;)<br>        for line in fileio:<br>            words = line.split(&quot; &quot;)<br>            t.append(float(words[0]))<br>            x.append(int(words[1]))<br>            y.append(int(words[2]))<br>            p.append(int(words[3]))<br>        fileio.close()<br>        return t, x, y, p<br><br><br># A Class to Represent Image Data (t_i, F_i)<br>class Images():<br><br>    def __init__(self,images_file):<br>        self.t, self.frames_path, self.frames = self.extract_image_data(images_file)<br><br>    # Extracting the image data from the txt file provided<br>    def extract_image_data(self,images_file):<br>        t, frames_path, frames = [], [], []<br>        fileio = open(images_file,&#39;r&#39;)<br>        for line in fileio:<br>            words = line.split(&quot; &quot;)<br>            t.append(float(words[0]))<br>            frames_path.append(words[1])<br>            frames.append(None) # Use frames.append(cv2.imread(words[2],cv2.IMREAD_GRAYSCALE)) to save the frame instead<br>        fileio.close()<br>        return t, frames_path, frames<br><br><br># A Class for Dealing with Event and Image Data Together (they share a common timeline - t)<br>class EVSandCISDataset():<br><br>    def __init__(self,events_file,images_file):<br>        self.events = Events(events_file)<br>        self.images = Images(images_file)<br>        self.h = max(self.events.x) + 1<br>        self.w = max(self.events.y) + 1<br><br>    # Creating an Event Image representation of a fixed time interval<br>    def make_event_image(self,start_time,end_time):<br>        if start_time &lt; self.events.t[0] or end_time &gt; self.events.t[-1]:<br>            print(&quot;Invalid Start/End Time Provided&quot;)<br>            return None<br>        event_img = np.zeros((self.w,self.h))<br>        idx = bisect.bisect_right(self.events.t,start_time)<br>        while self.events.t[idx] &lt;= end_time:<br>            x, y, p = self.events.x[idx], self.events.y[idx], self.events.p[idx]<br>            event_img[y,x] += 2*p - 1<br>            idx += 1<br>        return event_img # event_img can also be normalized based on the requirement and application<br><br>    # Creating a Time Surface Representation of a Fixed Time Interval<br>    def make_time_surface(self,start_time,end_time,tau=50e-3):<br>        if start_time &lt; self.events.t[0] or end_time &gt; self.events.t[-1]:<br>            print(&quot;Invalid Start/End Time Provided&quot;)<br>            return None<br>        time_surface = np.zeros((self.w,self.h))<br>        idx = bisect.bisect_right(self.events.t,start_time)<br>        while self.events.t[idx] &lt;= end_time:<br>            t, x, y, p = self.events.t[idx], self.events.x[idx], self.events.y[idx], self.events.p[idx]<br>            time_surface[y,x] = (2*p-1)*np.exp(-(end_time-t)/tau)<br>            idx += 1<br>        return time_surface # time_surface can also be normalized based on the requirement and application<br><br>    # Creating a Voxel Grid Representation of a Fixed Time Interval<br>    def make_spatio_temporal_voxel_grid(self,start_time,end_time,num_bins=5):<br>        if start_time &lt; self.events.t[0] or end_time &gt; self.events.t[-1]:<br>            print(&quot;Invalid Start/End Time Provided&quot;)<br>            return None<br>        event_imgs = []<br>        time_slice =  (end_time-start_time)/5<br>        voxel_ts = [start_time + i*time_slice for i in range(num_bins+1)]<br>        for i in range(num_bins):<br>            event_imgs.append(self.make_event_image(voxel_ts[i],voxel_ts[i+1]))<br>        voxel_grid = np.array(event_imgs)<br>        return voxel_grid<br><br>if __name__ == &quot;__main__&quot;:<br><br>    # Make sure to include the start and end time within the limits of the actual events happening (for ease and simplicity)<br>    slider_depth_data = EVSandCISDataset(&quot;events.txt&quot;,&quot;images.txt&quot;)<br>    event_img = slider_depth_data.make_event_image(0.01,0.1)<br>    time_surface = slider_depth_data.make_time_surface(0.01,0.1)<br>    voxel_grid = slider_depth_data.make_spatio_temporal_voxel_grid(0.01,0.1)<br>    # Use plt.imshow(...,cmap=&#39;gray&#39;) to view the event image, time surface, or any bin of the voxel grid</pre><p>Though the image data wasn’t used in any of these examples, many applications can readily make use of the data formulation introduced to use EVS and CIS data together.</p><p>Apart from these representations, there are a lot of other ways to encode event camera data. Some of these techniques include Adaptive Time Surfaces, Motion-Compensated Event Images, Binary Event History Images, and Tencodes. I encourage you to read more about them. Sources like the survey paper by Gallegho et. al [1] and Larry Dong’s GitHub repository [8] are good resources to refer to for the same.</p><h3>Image Frame Interpolation using Event Cameras</h3><p>The applications of event cameras are limitless. Either standalone or used in complement with regular CIS cameras, event cameras provide great potential for advancing computer vision. They provide new formulations for improving already existing techniques, and also for innovating new ideas. Though I can’t go over all, or even their most popular applications in a single article, I’ll provide an overview of one simple, yet powerful use case, image interpolation.</p><p>Most regular CIS cameras have a very low frame rate, usually around 24 FPS. Even more advanced cameras used for specific applications suffer from motion blur and aren’t optimized to capture near-continuous visual data. With event cameras recording events almost continuously, they provide a great way to interpolate between CIS image frames. Numerous traditional and deep learning-based methods use this idea and the Complementary Filter by Cedric Scheerlinck [9] is one of the earliest, most computationally efficient, and effective methods to do this task. The basic idea behind this method (more broadly called DVS Image Reconstruction) is shown below. Please refer to the paper [9] and code [10] for more details regarding the exact algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyrH-55LU6cc_H30fmfA7A.png" /><figcaption>Image Interpolation using DVS Image Reconstruction [9]</figcaption></figure><p>In essence, this method uses a high pass filter over events and a low pass filter over image frames to provide a continuous-like image representation. By querying a particular timestep, it is possible to get the interpolated frame with precision in microseconds. This method is intuitive considering events are high-frequency (and we thus use a high pass filter over them) and image frames are low-frequency (and we thus use a low pass filter over them). Since both a high pass and low pass filter are used, the overall filter is called a complementary filter. It is also possible, however, to use just a high-pass filter over events without using image frames at all, in which case results may be slightly suboptimal, but still impressive considering we use one less source of data.</p><h3>Other Applications using Event Cameras</h3><p>Event cameras can find use in many applications beyond image frame interpolation too. From image processing techniques like deblurring to computer vision tasks like optical flow estimation and even 3D reconstruction ideas like depth mapping, NeRF, and Gaussian Splatting, event cameras can be used almost everywhere.</p><p>One popular technique that keeps on popping up in event camera-related discussions is image deblurring. The image below, referring to Cedric Scheerlinck’s work [11] shows how using a simple double integration-based method can be used to deblur images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PggW54B8Iog8s47rY71KXA.png" /><figcaption>Bringing a Blurry Frame Alive at High Frame-Rate with an Event Camera [11]</figcaption></figure><p>Optical flow estimation is still one of the biggest open problems in computer vision. While there have been methods (both traditional and deep learning-based) that work fairly well, the performance increase that comes from using an additional hardware/data source is rarely matched. EVS data has been monumental in improving optical flow estimation and one such deep-learning method by Wan et. al. [12] that makes use of event data in addition to image frames is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d53Ir13E3u6H-dK2GhbQQQ.png" /><figcaption>Learning Dense and Continuous Optical Flow from an Event Camera [12]</figcaption></figure><p>Depth mapping is one of the most basic forms of 3D reconstruction. Stereo depth mapping and monocular single-shot depth estimation are well-studied fields in computer vision and similar ideas can be extended to event camera-based systems as well. The work shown below by Nam et. al. [13] shows a deep learning framework for multi-scale depth prediction from a stereo event camera pair. Older algorithms like EMVS [14] and E2DEPTH [15], developed by the RPG Lab, ETH Zurich are also popular, revolutionary EVS-assisted depth mapping techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTJHLgqCS3aijur0tUFvEA.png" /><figcaption>Stereo Depth from Events Cameras: Concentrate and Focus on the Future [13]</figcaption></figure><p>In the fields spanning novel view synthesis and rendering, NeRF and Gaussian Splatting have made monumental strides. However, using blurry images and having training imperfections can badly affect performance. Once again, EVS data proves to be a great way to work around these problems. The figures below (in order) show a NeRF method that uses just events in a NeRF-like pipeline [16] and an EVS-assisted Gaussian Splatting method [17] that uses events to circumvent the issues of using blurry input frames. Different variations of these methods also obviously exist and are an active area of research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hG67jhSal-NDU3b2xSdQ7g.png" /><figcaption>EventNeRF: Neural Radiance Fields from a Single Colour Event Camera [16]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*nOAk46OaoWmD-XU_11wnIw.png" /><figcaption>EvaGaussians: Event Stream Assisted Gaussian Splatting from Blurry Images [17]</figcaption></figure><p>Apart from the applications covered in this section, I encourage you to go through the GitHub repository embedded below [18], where the RPG lab has compiled a list of event camera applications and resources to refer to.</p><p><a href="https://github.com/uzh-rpg/event-based_vision_resources">GitHub - uzh-rpg/event-based_vision_resources</a></p><h3>Summary</h3><p>Event cameras have been revolutionary in advancing computer vision. By being based on a principle as simple as reacting to logarithmic changes in brightness, EVS-based systems take advantage of the biologically inspired aspects of human eyes and find themselves used in various applications. Either used in complement with regular cameras, or even used just standalone, event cameras make use of various properties like low latency, HDR, and power efficiency to fuel the growing demand for performance in fields including but not limited to image processing, visual odometry, 3D reconstruction, and virtual reality. From being adopted in smartphones to self-driving cars and even medical robots, event cameras are quickly becoming an irreplaceable part of many systems and I hope this blog helped motivate you to learn more about them!</p><h3>References</h3><p>The various references used to make this article include the following.</p><ol><li><a href="https://arxiv.org/pdf/1904.08405">https://arxiv.org/pdf/1904.08405</a></li><li><a href="https://spectra.mathpix.com/article/2022.03.00339/event-camera-the-next-generation-of-visual-perception-system">https://spectra.mathpix.com/article/2022.03.00339/event-camera-the-next-generation-of-visual-perception-system</a></li><li><a href="https://rpg.ifi.uzh.ch/davis_data.html">https://rpg.ifi.uzh.ch/davis_data.html</a></li><li><a href="https://inilabs.com/">https://inilabs.com/</a></li><li><a href="https://www.researchgate.net/figure/The-HDR-image-problem-left-is-LDR-image-and-right-is-the-actual-image-2_fig3_271469195">https://www.researchgate.net/figure/The-HDR-image-problem-left-is-LDR-image-and-right-is-the-actual-image-2_fig3_271469195</a></li><li><a href="https://www.prophesee.ai/">https://www.prophesee.ai/</a></li><li><a href="https://rpg.ifi.uzh.ch/davis_data.html">https://rpg.ifi.uzh.ch/davis_data.html</a></li><li><a href="https://github.com/LarryDong/event_representation/blob/main/README.md">https://github.com/LarryDong/event_representation/blob/main/README.md</a></li><li><a href="https://www.cedricscheerlinck.com/files/2018_scheerlinck_continuous-time_intensity_estimation.pdf">https://www.cedricscheerlinck.com/files/2018_scheerlinck_continuous-time_intensity_estimation.pdf</a></li><li><a href="https://github.com/cedric-scheerlinck/jupnote_event_demo">https://github.com/cedric-scheerlinck/jupnote_event_demo</a></li><li><a href="https://www.cedricscheerlinck.com/event-deblurring">https://www.cedricscheerlinck.com/event-deblurring</a></li><li><a href="https://npucvr.github.io/DCEIFlow/">https://npucvr.github.io/DCEIFlow/</a></li><li><a href="https://openaccess.thecvf.com/content/CVPR2022/papers/Nam_Stereo_Depth_From_Events_Cameras_Concentrate_and_Focus_on_the_CVPR_2022_paper.pdf">https://openaccess.thecvf.com/content/CVPR2022/papers/Nam_Stereo_Depth_From_Events_Cameras_Concentrate_and_Focus_on_the_CVPR_2022_paper.pdf</a></li><li><a href="https://rpg.ifi.uzh.ch/docs/IJCV17_Rebecq.pdf">https://rpg.ifi.uzh.ch/docs/IJCV17_Rebecq.pdf</a></li><li><a href="https://rpg.ifi.uzh.ch/docs/3DV20_Hidalgo.pdf">https://rpg.ifi.uzh.ch/docs/3DV20_Hidalgo.pdf</a></li><li><a href="https://openaccess.thecvf.com/content/CVPR2023/papers/Rudnev_EventNeRF_Neural_Radiance_Fields_From_a_Single_Colour_Event_Camera_CVPR_2023_paper.pdf">https://openaccess.thecvf.com/content/CVPR2023/papers/Rudnev_EventNeRF_Neural_Radiance_Fields_From_a_Single_Colour_Event_Camera_CVPR_2023_paper.pdf</a></li><li><a href="https://arxiv.org/pdf/2405.20224">https://arxiv.org/pdf/2405.20224</a></li><li><a href="https://github.com/uzh-rpg/event-based_vision_resources">https://github.com/uzh-rpg/event-based_vision_resources</a></li><li><a href="https://tonic.readthedocs.io/en/latest/">https://tonic.readthedocs.io/en/latest/</a></li><li><a href="https://rpg.ifi.uzh.ch/research_dvs.html">https://rpg.ifi.uzh.ch/research_dvs.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5dd4281eb9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Complexity Analysis of Dijkstra’s Algorithm]]></title>
            <link>https://medium.com/@vikramsetty169/time-complexity-of-dijkstras-algorithm-ed4a068e1633?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed4a068e1633</guid>
            <category><![CDATA[dijkstras-algorithm]]></category>
            <category><![CDATA[dijkstra]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 21:50:30 GMT</pubDate>
            <atom:updated>2024-09-13T21:53:11.814Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Dijkstra’s Algorithm is probably one of the most well-known and widely used algorithms in computer science. After all, where </em><strong><em>wouldn’t</em></strong><em> you need to compute the shortest paths between vertices on a graph :)</em></p><p><em>However simple the algorithm itself may be, its time complexity isn’t often well understood. Most people know it to be O(E*log(V)). That isn&#39;t exactly correct, though. O(E*log(V)) may be true sometimes but it&#39;s not a given fact. It depends a lot on the underlying data structure being used in the implementation. This blog provides a deeper dive into the time complexity analysis of Dijkstra’s Algorithm and aims to provide a better understanding of the nuances of using different data structures.</em></p><h4>A Quick Recap of Dijkstra’s Algorithm</h4><p>Dijkstra’s Algorithm is a greedy algorithm used to calculate the shortest path between a vertex and all other vertices in a directed, non-negative weighted-edge directed/undirected graph. For example, the sample graph shown below is a directed graph with positive edge weights, and thus Dijkstra’s Algorithm can be used to calculate the shortest path from Vertex 1 to all other vertices. This would obviously also work with other vertices as the source and also with the graph being undirected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUr3R27ZucThSSEbeI6Qgw.png" /><figcaption>Sample Non-Negative Weighted-Edge Graph [1]</figcaption></figure><p>The block below shows the pseudocode for Disjkstra’s Algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/0*UZ7YV1-hwh7aZcsI.gif" /><figcaption>Pseudocode of Dijkstra’s Algorithm [2]</figcaption></figure><p>It involves initializing a priority queue that stores the distance (from the source) of each vertex in the graph that is still to be finalized. A finalized vertex is one whose shortest distance from the source has been locked and has no further possible path optimization. Initially, this set of finalized vertices is empty and the source vertex with 0 distance (from itself) is added to the priority queue. Iteratively, the minimum distance vertex is popped from the priority queue, and this popped vertex is finalized. After finalizing this popped vertex, the minimum distance to all neighboring vertices reachable from it is re-evaluated (considering a path through the popped vertex). This leads to possibly adding (if not in the queue) or decreasing the distance value (if already in the queue) of the neighboring vertices to the priority queue. Once the queue is empty, Dijkstra’s Algorithm has run completely and the shortest path from the source to each reachable vertex (from the source) has been computed as the set of the finalized vertices. I encourage looking at a more in-depth explanation and program implementation of Dijkstra’s Algorithm in the GeeksforGeeks article linked below.</p><p><a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/">Find Shortest Paths from Source to all Vertices using Dijkstra&#39;s Algorithm - GeeksforGeeks</a></p><p>Time complexity-wise, there are three major steps to notice in Dijkstra’s Algorithm. The first is when a new vertex is pushed/added to the priority queue. Another is when a minimum-distance vertex is popped from the priority queue, and the final one is when a vertex’s distance is decreased within the priority queue. These three operations make the basis for the overall time complexity of Dijkstra’s Algorithm.</p><h4>Time Complexity Analysis</h4><p>Considering the three major steps of Dijkstra’s Algorithm (DA) mentioned in the previous section, the overall time complexity should intuitively be a combination of the time complexity of each of them. If we assume the number of reachable vertices in the graph (from the source) to be V and the number of edges to be E, the time complexity of Dijkstra’s Algorithm can be expressed as O(V) push and pop operations on the priority queue and O(E) decrease vertex distance steps. This can be shown using the expression below.</p><pre>Time Complexity (DA) = O(V)*(push_node + pop_node) + O(E)*(decrease_node_dist)</pre><p>This formulation is intuitive considering that all V reachable nodes are pushed to and popped from the priority queue throughout the run of the algorithm. Further, for every new edge checked while finalizing the popped node, the minimum distance of the neighboring nodes can be updated/decreased in the priority queue. This reasoning is consistent with the expression provided earlier.</p><p>The only hurdle is that the time complexity for pushing, popping, and updating/decreasing a vertex in the priority queue depends on the implementation of the priority queue, more specifically the data structure used in implementing it. The major data structures commonly used in the context of Dijkstra’s Algorithm include a simple array, a binary heap, a binomial heap, and a Fibonacci Heap. All these different data structures used in priority queue implementations have varying time complexities for these operations. The time complexities for the three operations on these data structures considering a general implementation of N nodes in the priority queue are shown in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xe6Z89Z_Fzo2NGwOnZTwIA.png" /><figcaption>General Time Complexity of Priority Queue Opertions Using Different Data Structures</figcaption></figure><p>It is clearly visible that going down the table above leads to more efficient operations overall. Fibonacci Heaps, in particular, are the most efficient overall, and are well-known for their amortized O(1) decrease-key time complexity. I encourage you to read in more detail about each of these data structures to get a better reasoning behind each time complexity mentioned. In the context of Dijkstra’s Algorithm using the time complexity expression stated earlier, the analysis of each data structure can be tabulated as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Qyv0MESIzXZzD9Dlz-MtA.png" /><figcaption>Dijkstra’s Algorithm Time Complexity Ananlysis for Different Data Strcutures</figcaption></figure><p>As stated earlier, each data structure shows a different overall time complexity depending upon the time complexity of each of the three major intermediate steps. Since E can either depend linearly or quadratically on the number of vertices, depending on the graph, it is often better to leave E and V decoupled as much as possible, though further simplifications in the final time complexity expressions in the table above can be done.</p><h4>Summary</h4><p>Like many other algorithms, Dijkstra’s Algorithm too can be implemented using different data structures. The choice of data structure changes both the time and coding complexity of the algorithm. Thus, the overall time complexity of Dijkstra’s Algorithm can never be answered in a single Big-O notation. However, the most efficient implementation of Dijkstra’s Algorithm comes from using a Fibonacci Heap as the priority queue where the overall time complexity reduces to O(E + V(log(V))).</p><h4>References</h4><p>References for sources and images used in this article include the following.</p><ol><li><a href="https://blog.quantinsti.com/dijkstra-algorithm/">https://blog.quantinsti.com/dijkstra-algorithm/</a></li><li><a href="https://www.sciencedirect.com/topics/computer-science/dijkstra-algorithms">https://www.sciencedirect.com/topics/computer-science/dijkstra-algorithms</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed4a068e1633" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scene Representations in 3D Computer Vision]]></title>
            <link>https://medium.com/@vikramsetty169/scene-representations-in-3d-computer-vision-163fae591a61?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/163fae591a61</guid>
            <category><![CDATA[3d-computer-vision]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 18:45:07 GMT</pubDate>
            <atom:updated>2024-08-18T16:59:55.811Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The most common way to represent scenes in 2D Computer Vision is using images with pixels. But how do we do it in 3D computer vision? Are there multiple ways, and if so, how are they different and better/worse from one another?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*n4uKWdVBwQGlB77Y3hsTPQ.png" /><figcaption>Different 3D Representations of the same 3D Object [1]</figcaption></figure><h4>Overview</h4><p>Both 2D and 3D computer vision capture the 3D world. The only difference is that 2D computer vision methods represent 3D scenes as some form of a 2D image (grayscale, RGB, panoptic segmentation, Canny Edges, etc). This representation, though effective for understanding a scene visually, loses a dimension of information (as we’re representing a 3D scene as a 2D image). More particularly, we lose depth information, i.e. it is impossible to obtain the exact depth corresponding to each pixel in the 2D image in the actual 3D scene. This is because monocular depth is ambiguous, i.e. larger objects far away from the camera appear similar in size to smaller objects closer to the camera. This ambiguity is visually shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*8oIJ6hkN5fjGUK0c.png" /><figcaption>Depth Ambiguity of Objects in Camera Images [2]</figcaption></figure><p>To overcome this limitation, 3D computer vision, which uses 3D representations of the 3D world is a useful option. Representing a 3D scene greatly depends on how you want to interpret it. Are you looking for depth measurements, object surface shapes, or free/occupied space depictions? Further, what computational capabilities do you have to process these representations? All these questions are important to choosing the right way to encode the 3D world as readable data. In this blog, I briefly go over the core idea, intuition, basic use cases, and advantages and disadvantages of the following, most commonly used 3D scene representations.</p><ol><li>Depth Maps</li><li>Surface Normal Maps</li><li>Implicit Surfaces</li><li>Voxel Grids</li><li>Point Clouds</li><li>Triangular Meshes</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwA1qMXv2d5cDI4_aLH2-g.png" /><figcaption>Basic Visual Intuition for the Different Representation Methods [3]</figcaption></figure><h4><strong>Depth Maps</strong></h4><p>Depth maps are the simplest way to encode the depth of a 3D scene. In a depth map, each pixel coordinate of the 2D image is assigned a depth value, corresponding to the actual depth (from the camera) of what that pixel represents in the 3D world. A depth map can be a standalone single-channel 2D layer containing just depth information, or it can also be an extra layer appended to an existing RGB image, resulting in an RGBD image (with four channels in total). Sensors like Kinect directly provide depth maps as an output. Broadly, depth maps can either be sparse or dense, the former providing depth only for select/important pixels (like edges/corners), and the latter providing depth for each pixel in the image. The difference between the two can be observed in the figure below. Though never completely accurate, there are many interpolation and deep learning-based algorithms to obtain dense depth from sparse depth, an area still actively researched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ZmibBGb0jV2XAlSiGerT_g.png" /><figcaption>Sparse Depth Map of a Scene [4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*BgxqlbKJimljQ6sEpVWVjw.png" /><figcaption>Dense Depth Map of a Scene [4]</figcaption></figure><h4>Surface Normals</h4><p>Another way to represent a 3D scene is by using surface normals. Similar to depth maps, this representation also encodes information corresponding to each pixel of the 2D image. However, instead of depth information, it indicates the direction of the normal (usually in the camera’s coordinate system) of the object corresponding to each pixel in the 3D world. The direction of the normal can be represented in several ways, though using unit vectors and Euler Angles are the most popular. Surface normals typically provide a better output for visualizing a scene&#39;s shape and texture than depth maps. However, depth maps are usually preferred for having more directly usable information (as depth is usually the most sought-after output from 3D computer vision).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVwMdLHMfx7Ixr39Mxw26Q.png" /><figcaption>Predicted Surface Normal Maps for 2D RGB Images [5]</figcaption></figure><h4><strong>Voxel Grids</strong></h4><p>Voxel grids, most simply put, are 3D occupancy maps. They can be imagined to be a cuboid with a resolution of H*W*C (height, width, and channels), where each voxel can take a binary value (of 0/1) indicating occupancy (whether or not that voxel cell is occupied). In essence, they can be thought of as 2D segmentations extrapolated to three dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*njZ9qyGN89WO3WIQcVYrlA.png" /><figcaption>Possible Voxel Grid Representation of a Corresponding 2D Image [6]</figcaption></figure><p>Though a great way to capture the 3D world using three explicit dimensions, voxel grids suffer from resolution and memory issues. A finer resolution would imply more accurate and smooth representations though higher memory requirements whereas a courser representation would demand much less memory but would also be less visually appealing and more inconsistent with the ground truth. There are methods, however, to work around these trade-offs. Some of them include using oct-trees and nested layers to vary the resolution of the voxel grid as per requirement.</p><h4><strong>Implicit Surfaces</strong></h4><p>Implicit surfaces, similar to surface normals, work with the surfaces/boundaries of objects in a scene. However, instead of indicating the direction of a surface normal, they encode the probability/likeliness that a certain pixel corresponds to the boundary of an object (considering the direction of viewing). Again, this representation, like surface normals, deals less with depth, and more with shape and texture. The idea is similar to how the signed distance function (SDF) gives the Euclidean Distance to the surface/boundary. Overall, implicit surfaces for an object can be thought of as learning the explicit shape of its boundary. A better visual understanding of implicit surfaces can be seen in the images below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBu1AkdDlyQCzgUmReB24Q.png" /><figcaption>Implicit Surface Representation for an Explicit Boundary/Surface Shape[3]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*TupcmVIAwKmD9Lql7Kr5lw.png" /><figcaption>SDF-like Implicit Surface Representation of a 3D object in the Given Viewing Direction [7]</figcaption></figure><h4><strong>Point Clouds</strong></h4><p>Probably the most popular representation in the 3D computer vision community, point clouds are a low-memory solution for representing 3D scenes. In essence, they are a set of 3D points (x,y,z) representing occupancy. However, compared to voxel grids which also indicate occupancy, point clouds are adaptive. This means that the number of points being used in an area where there is an object can be varied according to the precision and accuracy required. Multiple point clouds can very well represent the same scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4Bdfd9XbdO_3FvqQMjITg.png" /><figcaption>Point Clouds Corresponding to Different 3D Objects [8]</figcaption></figure><p>An important property of point clouds is that they are unordered. This means that the order in which the points of the point cloud are specified should not matter as each point is independent from one another. The adaptive and orderless properties of point clouds manifest through slight changes in the ways point clouds are dealt with. For example, deep learning methods that operate on point clouds like PointNet and PointNet++ use multiple average and max-pooling layers to ignore any order given to the points. Further, since L2 distance cannot be used to compare two point clouds (as they may have a different number of unordered points due to the adaptive property of point clouds), Chamfer Distance is a widely used alternative.</p><h4><strong>Meshes</strong></h4><p>Meshes are likely the most widely used representation in the gaming community. This representation uses a bunch of triangles that make up the surface of the object that it represents. This includes a set of faces and vertices throughout the mesh. Like point clouds, meshes too are adaptive representations, i.e. resolution can be increased/decreased by adding/removing the number of triangles (faces and vertices). Though great for rendering and visualizing explicit shapes, meshes are not easy to work with at a computer vision level. A popular way of doing so, however, is by sampling points along the mesh’s surface to construct a point cloud, from where further computation can be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*eFULjRrGo1Jk_2xi-RHABw.png" /><figcaption>Mesh Representation of a Cup [9]</figcaption></figure><h4>References</h4><p>A lot of the material in this blog and the overall flow is heavily inspired by Justin Johnson’s 3D Vision lecture at the University of Michigan in 2019, which can be accessed on YouTube using the link below. His lecture helped me grasp 3D vision fundamentals in the best way possible and I hope this blog does the same for you!</p><p><a href="https://www.youtube.com/watch?v=S1_nCdLUQQ8">https://www.youtube.com/watch?v=S1_nCdLUQQ8</a></p><p>Other references include the following.</p><ol><li><a href="https://www.mdpi.com/1424-8220/22/18/7040">https://www.mdpi.com/1424-8220/22/18/7040</a></li><li><a href="https://towardsdatascience.com/depth-estimation-1-basics-and-intuition-86f2c9538cd1">https://towardsdatascience.com/depth-estimation-1-basics-and-intuition-86f2c9538cd1</a></li><li><a href="https://web.eecs.umich.edu/~justincj/slides/eecs498/498_FA2019_lecture17.pdf">https://web.eecs.umich.edu/~justincj/slides/eecs498/498_FA2019_lecture17.pdf</a></li><li><a href="http://www.atapour.co.uk/completeEstimate.html">http://www.atapour.co.uk/completeEstimate.html</a></li><li><a href="https://arxiv.org/abs/1411.4734">https://arxiv.org/abs/1411.4734</a></li><li><a href="http://blog.wolfire.com/2009/11/Triangle-mesh-voxelization">http://blog.wolfire.com/2009/11/Triangle-mesh-voxelization</a></li><li><a href="https://www.youtube.com/watch?v=CVuy7_WwHBs">https://www.youtube.com/watch?v=CVuy7_WwHBs</a></li><li><a href="https://elmoatazbill.users.greyc.fr/point_cloud/index.html">https://elmoatazbill.users.greyc.fr/point_cloud/index.html</a></li><li><a href="https://discourse.ros.org/t/proposal-new-computer-vision-message-standards/1819?page=2">https://discourse.ros.org/t/proposal-new-computer-vision-message-standards/1819?page=2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163fae591a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using ROS in a Docker Container]]></title>
            <link>https://medium.com/@vikramsetty169/using-ros-in-a-docker-container-862bcbd9d4bf?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/862bcbd9d4bf</guid>
            <category><![CDATA[roses]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 16:37:21 GMT</pubDate>
            <atom:updated>2024-08-17T18:51:22.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*wuyhESkB41HACgTPyVrIfg.png" /></figure><p><em>The problems of library version mismatch, OS distribution support, and so much more find their way to ROS developers too, and as in other fields, Docker can prove to be quite a handy tool. In my opinion, the potential that Docker holds in helping roboticists is quite underrated. In this blog, I’ll go over how to get started with the basics of Docker and how we can use different ROS distributions as Docker containers. Read to know more!</em></p><h4><strong>Required Prerequisites</strong></h4><ol><li>Docker and ROS basics</li><li>Linux (Ubuntu) command-line interface</li></ol><h4><strong>Blog Overview</strong></h4><p>Initially, we’ll go over how to get a specific ROS distribution from Docker Hub and use it as a container in your Ubuntu system. We’ll then go over setting up a Catkin Workspace and using the basic functionalities of ROS within the container. This blog takes the example of using ROS Kinetic (a ROS 1 distribution) in the container.</p><h4><strong>Setting Up Your Docker Container</strong></h4><p>The biggest advantage of using Docker as a ROS developer is the ability to use multiple versions of ROS on the same machine, or the same OS rather. It basically gives you the power of a virtual machine, with each container having its own ROS distribution and packages. I initially turned to Docker to be able to use ROS Kinetic and run a few packages built for only that distribution. Having an Ubuntu 20.04 OS with ROS Noetic installed, Docker was the best way for me to accomplish this task.</p><p>There are many different Docker images available on Docker Hub to pull from. The ROS Docker Official Images are usually considered the best and most reliable to work with. I have attached the link to the Docker Hub page below.</p><p><a href="https://hub.docker.com/_/ros/">ros</a></p><p>However, it isn’t necessary to only use images from the official ROS Docker Hub page. Images published by other people should work fine too. For example, I too ended up having to use a ROS Kinetic Image (attached below) from a third party and it worked as smoothly as it could have.</p><p><a href="https://hub.docker.com/r/mjenz/ros-kinetic-desktop-full">Docker</a></p><p>After selecting the image of your choice, pull the image as per the command shown in Docker Hub. For example, the command I used is shown below.</p><pre>docker pull mjenz/ros-kinetic-desktop-full</pre><p>Do note that on a system you can pull as many images as you want. They could be the same image, different images of the same ROS version, or even different ROS versions altogether. Each container built is independent of other containers and would be run separately.</p><h4><strong>Using ROS in the Container</strong></h4><p>To start the docker container, we can run the <em>docker run</em> command as shown below by calling the name of the Docker image for an interactive session (indicated by the <em>it</em> argument). I’ve run it below for the image I shared a link to in the previous section.</p><pre>docker run -it ros mjenz/ros-kinetic-desktop-full</pre><p>Running the command would take us into an interactive session within the container. However, as ROS developers, we would need multiple interactive terminal tabs open to run and execute different packages. To do that we can run the command below to get the list of all currently running containers.</p><pre>$ docker ps -l</pre><p>On running the command, you should get a result similar to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*fmwNNENSCdxd5TVgV4I7cA.png" /><figcaption>Figure 1: Identifying the Container ID of the Running Docker Container</figcaption></figure><p>The text highlighted in white shows the Container ID of the running Docker container. Using this container ID, we can open a new terminal tab running in the same Docker Container by executing the command below.</p><pre>docker exec -it {ContainerID} bash</pre><p>Now that you have been able to open multiple terminal tabs within the container, it is necessary to set up the environment, which can be done by running the following command.</p><pre>source ros_entrypoint.sh</pre><p>Here, the <em>entrypoint.sh</em> file is a part of the container that needs to be run to set up the environment. After sourcing this file, we can continue to do operations in the ROS package as we usually do.</p><h4><strong>Listening to ROS Nodes Outside the Container</strong></h4><p>Sometimes, especially while working with hardware, it becomes necessary to listen to nodes outside the container. By default, docker containers run a virtual bridge network, often making the <em>localhost</em> inaccessible. This makes working with hardware and listening to nodes from other devices/containers impossible. To fix this, we can activate the networking driver by using the <em>— network host argument</em> when we run the container. So the new way to run and start the interactive session of the container would look like as shown below.</p><pre>docker run -it --network host ros mjenz/ros-kinetic-desktop-full</pre><h4><strong>Creating and Using the Catkin Workspace</strong></h4><p>Creating the Catkin Workspace in Docker is pretty similar to how one would do it in a regular ROS 1 installation. We can follow the steps given below to initially create the Catkin Workspace.</p><pre>$ mkdir -p ~/catkin_ws/src<br>$ cd ~/catkin_ws/src</pre><p>After cloning an existing repository or setting up your own package, you can source and make the package as shown below.</p><pre>$ cd ~/catkin_ws<br>$ catkin_make<br>$ source devel/setup.sh</pre><p>Do note that while accessing the <em>catkin_ws</em> directory, we cannot directly do a <em>cd catkin_ws</em> command. We would rather have to access it using a <em>cd /root/catkin_ws</em> or <em>cd ~/catkin_ws</em> command, meaning we have to access it through the home directory.</p><h4><strong>Summary</strong></h4><p>Through this blog, I hope you’ve been able to learn the basics of using ROS within a Docker Container. Though this isn’t comprehensive of the many other things you can do with ROS and Docker, I hope this has been a good place to start and understand how the whole thing works!</p><h4><strong>References</strong></h4><ol><li><a href="https://roboticseabass.com/2021/04/21/docker-and-ros/">https://roboticseabass.com/2021/04/21/docker-and-ros/</a></li><li><a href="http://wiki.ros.org/docker/Tutorials/Docker">http://wiki.ros.org/docker/Tutorials/Docker</a></li><li><a href="http://www.finnrietz.dev/linux/ros-docker/">http://www.finnrietz.dev/linux/ros-docker/</a></li><li><a href="https://tuw-cpsg.github.io/tutorials/docker-ros/">https://tuw-cpsg.github.io/tutorials/docker-ros/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=862bcbd9d4bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edge Types in Graph Traversal]]></title>
            <link>https://medium.com/@vikramsetty169/edge-types-in-graph-traversal-1c3545c61234?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c3545c61234</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 13:48:11 GMT</pubDate>
            <atom:updated>2022-09-03T13:48:11.450Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You won&#39;t see much difference between different edges when you take a quick glance at a graph, but that changes once you view the graph from the perspective of a single node. Let&#39;s traverse the graph with that node as the starting point. We then observe different types of edges, each present or absent differently in various kinds of graphs when explored using different algorithms. Read to know more!</em></p><h4><strong>Required Prerequisites</strong></h4><ol><li>Basics of Graph Theory (Nodes, Edges, Directed &amp; Undirected Graphs)</li><li>Graph Traversal Algorithms, i.e., Breadth-First Search (BFS) &amp; Depth-First Search (DFS)</li></ol><h4><strong>Introduction to Graph Edge Types</strong></h4><p>While exploring a graph from a source node, edges can be of four types.</p><ol><li><strong>Tree Edges</strong>: Tree edges connect a parent to its child node. The terms parent and child come up in reference to the graph exploration algorithm being used, i.e., when you use BFS or DFS to traverse a graph, a new child node you discover by examining the neighbors of the parent node is connected via a tree edge. Only tree edges make up the BFS/DFS traversal. All other edges fall in the other three categories.</li><li><strong>Forward Edges</strong>: Forward edges link a node to its descendent that has already been traversed.</li><li><strong>Back Edges</strong>: Back edges link a node to its ancestor that has already been traversed.</li><li><strong>Cross Edges</strong>: Cross edges connect two nodes that don&#39;t share any ancestor-descendent relation.</li></ol><p>These definitions may be a little vague and might not make sense at the moment, but they will become more apparent as we go through different traversals in the following sections by taking sample graphs.</p><p>In the sample graphs being used as examples, the following color scheme will be used while addressing edge types:</p><ol><li>Tree Edges: Green</li><li>Forward Edges: Blue</li><li>Back Edges: Purple</li><li>Cross Edges: Red</li></ol><p>We also assume that we always start exploration using node &#39;A&#39; as the source. Also, though edge classification depends on what neighbors we discover first during traversal, I&#39;ve included scenarios where the neighbor order becomes intuitive.</p><h4>Edges in a Directed Graph using DFS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*a8m7DsAO8LyEyzhqHbBobA.png" /><figcaption>Figure 1: DFS on a Directed Graph</figcaption></figure><p>When we traverse an undirected graph using DFS, we get an edge combination as shown above. Assume that traversal was done from node &#39;A&#39; starting with the A-B, then followed by the A-D edge. A couple of points to note:</p><ol><li>In this case, all types of edges are present.</li></ol><h4>Edges in an Undirected Graph Using DFS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*dkGXyx2sppz4FgeeWWyVSQ.png" /><figcaption>Figure 2: DFS on an Undirected Graph</figcaption></figure><p>When we traverse an undirected graph using DFS, we get an edge combination as shown above. Assume traversal was done from node &#39;A&#39; starting with the A-B edge. A couple of points to note:</p><ol><li>We only have tree and back edges in this scenario.</li><li>Forward cannot exist while using DFS on an undirected graph. This is because all such possibilities translate into back edges. For example, though A-E might look like a forward edge, it&#39;s a back edge since that edge is discovered from the &#39;E&#39; end before the &#39;A&#39; end because of the nature of the DFS algorithm.</li><li>Cross edges cannot exist either because their possibility implies that the explored node should have been traversed earlier. For example, though B-C looks like a cross edge and A-C like a tree edge, the nature of DFS makes B-C a tree edge and subsequently A-C a back edge.</li></ol><h4>Edges in a Directed Graph using BFS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*FxXxNVxORM53TgThQ8724A.png" /><figcaption>Figure 3: BFS on a Directed Graph</figcaption></figure><p>When we traverse a directed graph using BFS, we get an edge combination as shown above. A couple of points to note:</p><ol><li>We only have tree, back, and cross edges in this scenario.</li><li>Forward edges cannot exist because their possibility of existence implies that they should have been used as a tree edge for traversal earlier. For example, though A-I visually looks like a forward edge, it&#39;s a tree edge, making D-I a cross edge though it looks like a tree edge.</li></ol><h4><strong>Edges in an Undirected Graph Using BFS</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*psjUPsBQjGdZhlU0yu6XtA.png" /><figcaption>Figure 4: BFS on an Undirected Graph</figcaption></figure><p>When we traverse an undirected graph using BFS, we get an edge combination as shown above. A couple of points to note:</p><ol><li>We only have tree and cross edges in this scenario.</li><li>Cross edges can only connect two nodes at the same or adjacent levels. A level signifies a set of nodes sharing the same distance from the source. This is valid since if an edge spanning nodes with a difference with two or more levels could have existed, it would have been traversed beforehand. For example, the cross edge between B and C spans the same level, and the cross edge between C and H spans a single (adjacent) level.</li><li>Back and forward edges cannot exist either since that edge would have already been used for traversal earlier. For example, the edge connecting A and E looks like a back or forward edge but is actually a tree edge, making node E a single unit of distance away from A and B-E a cross edge.</li></ol><h4><strong>Summary</strong></h4><p>The information regarding edge types and their appearance in different graphs and traversals can be summarised in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*Hk_Mu2AW6kQ6JEQefYWqcA.png" /><figcaption>Table 1: Edge Types in Graph Traversal</figcaption></figure><p>However, note that the cross edges mentioned for undirected graphs using BFS span only across the same or adjacent levels (explained in detail earlier).</p><h4><strong>Reach Out For More</strong></h4><p>I hope you all got a good grasp of the different types of graph edges, their role, and presence/absence in various graphs and traversals. A lot of the understanding comes from intuition, and I recommend you to sit on these concepts for a while and convince yourselves why the conclusions I&#39;ve made turned out as they did.</p><p>If you have any questions or want to know about anything in more detail, don&#39;t hesitate to contact me via Linkedin. I&#39;ve linked my profile below.</p><p><a href="http://www.linkedin.com/in/vikram-setty">www.linkedin.com/in/vikram-setty</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3545c61234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiler Aware Programming Optimizations]]></title>
            <link>https://medium.com/@vikramsetty169/compiler-aware-programming-optimizations-1799ec6332af?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/1799ec6332af</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 14:38:20 GMT</pubDate>
            <atom:updated>2022-08-19T14:38:20.823Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You might underestimate it, but your compiler does a LOT! Apart from just converting your high-level language (HLL) program into assembly language, it constantly looks for optimizations to reduce the number of CPU cycles required to run your code. Although it does a pretty good job, it can only do so much and often runs into optimization blockers. However, we can help compilers A LOT by adopting a few subtle programming practices. They won&#39;t improve algorithmic efficiency or anything, but they&#39;ll take your implementation of the algorithm to a highly optimized level!</em></p><h4><strong>Required Prerequisites</strong></h4><ol><li>Understanding of Time Complexity and the Big-O Notation</li><li>Basic knowledge or intuition of computer architecture (pipelining, caching, control flow, etc.)</li><li>Familiarity with C++</li></ol><h4><strong>Introduction</strong></h4><p>According to the Big-O Notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*aakZ_XjZIA6bpQCGI617RA.png" /><figcaption>Equation 1: Big-O Notation</figcaption></figure><p>Graphically, we can represent this as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/0*68ADo0NhRqxgP074" /><figcaption>Figure 1: Graphical Representation of the Big-O Notation</figcaption></figure><p>When programming, the algorithm you choose makes the most significant contribution to efficiency. For example, irrespective of whether you have redundant loops and condition checks all over your code, an algorithm running in O(logN) time will run better than an algorithm executing in O(N) time in the long run. So, as a programmer, your foremost priority should always be choosing appropriate data structures and efficient algorithms. But once you have selected an optimal algorithm, there are still things you can do to optimize your code even further. It won&#39;t bring the time complexity down from, say, O(N) to O(logN), but it can drastically change the value of &#39;c&#39; defined earlier in the formula of the Big-O Notation. So how do we do this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*AwbXqUNmwtPi7afAqf150A.png" /><figcaption>Figure 2: Compilers</figcaption></figure><p>To understand these optimizations, we have to look from the perspective of a compiler. A compiler and assembler jointly work to convert your program written in a high-level language (HLL) like C/C++, Python, Java, etc., to machine code, which is then executed in a pipelined fashion by the computer&#39;s processor. The critical word here is <em>pipelined</em>. Your compiler constantly looks for optimizations like instruction reordering, register allocation, and inefficiency reduction to bring the effective cycles per instruction of the program as close to one as possible. Compilers even have optimization levels that correspond to different aggression levels they can work at. For example, in C, you can specify different levels of optimizations you want the compiler to work at using the -o1, -o1, or -o3 levels in GCC. You can read more about this in the link given below.</p><p><a href="https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html">Optimize Options (Using the GNU Compiler Collection (GCC))</a></p><p>Even with all of the compiler&#39;s power, it&#39;s sometimes helpless as it can&#39;t do any better without the help of the programmer. Thus, as programmers, we are responsible for writing code, keeping the compiler in mind, and trying to make its job as easy as possible. We can do this by adopting the following practices:</p><ol><li>Concurrent programming</li><li>Sharing common subexpressions</li><li>Using basic ALU operations most of the time</li><li>Minimizing procedure calls</li><li>Getting rid of unnecessary memory references</li><li>Decreasing dependency between different instructions</li><li>Utilizing spatial and temporal locality</li></ol><p>These optimizations will reasonably ease the compiler&#39;s work and increase program efficiency, even if it is just marginally. However, even with these optimizations, the compiler sometimes can&#39;t do anything because of <strong>optimization blockers</strong>. Two of these blockers include the ones mentioned below.</p><ol><li>Potential memory aliasing</li><li>Potential procedure call side effects</li></ol><p>We&#39;ll go through all the optimizations and blockers with examples to illustrate how they work and can be exploited.</p><h4><strong>Concurrent Programming</strong></h4><p>In 2001, IBM introduced the first multicore processor (2 64-bit microprocessors), and the world has never looked back. A lot of computation in a program can be split up into multiple independent (or almost independent) sub-tasks that should be exploited to the maximum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*WepY7X0-KAbNckrk.png" /><figcaption>Figure 3: Multi-threading in a Multicore Processor</figcaption></figure><p>Programmers should use every opportunity to parallelize code and run smaller program segments simultaneously using different threads on multiple cores and processors. Though doing this doesn&#39;t help the compiler, it incorporates long-term benefits that only increase efficiency.</p><h4><strong>Sharing Common Subexpressions</strong></h4><p>Sometimes, we unknowingly or knowingly promote the recomputation of specific values, which are repeatedly reused. For example, look at the C++ code below, where we observe the corners surrounding a pixel of an index (n1*x,n2*y) stored in a 2D array &#39;arr.&#39;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*pI-udsecBSzgLnA2EhDruw.png" /><figcaption>Code 1: Sharing Common Subexpressions 1</figcaption></figure><p>In this example, we are making the compiler recompute the value of n1*x &amp; n2*y four times each when we could enable it to do it only once by storing the values in variables. This would effectively reduce 6 ALU operations. Thus, the optimal way of going about this program can be seen in the corrected code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*zYjVQ6QtqLS-Injj0r9nAA.png" /><figcaption>Code 2: Sharing Common Subexpressions 2</figcaption></figure><h4><strong>Using Simple ALU Operations</strong></h4><p>Some ALU operations are more expensive than others. Generally, multiplication and division require more computation than addition, subtraction, logic gates, and other bit manipulations. Though it&#39;s inevitable sometimes to use multiplication and division in their standard forms, we can frequently adopt certain tricks to make use of the fact that some ALU operations are computationally cheaper. Some examples are shown in the code snippet below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*CGCIjPa0HGSAzFiFipLz6Q.png" /><figcaption>Code 3: Using Simple ALU Operations 1</figcaption></figure><p>Again, this isn&#39;t directly related to the compiler but is a practice you should keep in mind while coding. It might reduce code readability slightly but provides a reasonable tradeoff, especially if you use multiple such operations repeatedly throughout your program.</p><h4><strong>Minimizing Procedure Calls</strong></h4><p>As programmers, we often tend to specify unnecessary procedures or function calls. In some places, they make sense, but in others, they are redundant and increase computation for no reason. For example, look at the code snippet below, where we calculate the sum of elements in a C++ vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wEvfvQzwKObaRcRwzDGGXw.png" /><figcaption>Code 4: Minimizing Procedure Calls 1</figcaption></figure><p>The problem with this method is that for iteration, we call a function to recompute the size of the vector. The compiler can&#39;t assume that the vector&#39;s length remains constant throughout the loop and thus can&#39;t omit this step. This promotes unnecessary computation and increases the program&#39;s execution time. Therefore, we must utilize the fact that we aren&#39;t changing the vector&#39;s size by modifying the code slightly. We can do that by storing the size in a variable or using iterators, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*iWThGNkfSc5GoY5ZD9esPA.png" /><figcaption>Code 5: Minimizing Procedure Calls 2</figcaption></figure><h4><strong>Eliminating Redundant Memory References</strong></h4><p>In the control path for executing a machine code, memory accesses are done using load and store instructions which are the most time-taking. They are often the sole bottlenecks that cause the program to take many more CPU cycles to execute than it should. That&#39;s why it&#39;s crucial to store frequently used values and expressions in variables so they can easily be accessed through CPU registers instead of from the cache, RAM, or secondary memory. Let&#39;s take an example where we once again find the sum of a vector and store it at a location in the main memory. We could do this by repeatedly accessing that location and incrementing its value like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*O0C7Y6AUpme6dMvdjb53lQ.png" /><figcaption>Code 6: Eliminating Redundant Memory References 1</figcaption></figure><p>In this example, we reference the location of &#39;sum_vector&#39; &#39;N+1&#39; times. That is extremely expensive, especially if &#39;N&#39; is of a high order. We could alternatively limit the number of references to just two by modifying our approach by using variables stored in CPU registers, as shown in the subsequent code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*TLmByMHbzHN4wtzcjaPFcg.png" /><figcaption>Code 7: Eliminating Redundant Memory References 2</figcaption></figure><h4><strong>Decreasing Instruction Interdependency and Utilizing ILP</strong></h4><p>In an ideal scenario, pipelining allows us to reduce the average cycles per instruction to about 1, but unfortunately, that rarely even comes close to happening. Consider the illustration of pipelined instruction execution displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*_FnBWLdV3nUOdsHg" /><figcaption>Figure 4: Pipelining</figcaption></figure><p>This execution, with three instructions completed in 7 CPU cycles, is possible only when the three instructions are entirely independent (and other assumptions like no memory referencing). Although compilers enforce specific strategies like data-forwarding and branch-prediction to work with scenarios when instructions are interdependent, stalls are inevitable at some point or the other, at least while working with large programs. A large number of stalls occurring periodically could drastically increase the number of CPU cycles.</p><p>It is essential to work around this bottleneck as much as possible by making code segments independent from one another. This goes hand in hand with parallel or concurrent computation. If you have multiple, independent code segments to execute, execute them simultaneously, whether you have multiple cores or not. Take note of the example shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*fISj-aA25aylwlKcSR1w3w.png" /><figcaption>Code 8: Decreasing Instruction Interdependency and Utilizing ILP 1</figcaption></figure><p>ILP refers to <strong>instruction level parallelism</strong>. It&#39;s the &#39;illusion&#39; that multiple instructions are being executed simultaneously when they are being implemented in a pipelined manner. If the pipelining is almost optimal or stalls aren&#39;t frequent, the program displays a high level of ILP. As programmers, we have to do our part in ensuring that happens!</p><h4><strong>Exploiting Spatial &amp; Temporal Locality</strong></h4><p>Spatial Locality is based on the premise that locations close to another location that has been accessed have a high probability of being used in the near future. For example, if I currently access a block from the main memory, there&#39;s a good chance I&#39;d be exploring areas surrounding that block soon too.</p><p>Temporal locality is quite similar, except that it specifies a high probability of reusing the same block of accessed memory again in the near future.</p><p>Both concepts are intuitive and apply to many programming applications, especially loops, where we usually iterate over a range of memory locations (high potential to exploit spatial locality) or repeatedly perform an operation on the same set of memory locations (high potential to exploit temporal locality). It&#39;s essential to have a good understanding of these concepts and fully use them because memory access is a costly step during instruction execution. Optimizing code concerning loading and storing data can have high returns in efficiency.</p><p>To illustrate how we can exploit these patterns while programming, we can look at the code for matrix multiplication, a principle that uses three nested loops and runs in O(N³) time. We can do this in 6 ways, by interchanging the order of the nested loops. Each of them is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Fm5t9a1rtp2Y1zt9tbYMvg.png" /><figcaption>Code 9: Exploiting Spatial &amp; Temporal Locality 1 (i-j-k)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*KJ6L8FMgwmCemRalfpiFxA.png" /><figcaption>Code 10: Exploiting Spatial &amp; Temporal Locality 2(j-i-k)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*-6dESEfr7a8zJqfiyjNGyw.png" /><figcaption>Code 11: Exploiting Spatial &amp; Temporal Locality 3 (j-k-i)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*CjUz5FnEhmp9gnEnrJ8BMA.png" /><figcaption>Code 12: Exploiting Spatial &amp; Temporal Locality 4 (k-j-i)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*zmLAwqykzZuvnamXRdhogw.png" /><figcaption>Code 13: Exploiting Spatial &amp; Temporal Locality 5 (k-i-j)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*lfdEyLs4QYODu_Hi2umkug.png" /><figcaption>Code 14: Exploiting Spatial &amp; Temporal Locality 6 (i-k-j)</figcaption></figure><p>Though all of these six implementations are identical in correctness and time-complexity, they vary quite a bit with respect to the time required to access blocks of memory (i.e., rows of A, columns of B, and cells of C). Some of these six implementations utilize spatial and temporal locality better than others. To compare, let&#39;s assume a block size of 4 and a single cache level. If an element is accessed, its entire block containing four elements is brought from the main memory into the cache. An element in the cache takes less time to access. Thus whenever we access a new element from the main memory, we bring its entire block into the cache to exploit spatial and temporal locality. We get a <em>hit</em> when the element we&#39;re looking for is already in the cache and a <em>miss</em> when it&#39;s not in the cache, in which case the new block has to be brought from the main memory. We&#39;ll also assume&#39; N&#39; to be significantly high. In such a case, by just observing the program flow, we can note hit and miss ratios in each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*GFw5C7iXvo25XDEg-lXHZg.png" /><figcaption>Table 1: Miss Ratio in each Method</figcaption></figure><p>From this calculation, it is evident that the last two methods (k-i-j &amp; i-k-j) encounter the least amount of misses and thus provide a considerable advantage by saving lots of time when multiplying huge matrices. By using spatial and temporal locality better, these two methods have the memory locations we need to access in the cache most of the time. Many of us might turn to the first method to multiply matrices out of habit, but now knowing this, I hope you make it a practice to tweak your approach and account for spatial and temporal locality next time.</p><h4><strong>Optimization Blocker 1: Potential Memory Aliasing</strong></h4><p>Now that we&#39;ve gone over all the methods we can adopt to ease the compiler&#39;s work and make the program more efficient; we&#39;ll now turn to two specific cases where the compiler can&#39;t do anything just because of the nature of the program. These are called optimization blockers. The first blocker we&#39;ll look at is potential memory aliasing.</p><p>Memory aliasing is a situation where a single memory location can be accessed through multiple symbolic names or variables. But how is this a problem? Look at the two codes shown below. They should be equivalent to each other, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*EBriByuiWoyHdjLbUCCzoA.png" /><figcaption>Code 15: Optimization Blocker 1: Potential Memory Aliasing 1</figcaption></figure><p>If the two cases mean the same thing, the compiler could easily view the first case as the second if and when it encounters it. This would reduce the instruction count and thus the number of CPU cycles too. However, the two cases need not be equivalent if you look closely enough. If even one of &#39;y&#39; or &#39;z&#39; point to the same location, case 1 and case 2 give different results. The compiler doesn&#39;t know where each pointer points and thus can&#39;t make assumptions. Hence, the compiler can&#39;t do much with code segments like in the first case and runs into optimization blockers.</p><h4><strong>Optimization Blocker 2: Potential Procedure Call Side Effects</strong></h4><p>Procedure calls can sometimes be tricky to optimize as well. Like the previous optimization blocker, let&#39;s look at two supposedly equivalent cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*o_6N2jECGbtoOofoKKF2RA.png" /><figcaption>Code 16: Optimization Blocker 2: Potential Procedure Call Side Effects 1</figcaption></figure><p>Is there any possibility that the two cases could return different values this time? The answer is, once again, yes. Imagine the possibility of global variables that get incremented within f(). In that case, they would increment twice as many times in the first case compared to the second. Thus, once again, the compiler can&#39;t optimize case 1 by equating it to case 2 and runs into an optimization blocker.</p><h4><strong>Reach Out for More!</strong></h4><p>I hope you got a good understanding of the different techniques and blockers I discussed. I hope you start incorporating these principles while programming next time too!</p><p>If you have any questions or want to know about anything in more detail, don&#39;t hesitate to contact me via Linkedin. I&#39;ve linked my profile below.</p><p><a href="http://www.linkedin.com/in/vikram-setty">www.linkedin.com/in/vikram-setty</a></p><h4><strong>References</strong></h4><p>This blog is built on the principles mentioned in the book &#39;Computer Systems: A Programmer&#39;s Perspective,&#39; written by Randal Bryant and David O&#39;Hallaron. It also takes inspiration from the lecture slides of Warren Hunt and Bill Young from UT Austin.</p><p>Other references include:</p><ol><li>[Figure 1] <a href="https://notesformsc.org/algorithms-order-of-growth/">https://notesformsc.org/algorithms-order-of-growth/</a></li><li>[Figure 2] <a href="https://www.vectorstock.com/royalty-free-vector/compiler-concept-icon-software-development-vector-29166490">https://www.vectorstock.com/royalty-free-vector/compiler-concept-icon-software-development-vector-29166490</a></li><li>[Figure 3] <a href="https://stackoverflow.com/questions/32887943/multithreading-and-multitasking-on-single-core-processor-vs-multicore-processor">https://stackoverflow.com/questions/32887943/multithreading-and-multitasking-on-single-core-processor-vs-multicore-processor</a></li><li>[Figure 4] <a href="https://en.algorithmica.org/hpc/pipelining/">https://en.algorithmica.org/hpc/pipelining/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1799ec6332af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bayes Filter]]></title>
            <link>https://medium.com/@vikramsetty169/the-bayes-filter-71f8b61afc1c?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/71f8b61afc1c</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[bayes-theorem]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[bayes-filter]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Sun, 14 Aug 2022 13:31:13 GMT</pubDate>
            <atom:updated>2022-08-14T13:32:59.876Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In basic terms, the Bayes Filter is just the probabilistic representation of a system&#39;s state/belief. We can often update this belief to a more accurate value by performing recursive Bayesian estimation on new information. Though it might sound a little overwhelming, the Bayes Filter is simply the result of using the Bayes Theorem, one of the most simple yet valuable principles of probability theory. Although we can use the Bayes Filter in various applications (usually to find outliers like detecting spam emails), this blog focuses on its importance in robotics, particularly in localization, mapping, and the two combined, SLAM.</em></p><h4><strong>Required Prerequisites</strong></h4><ol><li>Basics of probability theory and calculus</li><li>Familiarity with sensors like ultrasound and lidar and their fundamental working principles.</li></ol><h4><strong>Background</strong></h4><p>I called the Bayes Filter a system&#39;s &#39;belief&#39; of its environment. So what exactly is this so-called belief? And how do we represent it using probability?</p><p>In a robotics context, a robot&#39;s belief refers to its presumption of its state or configuration. For example, for a wandering robot, it might be its position represented by coordinates. For a serial manipulator, it could be a set of joint angles. A belief is specific to the configuration space a robot behaves in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Rlk7NZjhkFGV4HNjKh3yFQ.png" /><figcaption>Figures 1 &amp; 2: Systems with states represented by coordinates (x&amp;y) and joint angles, respectively</figcaption></figure><p>You probably could ask why this is a big problem. After all, can&#39;t sensors in a robot help it calculate its configuration precisely? In an ideal case, yes. But sensor readings can often be wrong. Even some of the best sensors like laser scanners and lidars can suffer from errors like crosstalk (different beams interfering with each other), total reflection (at obstacles like glass), random measurements (not following any pattern), and maximum range errors (where the maximum range of the sensor is reached and no obstacle is detected). These errors can be visualized in the figure below, showing a typical 24-beam ultrasound scan. That is why it is necessary to develop an efficient framework to localize a system&#39;s belief accurately over time, considering that many measurements are wrong or erratic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*SLP87wA3FWHhU818MKgBfQ.png" /><figcaption>Figure 3: Errors in an Ultrasound Scan</figcaption></figure><p>However, in the end, a belief is just a belief. The actual state or configuration of the robot need not be what the robot thinks, as robots don&#39;t always have that information. Thus, the robot needs to use new information to update its belief and accurately estimate where it is or what its configuration looks like. This is the entire premise for the Bayes Filter! We need to use probability to represent the likeliness of a robot being in a particular state since it ensures an easy way of updating beliefs.</p><p>So how do we model this? How do we represent states and actions? Using what rubric does the robot make actions? These questions can be easier to answer if we can visualize the flow of information through time. For the rest of this blog, we can assume that at timestep &#39;t,&#39; the system is in state &#39;Xt,&#39; makes an observation &#39;Zt,&#39; and then takes action &#39;Ut+1&#39;, taking it to state&#39; Xt+1&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*HGHILPacxdEEJevG33fzrQ.png" /><figcaption>Figure 4: State-Action-Observation Flowchart</figcaption></figure><p>Here, observations refer to any information the robots can sense from being in a particular configuration. It could be GPS data, camera images, ultra-sound information, laser scans, etc. Actions can mean various things, from changing joint angles, moving left, rotating clockwise by an angle, etc. For simplicity, we can break down and limit all these infinite numbers of continuous actions into a discrete set we can apply to our robot.</p><p>So, now that we have a clear idea of notation and information flow over time, how does a system update its belief? The most basic way to do so is using <strong>Recursive Bayesian Updation</strong>. This method is not equivalent to using a Bayes Filter but will provide a preliminary understanding of how we can use the Bayes Theorem to update belief probabilities.</p><p>First, before we get into Recursive Bayesian Updation, we need to revisit Bayes Theorem. Bayes Theorem in two variables looks like as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*lz9GUuEkAws5nbHp1RaTAw.png" /><figcaption>Equation 1: Bayes Theorem in 2 Variables</figcaption></figure><p>Here, the prior refers to the probability of an event happening before performing some action Y on the system. This action results in the updated posterior, or the new belief of X. Thus, we can update beliefs using the simplest form of the Bayes Theorem! It&#39;s also essential to look at Bayes Theorem when extended to 3 variables (which you can prove quite easily and even extend to more variables), the formula of which is attached below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*O_PhMqlllk5UWsZH_Cpm2A.png" /><figcaption>Equation 2: Bayes Theorem in 3 Variables</figcaption></figure><p>In the context of robotics like localization, mapping, and SLAM, the denominators of equations 1 and 2 are usually fixed and can be treated like a normalization constant 𝜂.</p><p>Now, coming back to Recursive Bayesian Updation. Take an example to find the belief of a systems state (X). Given all its prior observations(Z), we can model the problem as solving for P(X|Z1…Zn). We can do this using the simple procedure shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*rWqSsxPwjVyF-YwAuqOuUw.png" /><figcaption>Derivation 1: Recursive Bayesian Updation</figcaption></figure><p>The derivation made above uses a simple yet essential assumption, <strong>Markov Independence</strong>. It assumes that the observation made from the present state is independent of the previous observations. Though this sounds intuitive, it may not be entirely accurate but can safely be assumed in most cases. Overall though, the set of equations above depicts how we can easily calculate the belief recursively using Bayes Theorem, giving a more accurate version with each timestep (ideally!)</p><h4><strong>The Bayes Filter Equation</strong></h4><p>The method shown for Recursive Bayesian Updation is one way to model our problem statement (representing beliefs). Still, as you may have noticed, we&#39;ve only used observation data (Z) and haven&#39;t considered actions made by the system (U). To incorporate those into our belief, we need to modify what we are looking for from the earlier P(X|Z1…Zn) to Bel(Xt) = P(Xt|Z1…Zt,U1…Ut). We call this version of belief, i.e., Bel(Xt), the <strong>Bayes Filter</strong>! Using the procedure shown below, we can get to a reasonable formula for calculating Bel(Xt).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*UzBzFd8E2M48M-GTR5p73Q.png" /><figcaption>Derivation 2: Bayes Filter Equation</figcaption></figure><p>Thus, using just Bayes Theorem &amp; Markov Independence, we could derive the Equation for the Bayes Filter. I&#39;ll put it separately below since we&#39;ll revisit this equation repeatedly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*kQerlOeayV3W6BP_zZvcSA.png" /><figcaption>Equation 3: The Bayes Filter Equation</figcaption></figure><p>Now the big question is how we use it. How do we put sensor, action, and state information into this equation to calculate our system&#39;s belief? How do we represent the terms in the equation specific to our system? We must find a way to model and represent P(Zt|Xt) &amp; P(Xt|Xt-1,Ut), referred to as probabilistic sensor and motion models, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*F4FT446ywtU-6lIds2n1TA.png" /><figcaption>Equations 4 &amp; 5: Probabilistic Motion &amp; Sensor Models</figcaption></figure><p>We&#39;ll go further into each of these in the subsequent sections. However, note that the equations and representations used till this point were general and could be applied to any system. However, motion and sensor models become specific to the system/application. Though different robots may share some similarities in how we model them, they could also be vastly different. For the rest of the blog, we&#39;ll assume we are using a robot with a lidar scanner to localize itself in a known and mapped environment.</p><h4><strong>Probabilistic Motion Models</strong></h4><p>As discussed, motion models represent the P(Xt|Xt-1,Ut) term of the Bayes Filter Equation. In the context of a robot localizing itself in a mapped environment while it simultaneously moves around, we can use motion models in two ways: odometry and velocity-based (dead reckoning) approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*0ftMAjRFE2gKC2VfwBZybw.png" /><figcaption>Figure 5: Types of Motion Models</figcaption></figure><p><strong>Odometry-based Approaches</strong></p><p>Odometry models use sensors like wheel encoders which calculate the robot&#39;s movement through rotation and translation. Of course, these measurements are not perfect and need to be modeled probabilistically to construct appropriate models. Without going too mathematical, the idea behind how to use these approaches can be understood through this picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*BpQRmfq9YjXd17NuANm8Ug.png" /><figcaption>Figure 6: Odometry-based Motion Models</figcaption></figure><p>In each of the three instances, the state at the bottom-left corresponds to the previous timestep, and the set of dots represented as a distribution of possible states represent the current states. Because of uncertainty in the two rotations and one translation made to reach the new state, the set of possibilities for the new system&#39;s state is spread, sometimes more over rotation and sometimes more over translation, and sometimes almost equally over both. The basic mathematic intuition for modeling this would look like as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*0FBJGTO07fvANqelPbJNBA.png" /><figcaption>Equations 6 &amp; 7: Odometry-based motion models</figcaption></figure><p><strong>Velocity-based Approaches (Dead Reckoning)</strong></p><p>Mathematically, this approach is quite similar to odometry, where we multiply three independent probabilities, each corresponding to a Gaussian. The difference is that instead of using wheel encoders or other sensors to measure movement, we use the system&#39;s belief of its velocity and orientation to predict where the robot moved. Instead of two rotations and one translation, we now deal with a linear velocity term, an angular velocity term, and a rotation term. They can be depicted as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*cHJIM4l_OWUQWWHlZn0QSg.png" /><figcaption>Figure 7: Velocity-based (Dead Reckoning) Motion Models</figcaption></figure><p>Irrespective of the motion model you use, it is important to note how uncertainties concerning position increase over time. This can be better shown visually in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*BAY_BzDoAa1wyAfIQi212Q.png" /><figcaption>Figure 8: Increase in position uncertainty with time in motion models</figcaption></figure><p>This is intuitive, of course. If each timestep adds a new level of uncertainty, then the uncertainty is bound to increase over time. We often use techniques like loop closure to overcome such barriers, combining previously collected information with new information to narrow down our sample space of highly possible beliefs.</p><h4><strong>Probabilistic Sensor Models</strong></h4><p>Revisiting the Bayes Filter Equation, sensor models represent the P(Zt|Xt) term. Like motion models, this can be done in multiple ways, including beam-based and scan-based techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrZ7YX14sax3AbUxdjTNuQ.png" /><figcaption>Figure 9: Types of Sensor Models</figcaption></figure><p><strong>Beam-based Approaches</strong></p><p>Assume that a single scan consists of &#39;K&#39; measurements (say one corresponding to each beam in an ultrasound scan, for example). Though not an ideal assumption, we can assume each beam is independent of one another. With this assumption, we get the equation written below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*VS5aDk-FJAH6144BCBVv8g.png" /><figcaption>Equation 8: Combining K scans into a sensor model</figcaption></figure><p>In this equation, &#39;m&#39; represents the map (assumed to be known information for the localization problem). Although it was available even while we were computing the motion model, we didn&#39;t need it. We&#39;re going to need the map information here, though.</p><p>To find P(Zt|Xt), we have to use precomputed scans based on the known map to obtain a parameter &#39;Zexp,&#39; the assumed actual observation for the current belief (Xt). So using &#39;Z&#39; and &#39;Zexp,&#39; we can calculate P(Zt|Xt) using a combination of different distributions, as shown below. We measure &#39;Z&#39; &amp; &#39;Zexp&#39; as the distance from the sensor to the sensed object, wall, or obstacle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*xXVWDwnNdLMOJDfYqin8OA.png" /><figcaption>Figure 10: Resulting distribution from combining different distributions for the Beam-based Sensor Model</figcaption></figure><p>The various distributions that make up this new distribution include:</p><ol><li>A Gaussian centered around Zexp with a calibrated variance</li><li>A spike for maximum range measurements at the extreme right</li><li>A uniform distribution for random errors</li><li>An exponential curve for unexpected obstacles (like people) on the left</li></ol><p>We can calculate P(Zt|Xt) using the formulas specific to each distribution. For example, if our observation sample &#39;Z&#39; falls under the Gaussian area, we would use a procedure similar to what we used in the motion model.</p><p><strong>Scan-based Approaches</strong></p><p>Though beam-based methods seem easy to use and simple, they don&#39;t work well at larger scan angles and aren&#39;t very smooth around obstacles and edges. It&#39;s also computationally expensive since we have to precompute all the experimental scan values (Zexp).</p><p>Scan-based models work around these problems by considering only the endpoint instead of the entire beam. Here, we still use all the metrics in beam-based models (like random error, maximum range reading, etc.), but the model/visualize them using potential fields. This can be better understood using the charts shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*Ybq2mNsCdXMFejBIncWnjg.png" /><figcaption>Figure 11: Distributions in Scan-based Sensor Models</figcaption></figure><p>As you can see, all the distributions discussed earlier are combined into one distribution. Further, if we go along the line shown in the potential field diagram, the curve achieves a local maxima close to obstacles as we&#39;d expect (since that&#39;s where there is a higher probability for the endpoint of the beam to be). Using this distribution, we can calculate P(Zt|Xt) similar to how we did in beam-based approaches, comparing our &#39;Z&#39; sample with the appropriate distribution.</p><p>Compared to beam-based methods, scan-based methods are much smoother, more efficient, and can be extended easily to other forms.</p><p>Some other techniques that can be used to construct sensor models include the following:</p><ol><li><strong>Map Matching</strong>: Generating local maps from scans and matching them against an available global map.</li><li><strong>Scan Matching</strong>: Matching the endpoints of a scan against available global scans.</li><li><strong>Feature Extraction</strong>: Use features like towers, poles, and beacons to calculate the robot&#39;s local position and then use an available global map to find its actual position.</li></ol><h4><strong>Representing the Bayes Filter</strong></h4><p>If we revisit the Bayes Filter Equation one last time, we&#39;ll realize that we&#39;re left to model only one more term, and that&#39;s the Bayes Filter itself, i.e., Bel(Xt)! Going over all the ways we can represent the Bayes Filter, quantitatively and qualitatively, even in brief, would take a while and would probably require an additional blog for each technique. Thus, we&#39;ll only go through a small overview of each method in this section. The popular ways to represent the Bayes Filter include the ones shown in the flowchart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnsIWgDapNgq5PTeamYSbg.png" /><figcaption>Figure 12: Ways to represent the Bayes Filter</figcaption></figure><ol><li><strong>Discrete Filters</strong>: Discrete filters represent the most basic way to model the robot&#39;s configuration space by breaking it into discrete intervals. For example, a 2D planar robot (with an orientation)on an N*N grid could represent its state space using N*N*36 particles (36, assuming we break the 360° heading space into 36 discrete intervals of size 10° each). Even though discrete filters have proven to work well, they are computationally expensive, prompting us to look for better techniques.</li><li><strong>Kalman Filters</strong>: When you can represent the Bayes Filter as a continuous Gaussian, it becomes equivalent to a Kalman Filter! This means we can represent &#39;Xt&#39; as a Gaussian. However, even if &#39;Xt&#39; is a Gaussian, the Kalman Filter is a valid representation only if updation equations are linear and stochastic. This can be understood better by viewing the expressions below. Unless these conditions are met (which depend on a system-to-system basis), we cannot use the Kalman Filter to represent Xt.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*U5JVbVPOyp2dpEnUgPOOFw.png" /><figcaption>Equations 9 &amp; 10: Linear &amp; Stochastic Conditions for using the Kalman Filter</figcaption></figure><p>3. <strong>Extended Kalman Filter</strong>: Of course, very few systems, if any, behave in a truly linear fashion, and thus, only limited systems can directly use a Kalman Filter representation. However, we can use Extended Kalman Filters EKFs) which use local linearization to approximate non-linear systems as linear ones, utilizing modified updation rules.</p><p>4. <strong>Particle Filters</strong>: To overcome the problems with high computation in discrete filters, we can use particle filters to represent possible beliefs as particles, each following motion, and sensor models and updating with every iteration. We also perform sampling every iteration utilizing a set of weights to ensure that we&#39;re only keeping track of highly probable particles and not erroneous ones. As we explore environments and perform actions like loop closure, the initially &#39;spread out&#39; particles converge to smaller ranges of possible states. Particle filters can be visualized, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*CMqsjlOelKJilbu409epLw.png" /><figcaption>Figure 13: Particles in a Particle Filter representation converging</figcaption></figure><h4>Reach Out for More!</h4><p>Though we couldn&#39;t go into much detail, we understood the Bayes Filter&#39;s derivation, principles, implementation, and applications. We couldn&#39;t go into the math of motion and sensor models and could only give an introduction to different representations of the Bayes Filter. However, I hope you got a good premise of what these ideas bring to the table, and I encourage you to read and learn more about them.</p><p>If you have any questions or want to know about anything in more detail, don&#39;t hesitate to contact me via Linkedin. I&#39;ve linked my profile below.</p><p><a href="http://www.linkedin.com/in/vikram-setty">www.linkedin.com/in/vikram-setty</a></p><h4><strong>References</strong></h4><p>This blog&#39;s content is inspired by Dr. Wolfram Burgard&#39;s &#39;Introduction to Mobile Robotics (SS 2021)&#39; class at the University of Freiburg. Dr. Burgard is a pioneer of modern-day robotics and is responsible for a lot of the game-changing research that led to the development of present state-of-the-art SLAM techniques. You can find the link to the entire course posted online at the link attached below.</p><p><a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/">Introduction to Mobile Robotics — SS 2021 — Arbeitsgruppe: Autonome Intelligente Systeme</a></p><p>Other references include:</p><ol><li>[Figure 2] <a href="https://www.researchgate.net/figure/PUMA-Robot-dimensions-and-joint-angles_fig1_311953769">https://www.researchgate.net/figure/PUMA-Robot-dimensions-and-joint-angles_fig1_311953769</a></li><li>[Figure 3] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/04-sensors.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/04-sensors.pdf</a></li><li>[Figure 6] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/06-motion-models.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/06-motion-models.pdf</a></li><li>[Figure 7] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/06-motion-models.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/06-motion-models.pdf</a></li><li>[Figure 8] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/06-motion-models.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/06-motion-models.pdf</a></li><li>[Figure 10] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/07-sensor-models.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/07-sensor-models.pdf</a></li><li>[Figure 11] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/07-sensor-models.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/07-sensor-models.pdf</a></li><li>[Figure 13] <a href="http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/09-pf-mcl.pdf">http://ais.informatik.uni-freiburg.de/teaching/ss21/robotics/slides/09-pf-mcl.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f8b61afc1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Second Order ODEs Using Euler's Method & Python]]></title>
            <link>https://medium.com/@vikramsetty169/solving-second-order-odes-using-eulers-method-python-cb77abb89efe?source=rss-d56bd0023172------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb77abb89efe</guid>
            <category><![CDATA[eulers-method]]></category>
            <category><![CDATA[numerical-analysis]]></category>
            <category><![CDATA[differential-equations]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vikram Setty]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 10:28:45 GMT</pubDate>
            <atom:updated>2022-08-12T16:57:50.306Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Euler&#39;s (or the Euler-Cauchy/Point-Slope) Method is a well-known numerical technique usually used to approximate functions using their first-order ordinary differential equations (ODEs). However, with a bit of modification from its canonical form, it can also be used to approximate them using second-order ODEs. In this blog post, I discuss how this is possible by taking the example of the spring-mass equation under damping, a famous second-order ODE. Further, I&#39;ll show you how to code whatever equations I&#39;m writing in Python so you can verify the correctness of the method and apply it to your own applications!</em></p><p>Required prerequisites:</p><ol><li>Basic understanding of calculus</li><li>Familiarity with the spring-mass equation</li><li>Rudimentary knowledge of Python</li></ol><p><em>And that&#39;s it! Nothing much more than that!</em></p><h4><strong>Introduction to Euler&#39;s Method</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*NB56eys4o17SnSp1g69lsg.png" /><figcaption>Equation 1: first-order derivative</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*P8wqacZ7nnimyCbowdF5tQ.png" /><figcaption>Equation 2: Canonical Form of Euler&#39;s Method</figcaption></figure><p>The two equations above represent Euler&#39;s Method&#39;s most basic form. Nothing special, right? Even from a basic level of intuition, we can understand why these equations make sense. After all, we are just approximating the next data point to be the sum of the previous data point and the change over a small interval &#39;h.&#39; The smaller the value of &#39;h,&#39; the more accurate the solution is. However, a smaller &#39;h&#39; also implies more computation since you&#39;ll be using the same equation a more significant number of times over the same interval. So to decide the value of &#39;h,&#39; you&#39;ll have to find a trade-off between accuracy and computation, often dependent on the application.</p><p>However, if we think outside the box and change the equation slightly, we can obtainthe equation shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*dkE6MMP40QRilpWpWD6NZQ.png" /><figcaption>Equation 3: Alpha-Euler&#39;s Method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*zu38yfb25FuemQ2TNm1GFg.png" /></figure><p>Although this equation may look different from the previous ones, it&#39;s not. If you look closely enough, it&#39;s the same except for two changes. The first change is that we are using the first order derivatives in place of 𝜙, which is once again self-intuitive since these equations mirror the definition of a derivative. The second change is that we introduce a new variable 𝛼 that acts as a weight in giving importance to the previous and current data points&#39; derivatives. We can imagine the significance of this modification if we consider how first derivatives can change even in the smallest of intervals, even if not by much. Taking the weighted average of multiple closely accepted derivatives would more likely bring us closer to the real solution. However, the optimal value of 𝛼 (giving a solution closest to the actual one) can only be determined through continuous testing and fine-tuning and is problem-specific. We can call this equation the <strong>A<em>lpha Variation of Euler&#39;s Method</em></strong>.</p><h4><strong>The Spring-Mass Equation</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*j-q2r0D4Q3OASNb2N7VbDQ.png" /><figcaption>Figure 1: The Sping-Mass System</figcaption></figure><p>The figure above shows how the spring-mass system looks physically. It, along with its corresponding differential equation, should be familiar to most of you. Its governing second-order ODE looks as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*hsJ0uv60obZRM_4977Cw2w.png" /><figcaption>Equation 4: The Spring-Mass Equation</figcaption></figure><p>The equation above represents the spring-mass equation under the effect of a damper and a time-varying external force. The idea behind the ODE is simple: find the system&#39;s displacement as a function of time ie, x(t). In the equation, &#39;k&#39; represents the spring stiffness, &#39;c&#39; the damping coefficient, and &#39;m&#39; the system’s mass. Also, note that the spring used here is assumed to be massless.</p><p>Considering the homogenous scenario, or when f(t)=0 throughout, we end up with three different cases based on the value of the damping ratio defined as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*Fr2h8mpaMGGsBxUiurkzJw.png" /><figcaption>Equation 5: Damping Ratio Formula</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*NMy8X0LXMSxcBi7sBjWlwg.png" /><figcaption>Equation 6: Damping Conditions</figcaption></figure><h4><strong>Application of Euler&#39;s Method</strong></h4><p>Now that we&#39;ve covered the fundamentals of both Euler&#39;s Method and the spring-mass system, we can go into implementing whatever we&#39;ve learned to find x(t). Considering a generic case (not limited to homogenous/non-homogenous, underdamped/overdamped, etc.), we can write a series of equations to simplify the initially vague formula.</p><p>The equations below mirror the same formulas written initially with minor changes. For example, ‘y’ is replaced with ‘x’ , since ‘x’ is now our dependent variable, and ‘h’ is replaced with Δt since ‘t’ is now our independent variable with Δt representing a very small time period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*Lab3DZ7hmMlUMdB7OqpAWQ.png" /><figcaption>Equations 7–11: Deriving Xn+1</figcaption></figure><p>Pretty simple I hope! In the end, all we’re doing is applying Euler’s Method twice since we’re dealing with a second order ODE. The equations may look big but are actually quite straightforward. If we were to use these equations to implement the solution through code in Python, it would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*109euSH94OeomrDFBDO4cQ.png" /></figure><p>Though the notations might be slightly different from the ones used in the equations, the principle remains the same. Throughout a specified time interval ranging from ‘t_i’ to ‘t_f’, we iteratively calculate each data point after travaersing a time Δt.</p><h4><strong>Cross-Checking Solution Corectness</strong></h4><p>Consider a homogenous system, where f(t)=0. If we want to prove that our implementation of Euler’s Method is accurate, we need to compare our results with a solution based off theoretical equations. For a homogenous and damped spring-mass system which is underdamped, the theoretical solutions looks as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*u2ACTj04nDbix6ciVnWvWQ.png" /><figcaption>Equation 12: Underdamped &amp; Homogenous Spring-Mass Equation</figcaption></figure><p>All the terms in the equation represent terms used in normal notation. If we are to use this formula and compare its result with the implementation for Euler’s Method we just came up with, we can run the code the blocks shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*UQCyteoPtDHY3hVbY488UA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*tPY1oEaKXZhzx1Aax4971g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*bIUVPTdzJYm7MojdzkIF3A.png" /></figure><p>Graphically, both solutions look exactly the same! This proves that whatever we derived and implemented is true. of course, this solution is for a particular set of values of initial conditions and parameters, and accuracy levels could change when these values change.</p><p>It’s also important to note that they match so perfectly because we chose a really small value of Δt. Larger values are guaranteed to give less accurate solutions. We can verify that as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*RsDv0Vr_4lJbsvTMKCQHGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*nZf_TIrxnfGwC5h6fuVafg.png" /></figure><p>Just as predicted, as Δt increases, the curve looks less and less accurate. Another thing we could do is vary the value of alpha between 0 and 1 and see the effect of the same on the curve. However, for this particular situation, the value of alpha has little significance and its variation won’t affect solution correctness significantly.</p><p>If we were to verify our work for non-homogenous equations, then we’d have to take f(t) to be something other than 0. For example, consider taking x(t)=1+Sin(Wn*t) to have a non-zero f(t) (we’re initializing x(t)as 1+Sin(Wn*t) instead of f(t) since we eventually want to plot x(t) and we’d know what type of graph we could expect). By plotting our solutions and comparing them, we can arrive at the graphs below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*qKjRtJy4b4NOD_f_BtSxXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*kiu06D30Ie8dR1jDDgSOow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*lvhllf8Af_c7WaQ-tkOAeA.png" /></figure><p>Again, our implementation of Euler’s Method seems to be working really well since the plots almost overlap entirely!</p><p>If you’d like to have a better look at the code and play around with it, go check out my github repository below which has everything laid out step by step.</p><p><a href="https://github.com/vikrams169/Using-Eulers-Method-to-Solve-the-Spring-Mass-Equation">GitHub - vikrams169/Using-Eulers-Method-to-Solve-the-Spring-Mass-Equation: A variable alpha technique to apply Euler&#39;s Method to solve the Second Order ODE of the Famous Spring Mass Equation</a></p><p>If you have any questions, please feel free to reach out to me via Linkedin. I’ve linked my profile down below.</p><p><a href="http://www.linkedin.com/in/vikram-setty">www.linkedin.com/in/vikram-setty</a></p><h4><strong>References</strong></h4><ol><li>The cananoical forms of Euler’s Method were referenced from the 7th Edition of ‘Numerical Methods for Engineers’ by Steven C. Chapra and Raymond P. Canale.</li><li>The picture depicting the spring-mass system under the action of a damper and time-varying force f(t) is taken from <a href="https://physics.stackexchange.com/questions/335951/compute-the-damping-value-for-two-masses-in-a-harmonic-oscillator">https://physics.stackexchange.com/questions/335951/compute-the-damping-value-for-two-masses-in-a-harmonic-oscillator</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb77abb89efe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>