<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://atharvabhagwat.dev/feed.xml" rel="self" type="application/atom+xml" /><link href="https://atharvabhagwat.dev/" rel="alternate" type="text/html" /><updated>2026-12-01T20:25:19+00:00</updated><id>https://atharvabhagwat.dev/feed.xml</id><title type="html">Atharva Bhagwat</title><author><name>Atharva Bhagwat</name><email>atharva.bhagwat42@gmail.com</email></author><entry><title type="html">Introduction to Bioinformatics Programming in Python</title><link href="https://atharvabhagwat.dev/articles/intro-to-python-biosci" rel="alternate" type="text/html" title="Introduction to Bioinformatics Programming in Python" /><published>2026-11-04T00:00:00+00:00</published><updated>2026-11-04T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/articles/introduction-to-bioinformatics-programming-in-python</id><content type="html" xml:base="https://atharvabhagwat.dev/articles/intro-to-python-biosci"><![CDATA[<div class="quest" id="quest" data-total-stars="30" data-total-ex="0" data-hide-total="1" data-hash-map="{&quot;12&quot;: &quot;/articles/intro-to-python-biosci/python-building-blocks&quot;, &quot;1&quot;: &quot;/articles/intro-to-python-biosci/notebooks-text-loops&quot;, &quot;2&quot;: &quot;/articles/intro-to-python-biosci/error-messages&quot;, &quot;3&quot;: &quot;/articles/intro-to-python-biosci/pandas-tables&quot;, &quot;4&quot;: &quot;/articles/intro-to-python-biosci/calculations-groups&quot;, &quot;5&quot;: &quot;/articles/intro-to-python-biosci/functions&quot;, &quot;7&quot;: &quot;/articles/intro-to-python-biosci/checking-real-data&quot;, &quot;8&quot;: &quot;/articles/intro-to-python-biosci/summarising-regions&quot;, &quot;9&quot;: &quot;/articles/intro-to-python-biosci/plotting-distributions&quot;, &quot;10&quot;: &quot;/articles/intro-to-python-biosci/more-plots&quot;, &quot;11&quot;: &quot;/articles/intro-to-python-biosci/checking-conclusion&quot;, &quot;0&quot;: &quot;/articles/intro-to-python-biosci/computer-setup&quot;, &quot;6&quot;: &quot;/articles/intro-to-python-biosci/organising-project&quot;, &quot;13&quot;: &quot;/articles/intro-to-python-biosci/running-scripts&quot;, &quot;15&quot;: &quot;/articles/intro-to-python-biosci/biopython-extra&quot;}">
<link rel="stylesheet" href="/assets/css/quest.css" />
<script src="/assets/js/quest-answers.js" defer=""></script>
<script src="/assets/js/quest.js" defer=""></script>
<div class="q-bar is-quiet"><span class="q-bar-stars"><span class="q-glyph" aria-hidden="true">&#9733;</span><span id="q-bar-count">0</span></span><span class="q-bar-rank" id="q-bar-rank"></span><span class="q-bar-links"><a href="/articles/intro-to-python-biosci/plan">Plan</a><button type="button" class="q-reset">Reset stars</button></span></div>
<section class="q-start"><p class="q-start-lede">Learn to analyse biological data with Python.</p><p class="q-start-text">You do not need any experience. We start with a short, friendly first exercise that runs in your browser. There is nothing to install.</p><h3>Reading Python is like reading English</h3><p>Code is a list of instructions the computer follows from top to bottom, like a recipe. Read each note (the line starting with <code>#</code>), then the code under it. They say the same thing.</p><div class="qcode"><div class="qcode-bar"><span class="qcode-name">English in the notes, Python in the code</span><button class="qcopy" type="button">Copy</button></div><pre><code><span class="c1"># Say hello.</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Hello"</span><span class="p">)</span>

<span class="c1"># Remember that the age is 25.</span>
<span class="n">age</span> <span class="o">=</span> <span class="mi">25</span>

<span class="c1"># If the age is more than 18, say "adult".</span>
<span class="k">if</span> <span class="n">age</span> <span class="o">&gt;</span> <span class="mi">18</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">"adult"</span><span class="p">)</span></code></pre></div><p class="q-colab-row"><a class="q-colab q-colab-big" href="https://colab.research.google.com/drive/1REd93Zy0POwOcKR8x0L3EVD44wNbcDE9" target="_blank" rel="noopener">Start the 10-minute warm-up</a><span class="q-colab-note">Opens in Google Colab. You need a free Google account. Once it opens, choose File, then Save a copy in Drive.</span></p><div class="q-puzzles"><div class="q-puzzle" data-qid="s14p1" data-part="1" data-done-msg="You did it. That was real code. Your plan is ready just below." data-kind="num" data-value="0.375" data-dp="3"><div class="q-puzzle-head"><span class="q-star" aria-hidden="true">&#9733;</span><h4>First star</h4></div><div class="q-puzzle-body"><p>Back from the warm-up? Type the GC fraction you wrote down, rounded to 3 decimal places.</p></div><div class="q-answer"><label class="q-prompt" for="in-s14p1">answer =</label><input id="in-s14p1" type="text" inputmode="decimal" spellcheck="false" autocomplete="off" autocapitalize="off" placeholder="e.g. 0.123" /><button type="button" class="q-check">Check answer</button></div><p class="q-feedback" role="status" aria-live="polite"></p><details class="q-details q-help"><summary>Stuck? Get a nudge</summary><p>It is the number printed by the last cell, the one with <code>round(gc, 3)</code>. Run that cell again in the notebook if you need to.</p></details></div></div><div class="q-start-after" data-reveal-on="s14p1" hidden=""><a class="q-colab q-colab-big" href="/articles/intro-to-python-biosci/plan">See the plan</a><span class="q-colab-note">Everything after this is optional. You choose what to do and when.</span></div><div class="q-start-trail" data-show-when-stars="1" hidden=""><h3>Your progress</h3><p class="q-start-text">Pick any stage to jump to it. Stars are saved in this browser.</p><div class="q-nb"><div class="q-nb-row q-nb-out"><div class="q-nb-label">Out[1]:</div><div class="q-nb-body"><table class="q-df q-df-plan"><thead><tr><th></th><th class="q-df-name">stage</th><th>star1</th><th>star2</th><th>star3</th></tr></thead><tbody><tr class="q-df-part"><th colspan="5" scope="colgroup">Part 1: learn by running code (all in Colab, nothing to install)</th></tr><tr><th scope="row">start</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci">Warm-up</a><span class="q-df-sub">reading code like English, in about 10 minutes</span></td><td data-cell="s14p1"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">0</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/python-building-blocks">Python building blocks</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">values, lists, dictionaries, libraries, tables &middot; about 60 min</span></td><td data-cell="s12p1"><span class="q-nan">NaN</span></td><td data-cell="s12p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">1</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/notebooks-text-loops">Notebooks, text and loops</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">cells, kernel memory, text, loops &middot; about 45 min</span></td><td data-cell="s1p1"><span class="q-nan">NaN</span></td><td data-cell="s1p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">2</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/error-messages">Reading error messages</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">what error messages mean and what to do &middot; about 30 min</span></td><td data-cell="s2p1"><span class="q-nan">NaN</span></td><td data-cell="s2p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">3</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/pandas-tables">Tables with pandas</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">load a table, pick columns, filter rows &middot; about 40 min</span></td><td data-cell="s3p1"><span class="q-nan">NaN</span></td><td data-cell="s3p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">4</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/calculations-groups">Calculations and groups</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">new columns, groups, pivots &middot; about 40 min</span></td><td data-cell="s4p1"><span class="q-nan">NaN</span></td><td data-cell="s4p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">5</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/functions">Writing functions</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">reuse code with a function &middot; about 40 min</span></td><td data-cell="s5p1"><span class="q-nan">NaN</span></td><td data-cell="s5p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">6</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/checking-real-data">Checking real data</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">look at real data before trusting it &middot; about 45 min</span></td><td data-cell="s7p1"><span class="q-nan">NaN</span></td><td data-cell="s7p2"><span class="q-nan">NaN</span></td><td data-cell="s7p3"><span class="q-nan">NaN</span></td></tr><tr><th scope="row">7</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/summarising-regions">Summarising by region</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">group, summarise, interpret &middot; about 40 min</span></td><td data-cell="s8p1"><span class="q-nan">NaN</span></td><td data-cell="s8p2"><span class="q-nan">NaN</span></td><td data-cell="s8p3"><span class="q-nan">NaN</span></td></tr><tr><th scope="row">8</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/plotting-distributions">Plotting distributions</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">histogram, box plot, violin, strip, count &middot; about 40 min</span></td><td data-cell="s9p1"><span class="q-nan">NaN</span></td><td data-cell="s9p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">9</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/more-plots">More plots</a> <span class="q-badge is-optional">Optional</span><span class="q-df-sub">scatter, line, heatmap &middot; about 45 min</span></td><td data-cell="s10p1"><span class="q-nan">NaN</span></td><td data-cell="s10p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">10</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/checking-conclusion">Checking your conclusion</a> <span class="q-badge is-core">Core</span><span class="q-df-sub">does the answer survive a different rule? &middot; about 40 min</span></td><td data-cell="s11p1"><span class="q-nan">NaN</span></td><td data-cell="s11p2"><span class="q-nan">NaN</span></td><td data-cell="s11p3"><span class="q-nan">NaN</span></td></tr><tr class="q-df-part"><th colspan="5" scope="colgroup">Part 2: your own computer, then the cluster</th></tr><tr><th scope="row">11</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/computer-setup">Setting up your computer</a> <span class="q-badge is-optional">Level up</span><span class="q-df-sub">terminal, Miniconda, environments, VS Code &middot; about 60 min</span></td><td data-cell="s0p1"><span class="q-nan">NaN</span></td><td data-cell="s0p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">12</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/organising-project">Organising a project</a> <span class="q-badge is-optional">Level up</span><span class="q-df-sub">folders, downloads, checksums, helper files &middot; about 45 min</span></td><td data-cell="s6p1"><span class="q-nan">NaN</span></td><td data-cell="s6p2"><span class="q-nan">NaN</span></td><td class="q-df-none">&ndash;</td></tr><tr><th scope="row">13</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/running-scripts">Running a script</a> <span class="q-badge is-optional">Level up</span><span class="q-df-sub">one command that rebuilds a result &middot; about 30 min</span></td><td class="q-df-none">&ndash;</td><td class="q-df-none">&ndash;</td><td class="q-df-none">&ndash;</td></tr><tr class="q-df-part"><th colspan="5" scope="colgroup">Extra</th></tr><tr><th scope="row">extra</th><td class="q-df-name"><a href="/articles/intro-to-python-biosci/biopython-extra">DNA sequences with Biopython</a> <span class="q-badge is-optional">Optional</span><span class="q-df-sub">translate and read sequence files &middot; about 40 min</span></td><td class="q-df-none">&ndash;</td><td class="q-df-none">&ndash;</td><td class="q-df-none">&ndash;</td></tr></tbody></table></div></div></div></div><p class="q-start-faq">Already know some Python? <a href="/articles/intro-to-python-biosci/faq">Where should I start?</a></p></section>
<div class="q-credits"><p class="q-credit-line">Special thanks to <a href="https://github.com/itsjustnilay" target="_blank" rel="noopener">Nilay</a>!</p><button type="button" class="q-reset">Reset all stars on this browser</button></div>
</div>]]></content><author><name>Atharva Bhagwat</name></author><category term="articles" /><summary type="html"><![CDATA[&#9733;0PlanReset stars Learn to analyse biological data with Python.You do not need any experience. We start with a short, friendly first exercise that runs in your browser. There is nothing to install.Reading Python is like reading EnglishCode is a list of instructions the computer follows from top to bottom, like a recipe. Read each note (the line starting with #), then the code under it. They say the same thing.English in the notes, Python in the codeCopy# Say hello. print("Hello") # Remember that the age is 25. age = 25 # If the age is more than 18, say "adult". if age &gt; 18: print("adult")Start the 10-minute warm-upOpens in Google Colab. You need a free Google account. Once it opens, choose File, then Save a copy in Drive.&#9733;First starBack from the warm-up? Type the GC fraction you wrote down, rounded to 3 decimal places.answer =Check answerStuck? Get a nudgeIt is the number printed by the last cell, the one with round(gc, 3). Run that cell again in the notebook if you need to.See the planEverything after this is optional. You choose what to do and when.Your progressPick any stage to jump to it. Stars are saved in this browser.Out[1]:stagestar1star2star3Part 1: learn by running code (all in Colab, nothing to install)startWarm-upreading code like English, in about 10 minutesNaN&ndash;&ndash;0Python building blocks Corevalues, lists, dictionaries, libraries, tables &middot; about 60 minNaNNaN&ndash;1Notebooks, text and loops Corecells, kernel memory, text, loops &middot; about 45 minNaNNaN&ndash;2Reading error messages Corewhat error messages mean and what to do &middot; about 30 minNaNNaN&ndash;3Tables with pandas Coreload a table, pick columns, filter rows &middot; about 40 minNaNNaN&ndash;4Calculations and groups Corenew columns, groups, pivots &middot; about 40 minNaNNaN&ndash;5Writing functions Corereuse code with a function &middot; about 40 minNaNNaN&ndash;6Checking real data Corelook at real data before trusting it &middot; about 45 minNaNNaNNaN7Summarising by region Coregroup, summarise, interpret &middot; about 40 minNaNNaNNaN8Plotting distributions Corehistogram, box plot, violin, strip, count &middot; about 40 minNaNNaN&ndash;9More plots Optionalscatter, line, heatmap &middot; about 45 minNaNNaN&ndash;10Checking your conclusion Coredoes the answer survive a different rule? &middot; about 40 minNaNNaNNaNPart 2: your own computer, then the cluster11Setting up your computer Level upterminal, Miniconda, environments, VS Code &middot; about 60 minNaNNaN&ndash;12Organising a project Level upfolders, downloads, checksums, helper files &middot; about 45 minNaNNaN&ndash;13Running a script Level upone command that rebuilds a result &middot; about 30 min&ndash;&ndash;&ndash;ExtraextraDNA sequences with Biopython Optionaltranslate and read sequence files &middot; about 40 min&ndash;&ndash;&ndash;Already know some Python? Where should I start? Special thanks to Nilay!Reset all stars on this browser]]></summary></entry><entry><title type="html">Case #006: The Vanishing Diamond</title><link href="https://atharvabhagwat.dev/projects/sqlnoir-case-6" rel="alternate" type="text/html" title="Case #006: The Vanishing Diamond" /><published>2025-05-25T00:00:00+00:00</published><updated>2025-05-25T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/projects/sqlnoir-case-6</id><content type="html" xml:base="https://atharvabhagwat.dev/projects/sqlnoir-case-6"><![CDATA[<!-- markdownlint-disable MD032 MD033 -->

<p>At Miami’s prestigious Fontainebleau Hotel charity gala, the famous “Heart of Atlantis” diamond necklace suddenly disappeared from its display.</p>

<p>Reading the case description these are the <strong>clues</strong> we can pick up:</p>

<ul>
  <li>Location: <strong>Fontainebleau Hotel</strong></li>
  <li>Famous “Heart of Atlantis” diamond necklace suddenly disappeared; Type of crime: <strong>theft</strong></li>
</ul>

<h2 id="going-over-the-schema">Going over the schema</h2>

<p>There are 6 tables:</p>
<ul>
  <li>crime_scene:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>guest:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>attire_registry:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>guest_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">guest</code></li>
    </ul>
  </li>
  <li>witness_statements:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>guest_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">guest</code></li>
    </ul>
  </li>
  <li>final_interviews:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>guest_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">guest</code></li>
    </ul>
  </li>
  <li>marina_rentals:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>renter_guest_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">guest</code></li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/articles/sqlnoir_case6/schema.png" alt="case6_schema" /></p>

<h2 id="investigation">Investigation</h2>

<p>We start by looking through all the crime scenes where the <code class="language-html highlighter-rouge">location</code> has Fontainebleau Hotel.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">crime_scene</span> <span class="k">where</span> <span class="k">location</span> <span class="k">like</span> <span class="s1">'%Fontainebleau Hotel%'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>The Heart of Atlantis necklace disappeared. Many guests were questioned but only two of them gave valuable clues. One of them is a really famous actor. The other one is a woman who works as a consultant for a big company and her first name ends with “an”.</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>witness #1 is a famous actor</li>
  <li>witness #2 is a woman who works as a consultant and her first name ends with ‘an’</li>
</ul>

<p>Let us look at witness statements using the witness descriptions we just got. We can do this by using a <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">guest</code> and <code class="language-html highlighter-rouge">witness_statements</code> tables.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">guest_id</span><span class="p">,</span> <span class="n">guest</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">clue</span> <span class="k">from</span> <span class="n">witness_statements</span> 
<span class="k">join</span> <span class="n">guest</span> <span class="k">on</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">guest_id</span> <span class="o">=</span> <span class="n">guest</span><span class="p">.</span><span class="n">id</span> 
<span class="k">where</span> <span class="n">guest</span><span class="p">.</span><span class="n">occupation</span> <span class="k">like</span> <span class="s1">'%Actor%'</span> <span class="k">or</span> 
<span class="p">(</span><span class="n">guest</span><span class="p">.</span><span class="n">occupation</span> <span class="k">like</span> <span class="s1">'%consultant%'</span> <span class="k">and</span> <span class="n">guest</span><span class="p">.</span><span class="n">name</span> <span class="k">like</span> <span class="s1">'%an %'</span><span class="p">);</span>
</code></pre></div></div>

<blockquote>
  <p>I overheard someone say, “Meet me at the marina, dock 3.
I saw someone holding an invitation ending with “-R”. He was wearing a navy suit and a white tie.</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Marina dock 3 is relevant</li>
  <li>Invitation ending with ‘-R’ wearing a navy suit and white tie</li>
</ul>

<p>Let’s look at marina rentals using the other clues as filters. We can use <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">guest</code>, <code class="language-html highlighter-rouge">attire_registry</code>, and <code class="language-html highlighter-rouge">marina_rentals</code>.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">guest</span><span class="p">.</span><span class="n">id</span><span class="p">,</span> <span class="n">guest</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="n">guest</span><span class="p">.</span><span class="n">invitation_code</span><span class="p">,</span> <span class="n">attire_registry</span><span class="p">.</span><span class="n">note</span><span class="p">,</span> 
<span class="n">marina_rentals</span><span class="p">.</span><span class="n">dock_number</span><span class="p">,</span> <span class="n">marina_rentals</span><span class="p">.</span><span class="n">rental_date</span><span class="p">,</span> <span class="n">marina_rentals</span><span class="p">.</span><span class="n">boat_name</span> <span class="k">from</span> <span class="n">guest</span> 
<span class="k">join</span> <span class="n">attire_registry</span> <span class="k">on</span> <span class="n">guest</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">attire_registry</span><span class="p">.</span><span class="n">guest_id</span> 
<span class="k">join</span> <span class="n">marina_rentals</span> <span class="k">on</span> <span class="n">guest</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">marina_rentals</span><span class="p">.</span><span class="n">renter_guest_id</span>  
<span class="k">where</span> <span class="n">attire_registry</span><span class="p">.</span><span class="n">note</span> <span class="k">like</span> <span class="s1">'%navy suit, white tie%'</span> <span class="k">and</span> 
<span class="n">guest</span><span class="p">.</span><span class="n">invitation_code</span> <span class="k">like</span> <span class="s1">'%-R'</span><span class="p">;</span>
</code></pre></div></div>

<p>We only get one entry. This has to be our guy. Let’s look at the final interview.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">guest</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="n">final_interviews</span><span class="p">.</span><span class="n">confession</span> <span class="k">from</span> <span class="n">guest</span> 
<span class="k">join</span> <span class="n">final_interviews</span> <span class="k">on</span> <span class="n">guest</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">final_interviews</span><span class="p">.</span><span class="n">guest_id</span> 
<span class="k">where</span> <span class="n">guest</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="mi">105</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>“I was the one who took the crystal. I guess I need a lawyer now?” ~ Mike Manning</p>
</blockquote>

<p>We got him. Too bad the spotlight never left the “Heart of Atlantis”.</p>

<hr />

<p>Thank you <a href="https://github.com/hristo2612">Chris</a> for creating <a href="https://www.sqlnoir.com/">SQL Noir</a>.</p>]]></content><author><name>Atharva Bhagwat</name></author><category term="projects" /><summary type="html"><![CDATA[At Miami’s prestigious Fontainebleau Hotel charity gala, the famous “Heart of Atlantis” diamond necklace suddenly disappeared from its display. Reading the case description these are the clues we can pick up: Location: Fontainebleau Hotel Famous “Heart of Atlantis” diamond necklace suddenly disappeared; Type of crime: theft Going over the schema There are 6 tables: crime_scene: id: PRIMARY KEY guest: id: PRIMARY KEY attire_registry: id: PRIMARY KEY guest_id: FOREIGN KEY referencing id in guest witness_statements: id: PRIMARY KEY guest_id: FOREIGN KEY referencing id in guest final_interviews: id: PRIMARY KEY guest_id: FOREIGN KEY referencing id in guest marina_rentals: id: PRIMARY KEY renter_guest_id: FOREIGN KEY referencing id in guest Investigation We start by looking through all the crime scenes where the location has Fontainebleau Hotel. select * from crime_scene where location like '%Fontainebleau Hotel%'; The Heart of Atlantis necklace disappeared. Many guests were questioned but only two of them gave valuable clues. One of them is a really famous actor. The other one is a woman who works as a consultant for a big company and her first name ends with “an”. New clues: witness #1 is a famous actor witness #2 is a woman who works as a consultant and her first name ends with ‘an’ Let us look at witness statements using the witness descriptions we just got. We can do this by using a JOIN on guest and witness_statements tables. select witness_statements.guest_id, guest.name, witness_statements.clue from witness_statements join guest on witness_statements.guest_id = guest.id where guest.occupation like '%Actor%' or (guest.occupation like '%consultant%' and guest.name like '%an %'); I overheard someone say, “Meet me at the marina, dock 3. I saw someone holding an invitation ending with “-R”. He was wearing a navy suit and a white tie. New clues: Marina dock 3 is relevant Invitation ending with ‘-R’ wearing a navy suit and white tie Let’s look at marina rentals using the other clues as filters. We can use JOIN on guest, attire_registry, and marina_rentals. select guest.id, guest.name, guest.invitation_code, attire_registry.note, marina_rentals.dock_number, marina_rentals.rental_date, marina_rentals.boat_name from guest join attire_registry on guest.id = attire_registry.guest_id join marina_rentals on guest.id = marina_rentals.renter_guest_id where attire_registry.note like '%navy suit, white tie%' and guest.invitation_code like '%-R'; We only get one entry. This has to be our guy. Let’s look at the final interview. select guest.name, final_interviews.confession from guest join final_interviews on guest.id = final_interviews.guest_id where guest.id = 105; “I was the one who took the crystal. I guess I need a lawyer now?” ~ Mike Manning We got him. Too bad the spotlight never left the “Heart of Atlantis”. Thank you Chris for creating SQL Noir.]]></summary></entry><entry><title type="html">Case #005: The Silicon Sabotage</title><link href="https://atharvabhagwat.dev/projects/sqlnoir-case-5" rel="alternate" type="text/html" title="Case #005: The Silicon Sabotage" /><published>2025-05-24T00:00:00+00:00</published><updated>2025-05-24T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/projects/sqlnoir-case-5</id><content type="html" xml:base="https://atharvabhagwat.dev/projects/sqlnoir-case-5"><![CDATA[<!-- markdownlint-disable MD032 MD033 -->

<p>QuantumTech, Miami’s leading technology corporation, was about to unveil its groundbreaking microprocessor called “QuantaX.” Just hours before the reveal, the prototype was destroyed, and all research data was erased. Detectives suspect corporate espionage.</p>

<p>Reading the case description these are the <strong>clues</strong> we can pick up:</p>

<ul>
  <li>Location: <strong>QuantumTech</strong></li>
  <li>Prototype was destroyed, and all research data was erased; Type of crime: <strong>corporate espionage</strong></li>
</ul>

<h2 id="going-over-the-schema">Going over the schema</h2>

<p>There are 7 tables:</p>
<ul>
  <li>incident_reports:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>employee_records:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>witness_statements:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>incident_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">incident_reports</code></li>
      <li>emplotee_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">employee_records</code></li>
    </ul>
  </li>
  <li>facility_access_logs:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>employee_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">employee_records</code></li>
    </ul>
  </li>
  <li>computer_access_logs:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>employee_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">employee_records</code></li>
    </ul>
  </li>
  <li>keycard_access_logs:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>employee_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">employee_records</code></li>
    </ul>
  </li>
  <li>email_logs:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>sender_employee_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">employee_records</code></li>
      <li>recipient_employee_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">employee_records</code></li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/articles/sqlnoir_case5/schema.png" alt="case4_schema" /></p>

<h2 id="investigation">Investigation</h2>

<p>We start by looking through all the crime scenes where the <code class="language-html highlighter-rouge">location</code> has QuantumTech.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">incident_reports</span> <span class="k">where</span> <span class="k">location</span> <span class="k">like</span> <span class="s1">'%QuantumTech%'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>Prototype destroyed; data erased from servers.</p>
</blockquote>

<p>New <strong>clue</strong>:</p>
<ul>
  <li>Incident happened on <em>April 21, 1989</em></li>
</ul>

<p>Let us also look at witness statements for this crime. We can do this by using a <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">incident_reports</code> and <code class="language-html highlighter-rouge">witness_statements</code> tables.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">id</span><span class="p">,</span> <span class="n">witness_statements</span><span class="p">.</span><span class="k">statement</span> <span class="k">from</span> <span class="n">witness_statements</span> 
<span class="k">join</span> <span class="n">incident_reports</span> <span class="k">on</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">incident_id</span> <span class="o">=</span> <span class="n">incident_reports</span><span class="p">.</span><span class="n">id</span> 
<span class="k">where</span> <span class="k">location</span> <span class="k">like</span> <span class="s1">'%QuantumTech%'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>I heard someone mention a server in Helsinki.</p>
</blockquote>

<blockquote>
  <p>I saw someone holding a keycard marked QX- succeeded by a two-digit odd number.</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Server in Helsinki mentioned</li>
  <li>Keycard marked QX- succeeded by a two-digit odd number</li>
</ul>

<p>Using these clues we can find employees that access both the server and facility.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">employee_records</span> 
<span class="k">where</span> <span class="n">id</span> <span class="k">in</span> 
  <span class="p">(</span>
    <span class="k">select</span> <span class="n">employee_id</span> <span class="k">from</span> <span class="n">keycard_access_logs</span> 
    <span class="k">where</span> <span class="n">keycard_code</span> <span class="k">like</span> <span class="s1">'%QX-0__'</span> <span class="k">and</span> 
    <span class="n">SUBSTR</span><span class="p">(</span><span class="n">keycard_code</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="k">in</span> <span class="p">(</span><span class="s1">'1'</span><span class="p">,</span> <span class="s1">'3'</span><span class="p">,</span> <span class="s1">'5'</span><span class="p">,</span> <span class="s1">'7'</span><span class="p">,</span> <span class="s1">'9'</span><span class="p">)</span> <span class="k">and</span> 
    <span class="n">access_date</span> <span class="o">=</span> <span class="mi">19890421</span>
<span class="p">)</span> <span class="k">and</span> 
<span class="n">id</span> <span class="k">in</span> 
  <span class="p">(</span>
    <span class="k">select</span> <span class="n">employee_id</span> <span class="k">from</span> <span class="n">computer_access_logs</span> 
    <span class="k">where</span> <span class="n">server_location</span> <span class="o">=</span> <span class="s1">'Helsinki'</span> <span class="k">and</span> 
    <span class="n">access_date</span> <span class="o">=</span> <span class="mi">19890421</span>
<span class="p">);</span>
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>id</th>
      <th>employee_name</th>
      <th>department</th>
      <th>occupation</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>99</td>
      <td>Elizabeth Gordon</td>
      <td>Engineering</td>
      <td>Solutions Architect</td>
    </tr>
  </tbody>
</table>

<p>Only one name pops up. Let’s take a look at the email logs either to or from this person.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">email_logs</span> 
<span class="k">where</span> <span class="n">sender_employee_id</span> <span class="o">=</span> <span class="mi">99</span> <span class="k">or</span> 
<span class="n">recipient_employee_id</span> <span class="o">=</span> <span class="mi">99</span><span class="p">;</span>
</code></pre></div></div>

<p>Just 1 email recieved where the sender employee id is 263. Let’s follow this trail.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">email_logs</span> 
<span class="k">where</span> <span class="n">sender_employee_id</span> <span class="o">=</span> <span class="mi">263</span> <span class="k">or</span> 
<span class="n">recipient_employee_id</span> <span class="o">=</span> <span class="mi">263</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>L’s schedule puts her close enough, but we need her inside F18 before 9. Trigger a minor alert or routine checkup to send her in by 8:30. Make sure she logs the visit. That part matters.</p>
</blockquote>

<blockquote>
  <p>Unlock 18 quietly by 9. He’ll use his own credentials to access it shortly after L leaves. No questions. Just ensure the timing lines up. The trail will lead exactly where it needs to.</p>
</blockquote>

<p>Reading the first email it looks like someone is trying to frame Elizabeth Gordon. The send email will help us get to the actual culprit. Let’s look at facility logs for facility 18.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">facility_access_logs</span> <span class="k">where</span> <span class="n">facility_name</span> <span class="o">=</span> <span class="s1">'Facility 18'</span><span class="p">;</span>
</code></pre></div></div>

<p>Only two people accessed this facility in the morning. Elizabeth and an employee with id 297. That must be our guy.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">employee_records</span> <span class="k">where</span> <span class="n">id</span> <span class="o">=</span> <span class="mi">297</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>Hristo Bogoev, Principal Engineer</p>
</blockquote>

<p>We got him. At QuantumTech, the real glitch was human.</p>

<hr />

<p>Thank you <a href="https://github.com/hristo2612">Chris</a> for creating <a href="https://www.sqlnoir.com/">SQL Noir</a>.</p>]]></content><author><name>Atharva Bhagwat</name></author><category term="projects" /><summary type="html"><![CDATA[QuantumTech, Miami’s leading technology corporation, was about to unveil its groundbreaking microprocessor called “QuantaX.” Just hours before the reveal, the prototype was destroyed, and all research data was erased. Detectives suspect corporate espionage. Reading the case description these are the clues we can pick up: Location: QuantumTech Prototype was destroyed, and all research data was erased; Type of crime: corporate espionage Going over the schema There are 7 tables: incident_reports: id: PRIMARY KEY employee_records: id: PRIMARY KEY witness_statements: id: PRIMARY KEY incident_id: FOREIGN KEY referencing id in incident_reports emplotee_id: FOREIGN KEY referencing id in employee_records facility_access_logs: id: PRIMARY KEY employee_id: FOREIGN KEY referencing id in employee_records computer_access_logs: id: PRIMARY KEY employee_id: FOREIGN KEY referencing id in employee_records keycard_access_logs: id: PRIMARY KEY employee_id: FOREIGN KEY referencing id in employee_records email_logs: id: PRIMARY KEY sender_employee_id: FOREIGN KEY referencing id in employee_records recipient_employee_id: FOREIGN KEY referencing id in employee_records Investigation We start by looking through all the crime scenes where the location has QuantumTech. select * from incident_reports where location like '%QuantumTech%'; Prototype destroyed; data erased from servers. New clue: Incident happened on April 21, 1989 Let us also look at witness statements for this crime. We can do this by using a JOIN on incident_reports and witness_statements tables. select witness_statements.id, witness_statements.statement from witness_statements join incident_reports on witness_statements.incident_id = incident_reports.id where location like '%QuantumTech%'; I heard someone mention a server in Helsinki. I saw someone holding a keycard marked QX- succeeded by a two-digit odd number. New clues: Server in Helsinki mentioned Keycard marked QX- succeeded by a two-digit odd number Using these clues we can find employees that access both the server and facility. select * from employee_records where id in ( select employee_id from keycard_access_logs where keycard_code like '%QX-0__' and SUBSTR(keycard_code, -1, 1) in ('1', '3', '5', '7', '9') and access_date = 19890421 ) and id in ( select employee_id from computer_access_logs where server_location = 'Helsinki' and access_date = 19890421 ); id employee_name department occupation 99 Elizabeth Gordon Engineering Solutions Architect Only one name pops up. Let’s take a look at the email logs either to or from this person. select * from email_logs where sender_employee_id = 99 or recipient_employee_id = 99; Just 1 email recieved where the sender employee id is 263. Let’s follow this trail. select * from email_logs where sender_employee_id = 263 or recipient_employee_id = 263; L’s schedule puts her close enough, but we need her inside F18 before 9. Trigger a minor alert or routine checkup to send her in by 8:30. Make sure she logs the visit. That part matters. Unlock 18 quietly by 9. He’ll use his own credentials to access it shortly after L leaves. No questions. Just ensure the timing lines up. The trail will lead exactly where it needs to. Reading the first email it looks like someone is trying to frame Elizabeth Gordon. The send email will help us get to the actual culprit. Let’s look at facility logs for facility 18. select * from facility_access_logs where facility_name = 'Facility 18'; Only two people accessed this facility in the morning. Elizabeth and an employee with id 297. That must be our guy. select * from employee_records where id = 297; Hristo Bogoev, Principal Engineer We got him. At QuantumTech, the real glitch was human. Thank you Chris for creating SQL Noir.]]></summary></entry><entry><title type="html">Case #004: The Midnight Masquerade Murder</title><link href="https://atharvabhagwat.dev/projects/sqlnoir-case-4" rel="alternate" type="text/html" title="Case #004: The Midnight Masquerade Murder" /><published>2025-05-23T00:00:00+00:00</published><updated>2025-05-23T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/projects/sqlnoir-case-4</id><content type="html" xml:base="https://atharvabhagwat.dev/projects/sqlnoir-case-4"><![CDATA[<!-- markdownlint-disable MD032 MD033 -->

<p>On October 31, 1987, at a Coconut Grove mansion masked ball, Leonard Pierce was found dead in the garden.</p>

<p>Reading the case description these are the <strong>clues</strong> we can pick up:</p>

<ul>
  <li>Location: <strong>Coconut Grove mansion</strong></li>
  <li>Date: <strong>October 31, 1987</strong></li>
  <li>Leonard Pierce was found dead; Type of crime: <strong>murder</strong></li>
</ul>

<h2 id="going-over-the-schema">Going over the schema</h2>

<p>There are 9 tables:</p>
<ul>
  <li>crime_scene:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>person:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>witness_statements:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>crime_scene_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">crime_scene</code></li>
      <li>witness_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>final_interviews:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>vehicle_registry:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>catering_orders:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>phone_records:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>caller_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
      <li>recipient_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>hotel_checkins:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>surveillance_records:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>hotel_checkin_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">hotel_checkins</code></li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/articles/sqlnoir_case4/schema.png" alt="case4_schema" /></p>

<h2 id="investigation">Investigation</h2>

<p>We start by looking through all the crime scenes where the <code class="language-html highlighter-rouge">location</code> has Coconut Grove and <code class="language-html highlighter-rouge">date</code> is October 31, 1987.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">crime_scene</span> <span class="k">where</span> <span class="nb">date</span> <span class="o">=</span> <span class="mi">19871031</span> <span class="k">and</span> <span class="k">location</span> <span class="k">like</span> <span class="s1">'%Coconut Grove%'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>During a masked ball, a body was found in the garden. Witnesses mentioned a hotel booking and suspicious phone activity.</p>
</blockquote>

<p>Let us also look at witness statements for this crime. We can do this by using a <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">crime_scene</code> and <code class="language-html highlighter-rouge">witness_statements</code> tables.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">witness_id</span><span class="p">,</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">clue</span> <span class="k">from</span> <span class="n">witness_statements</span> 
<span class="k">join</span> <span class="n">crime_scene</span> <span class="k">on</span> <span class="n">witness_statements</span><span class="p">.</span><span class="n">crime_scene_id</span> <span class="o">=</span> <span class="n">crime_scene</span><span class="p">.</span><span class="n">id</span> 
<span class="k">where</span> <span class="n">crime_scene</span><span class="p">.</span><span class="nb">date</span> <span class="o">=</span> <span class="mi">19871031</span> <span class="k">and</span> 
<span class="n">crime_scene</span><span class="p">.</span><span class="k">location</span> <span class="k">like</span> <span class="s1">'%Coconut Grove%'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>I overheard a booking at The Grand Regency.</p>
</blockquote>

<blockquote>
  <p>I noticed someone at the front desk discussing Room 707 for a reservation made yesterday.</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Hotel booking at <em>The Grand Regency</em></li>
  <li>Room <em>707</em> booked on <em>October 30, 1987</em></li>
</ul>

<p>We look into all the surveillance records for hotel checkins at The Grand Regency for room 707 on October 30, 1987.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">surveillance_records</span><span class="p">.</span><span class="n">id</span><span class="p">,</span> <span class="n">surveillance_records</span><span class="p">.</span><span class="n">hotel_checkin_id</span><span class="p">,</span> 
<span class="n">surveillance_records</span><span class="p">.</span><span class="n">note</span> <span class="k">from</span> <span class="n">surveillance_records</span> 
<span class="k">join</span> <span class="n">hotel_checkins</span> <span class="k">on</span> <span class="n">surveillance_records</span><span class="p">.</span><span class="n">hotel_checkin_id</span> <span class="o">=</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">id</span>
<span class="k">where</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">hotel_name</span> <span class="o">=</span> <span class="s1">'The Grand Regency'</span> <span class="k">and</span> 
<span class="n">hotel_checkins</span><span class="p">.</span><span class="n">room_number</span> <span class="o">=</span> <span class="mi">707</span> <span class="k">and</span>
<span class="n">hotel_checkins</span><span class="p">.</span><span class="n">check_in_date</span> <span class="o">=</span> <span class="mi">19871030</span> <span class="k">and</span>
<span class="n">surveillance_records</span><span class="p">.</span><span class="n">note</span> <span class="k">is</span> <span class="k">not</span> <span class="k">NULL</span><span class="p">;</span>
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>hotel_checkin_id</th>
      <th>note</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>119</td>
      <td>Subject was overheard yelling on a phone: “Did you kill him?”</td>
    </tr>
  </tbody>
</table>

<p>We can look at hotel checkins for id 119 and see which person checked in.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">hotel_checkins</span> <span class="k">where</span> <span class="n">id</span> <span class="o">=</span> <span class="mi">119</span><span class="p">;</span>
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>id</th>
      <th>person_id</th>
      <th>hotel_name</th>
      <th>check_in_date</th>
      <th>room_number</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>119</td>
      <td>11</td>
      <td>The Grand Regency</td>
      <td>19871030</td>
      <td>707</td>
    </tr>
  </tbody>
</table>

<p>We now look into the phone records for person id 11. <em>(Query below also looks at phone records for person id 58 as they are the recipient of the call)</em></p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">phone_records</span> <span class="k">where</span> <span class="n">caller_id</span> <span class="k">in</span> <span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">58</span><span class="p">)</span> <span class="k">or</span> <span class="n">recipient_id</span> <span class="k">in</span> <span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">58</span><span class="p">);</span>
</code></pre></div></div>

<blockquote>
  <p>“Why did you kill him, bro? You should have left the carpenter do it himself!”</p>
</blockquote>

<blockquote>
  <p>“I will do it. Only if you give me that nice Lambo of yours.”</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Suspect maybe be a carpenter</li>
  <li>Suspect owns a Lamborghini</li>
</ul>

<p>We can use <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">person</code> and <code class="language-html highlighter-rouge">vehicle_registry</code> to find our suspect.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">vehicle_registry</span> 
<span class="k">join</span> <span class="n">person</span> <span class="k">on</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">vehicle_registry</span><span class="p">.</span><span class="n">person_id</span> 
<span class="k">where</span> <span class="n">car_make</span> <span class="o">=</span> <span class="s1">'Lamborghini'</span> <span class="k">and</span> 
<span class="n">person</span><span class="p">.</span><span class="n">occupation</span> <span class="k">like</span> <span class="s1">'carpenter'</span><span class="p">;</span>
</code></pre></div></div>

<p><em>Marco Santos</em> is the only name which pops up. Let us look at final interview for this person.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">final_interviews</span>
<span class="k">where</span> <span class="n">person_id</span> <span class="o">=</span> <span class="mi">97</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>“I ordered the hit. It was me. You caught me.” ~ Marco Santos</p>
</blockquote>

<p>We got him. The mask slipped.</p>

<hr />

<p>Thank you <a href="https://github.com/hristo2612">Chris</a> for creating <a href="https://www.sqlnoir.com/">SQL Noir</a>.</p>]]></content><author><name>Atharva Bhagwat</name></author><category term="projects" /><summary type="html"><![CDATA[On October 31, 1987, at a Coconut Grove mansion masked ball, Leonard Pierce was found dead in the garden. Reading the case description these are the clues we can pick up: Location: Coconut Grove mansion Date: October 31, 1987 Leonard Pierce was found dead; Type of crime: murder Going over the schema There are 9 tables: crime_scene: id: PRIMARY KEY person: id: PRIMARY KEY witness_statements: id: PRIMARY KEY crime_scene_id: FOREIGN KEY referencing id in crime_scene witness_id: FOREIGN KEY referencing id in person final_interviews: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person vehicle_registry: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person catering_orders: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person phone_records: id: PRIMARY KEY caller_id: FOREIGN KEY referencing id in person recipient_id: FOREIGN KEY referencing id in person hotel_checkins: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person surveillance_records: id: PRIMARY KEY hotel_checkin_id: FOREIGN KEY referencing id in hotel_checkins Investigation We start by looking through all the crime scenes where the location has Coconut Grove and date is October 31, 1987. select * from crime_scene where date = 19871031 and location like '%Coconut Grove%'; During a masked ball, a body was found in the garden. Witnesses mentioned a hotel booking and suspicious phone activity. Let us also look at witness statements for this crime. We can do this by using a JOIN on crime_scene and witness_statements tables. select witness_statements.witness_id, witness_statements.clue from witness_statements join crime_scene on witness_statements.crime_scene_id = crime_scene.id where crime_scene.date = 19871031 and crime_scene.location like '%Coconut Grove%'; I overheard a booking at The Grand Regency. I noticed someone at the front desk discussing Room 707 for a reservation made yesterday. New clues: Hotel booking at The Grand Regency Room 707 booked on October 30, 1987 We look into all the surveillance records for hotel checkins at The Grand Regency for room 707 on October 30, 1987. select surveillance_records.id, surveillance_records.hotel_checkin_id, surveillance_records.note from surveillance_records join hotel_checkins on surveillance_records.hotel_checkin_id = hotel_checkins.id where hotel_checkins.hotel_name = 'The Grand Regency' and hotel_checkins.room_number = 707 and hotel_checkins.check_in_date = 19871030 and surveillance_records.note is not NULL; hotel_checkin_id note 119 Subject was overheard yelling on a phone: “Did you kill him?” We can look at hotel checkins for id 119 and see which person checked in. select * from hotel_checkins where id = 119; id person_id hotel_name check_in_date room_number 119 11 The Grand Regency 19871030 707 We now look into the phone records for person id 11. (Query below also looks at phone records for person id 58 as they are the recipient of the call) select * from phone_records where caller_id in (11, 58) or recipient_id in (11, 58); “Why did you kill him, bro? You should have left the carpenter do it himself!” “I will do it. Only if you give me that nice Lambo of yours.” New clues: Suspect maybe be a carpenter Suspect owns a Lamborghini We can use JOIN on person and vehicle_registry to find our suspect. select * from vehicle_registry join person on person.id = vehicle_registry.person_id where car_make = 'Lamborghini' and person.occupation like 'carpenter'; Marco Santos is the only name which pops up. Let us look at final interview for this person. select * from final_interviews where person_id = 97; “I ordered the hit. It was me. You caught me.” ~ Marco Santos We got him. The mask slipped. Thank you Chris for creating SQL Noir.]]></summary></entry><entry><title type="html">Case #003: The Miami Marina Murder</title><link href="https://atharvabhagwat.dev/projects/sqlnoir-case-3" rel="alternate" type="text/html" title="Case #003: The Miami Marina Murder" /><published>2025-05-22T00:00:00+00:00</published><updated>2025-05-22T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/projects/sqlnoir-case-3</id><content type="html" xml:base="https://atharvabhagwat.dev/projects/sqlnoir-case-3"><![CDATA[<!-- markdownlint-disable MD032 MD033 -->

<p>A body was found floating near the docks of Coral Bay Marina in the early hours of August 14, 1986.</p>

<p>Reading the case description these are the <strong>clues</strong> we can pick up:</p>

<ul>
  <li>Location: <strong>Coral Bay Marina</strong></li>
  <li>Date: <strong>August 14, 1986</strong></li>
  <li>Dead body was found; Type of crime: <strong>murder</strong></li>
</ul>

<h2 id="going-over-the-schema">Going over the schema</h2>

<p>There are 6 tables:</p>
<ul>
  <li>crime_scene:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>person:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>hotel_checkins:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>confessions:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>interviews:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
    </ul>
  </li>
  <li>surveillance_records:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>person_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">person</code></li>
      <li>hotel_checkin_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">hotel_checkin</code></li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/articles/sqlnoir_case3/schema.png" alt="case3_schema" /></p>

<h2 id="investigation">Investigation</h2>

<p>We start by looking through all the crime scenes where the <code class="language-html highlighter-rouge">location</code> is Coral Bay Marina and <code class="language-html highlighter-rouge">date</code> is August 14, 1986.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">crime_scene</span> <span class="k">where</span> <span class="nb">date</span> <span class="o">=</span> <span class="mi">19860814</span> <span class="k">and</span> <span class="k">location</span> <span class="o">=</span> <span class="s1">'Coral Bay Marina'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>The body of an unidentified man was found near the docks. Two people were seen nearby: one who lives on 300ish “Ocean Drive” and another whose first name ends with “ul” and his last name ends with “ez”.</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Two people seen
    <ul>
      <li>one lives on 300ish “Ocean Drive”</li>
      <li>other first name ends with “ul” and his last name ends with “ez”</li>
    </ul>
  </li>
</ul>

<p>We now look into the <code class="language-html highlighter-rouge">person</code> table where <code class="language-html highlighter-rouge">address</code> has <em>300ish Ocean Drive</em> or the <code class="language-html highlighter-rouge">name</code> is of pattern *ul *ez</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">person</span> 
<span class="k">where</span> <span class="n">address</span> <span class="k">like</span> <span class="s1">'3__ %Ocean Drive%'</span> <span class="k">or</span> 
<span class="n">name</span> <span class="k">like</span> <span class="s1">'%ul %ez'</span><span class="p">;</span>
</code></pre></div></div>

<p>The two names that pop-up are <em>Carlos Mendez</em> and <em>Raul Gutierrez</em>. We can use <code class="language-html highlighter-rouge">JOIN</code> on person and interviews with the filters we just used.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">interviews</span><span class="p">.</span><span class="n">transcript</span> <span class="k">from</span> <span class="n">interviews</span> 
<span class="k">join</span> <span class="n">person</span> <span class="k">on</span> <span class="n">interviews</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> 
<span class="k">where</span> <span class="n">person</span><span class="p">.</span><span class="n">address</span> <span class="k">like</span> <span class="s1">'3__ %Ocean Drive%'</span> <span class="k">or</span> 
<span class="n">name</span> <span class="k">like</span> <span class="s1">'%ul %ez'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>“I saw someone check into a hotel on August 13. The guy looked nervous.”
“I heard someone checked into a hotel with ‘Sunset’ in the name.”</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Suspect checked into a hotel on August 13, 1986</li>
  <li>Hotel has ‘Sunset’ in its name</li>
</ul>

<p>We can use <code class="language-html highlighter-rouge">JOIN</code> this time on <code class="language-html highlighter-rouge">hotel_checkins</code> table and <code class="language-html highlighter-rouge">person</code> table where the check in date is August 13, 1986 and hotel has ‘Sunset’ in its name.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">hotel_checkins</span> 
<span class="k">join</span> <span class="n">person</span> <span class="k">on</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> 
<span class="k">where</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">hotel_name</span> <span class="k">like</span> <span class="s1">'%Sunset%'</span> <span class="k">and</span> 
<span class="n">hotel_checkins</span><span class="p">.</span><span class="n">check_in_date</span> <span class="o">=</span> <span class="mi">19860813</span><span class="p">;</span>
</code></pre></div></div>

<p>Well, this does not narrow down our list of suspects. We can look into the <code class="language-html highlighter-rouge">surveillance_records</code> where the <code class="language-html highlighter-rouge">person_id</code> is present in the hotel checkins we just looked at.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">surveillance_records</span> <span class="k">where</span> 
<span class="n">person_id</span> <span class="k">in</span> <span class="p">(</span>
  <span class="k">select</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">person_id</span> <span class="k">from</span> <span class="n">hotel_checkins</span> 
  <span class="k">join</span> <span class="n">person</span> <span class="k">on</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> 
  <span class="k">where</span> <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">hotel_name</span> <span class="k">like</span> <span class="s1">'%Sunset%'</span> <span class="k">and</span> 
  <span class="n">hotel_checkins</span><span class="p">.</span><span class="n">check_in_date</span> <span class="o">=</span> <span class="mi">19860813</span>
<span class="p">)</span> <span class="k">and</span> <span class="n">suspicious_activity</span> <span class="k">is</span> <span class="k">not</span> <span class="k">NULL</span><span class="p">;</span>
</code></pre></div></div>

<p>After a little bit of grunt work we can narrow down our search to these suspects:</p>

<table>
  <thead>
    <tr>
      <th>person_id</th>
      <th>hotel_checkin_id</th>
      <th>suspicious_activity</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>6</td>
      <td>34</td>
      <td>Spotted entering late at night</td>
    </tr>
    <tr>
      <td>7</td>
      <td>89</td>
      <td>Seen arguing with an unknown person</td>
    </tr>
    <tr>
      <td>8</td>
      <td>2</td>
      <td>Left suddenly at 3 AM</td>
    </tr>
  </tbody>
</table>

<p>We can now look at confessions where <code class="language-html highlighter-rouge">person_id</code> in <code class="language-html highlighter-rouge">[6, 7, 8]</code>. To simplify, we <code class="language-html highlighter-rouge">JOIN</code> <code class="language-html highlighter-rouge">confessions</code> and <code class="language-html highlighter-rouge">person</code> tables to directly get person name along with the confession.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">person</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="n">confessions</span><span class="p">.</span><span class="n">confession</span> <span class="k">from</span> <span class="n">confessions</span> 
<span class="k">join</span> <span class="n">person</span> <span class="k">on</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">confessions</span><span class="p">.</span><span class="n">person_id</span> 
<span class="k">where</span> <span class="n">person_id</span> <span class="k">in</span> <span class="p">(</span><span class="mi">6</span><span class="p">,</span><span class="mi">7</span><span class="p">,</span><span class="mi">8</span><span class="p">);</span>
</code></pre></div></div>

<blockquote>
  <p>“Alright! I did it. I was paid to make sure he never left the marina alive.” ~ Thomas Brown</p>
</blockquote>

<p>We got him. The tide tried to keep the secret. But in Coral Bay, even the water talks.</p>

<hr />

<p>Thank you <a href="https://github.com/hristo2612">Chris</a> for creating <a href="https://www.sqlnoir.com/">SQL Noir</a>.</p>]]></content><author><name>Atharva Bhagwat</name></author><category term="projects" /><summary type="html"><![CDATA[A body was found floating near the docks of Coral Bay Marina in the early hours of August 14, 1986. Reading the case description these are the clues we can pick up: Location: Coral Bay Marina Date: August 14, 1986 Dead body was found; Type of crime: murder Going over the schema There are 6 tables: crime_scene: id: PRIMARY KEY person: id: PRIMARY KEY hotel_checkins: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person confessions: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person interviews: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person surveillance_records: id: PRIMARY KEY person_id: FOREIGN KEY referencing id in person hotel_checkin_id: FOREIGN KEY referencing id in hotel_checkin Investigation We start by looking through all the crime scenes where the location is Coral Bay Marina and date is August 14, 1986. select * from crime_scene where date = 19860814 and location = 'Coral Bay Marina'; The body of an unidentified man was found near the docks. Two people were seen nearby: one who lives on 300ish “Ocean Drive” and another whose first name ends with “ul” and his last name ends with “ez”. New clues: Two people seen one lives on 300ish “Ocean Drive” other first name ends with “ul” and his last name ends with “ez” We now look into the person table where address has 300ish Ocean Drive or the name is of pattern *ul *ez select * from person where address like '3__ %Ocean Drive%' or name like '%ul %ez'; The two names that pop-up are Carlos Mendez and Raul Gutierrez. We can use JOIN on person and interviews with the filters we just used. select interviews.transcript from interviews join person on interviews.person_id = person.id where person.address like '3__ %Ocean Drive%' or name like '%ul %ez'; “I saw someone check into a hotel on August 13. The guy looked nervous.” “I heard someone checked into a hotel with ‘Sunset’ in the name.” New clues: Suspect checked into a hotel on August 13, 1986 Hotel has ‘Sunset’ in its name We can use JOIN this time on hotel_checkins table and person table where the check in date is August 13, 1986 and hotel has ‘Sunset’ in its name. select * from hotel_checkins join person on hotel_checkins.person_id = person.id where hotel_checkins.hotel_name like '%Sunset%' and hotel_checkins.check_in_date = 19860813; Well, this does not narrow down our list of suspects. We can look into the surveillance_records where the person_id is present in the hotel checkins we just looked at. select * from surveillance_records where person_id in ( select hotel_checkins.person_id from hotel_checkins join person on hotel_checkins.person_id = person.id where hotel_checkins.hotel_name like '%Sunset%' and hotel_checkins.check_in_date = 19860813 ) and suspicious_activity is not NULL; After a little bit of grunt work we can narrow down our search to these suspects: person_id hotel_checkin_id suspicious_activity 6 34 Spotted entering late at night 7 89 Seen arguing with an unknown person 8 2 Left suddenly at 3 AM We can now look at confessions where person_id in [6, 7, 8]. To simplify, we JOIN confessions and person tables to directly get person name along with the confession. select person.name, confessions.confession from confessions join person on person.id = confessions.person_id where person_id in (6,7,8); “Alright! I did it. I was paid to make sure he never left the marina alive.” ~ Thomas Brown We got him. The tide tried to keep the secret. But in Coral Bay, even the water talks. Thank you Chris for creating SQL Noir.]]></summary></entry><entry><title type="html">Case #002: The Stolen Sound</title><link href="https://atharvabhagwat.dev/projects/sqlnoir-case-2" rel="alternate" type="text/html" title="Case #002: The Stolen Sound" /><published>2025-05-21T00:00:00+00:00</published><updated>2025-05-21T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/projects/sqlnoir-case-2</id><content type="html" xml:base="https://atharvabhagwat.dev/projects/sqlnoir-case-2"><![CDATA[<!-- markdownlint-disable MD032 MD033 -->

<p>In the neon glow of 1980s Los Angeles, the West Hollywood Records store was rocked by a daring theft. A prized vinyl record, worth over $10,000, vanished during a busy evening, leaving the store owner desperate for answers. Vaguely recalling the details, you know the incident occurred on July 15, 1983, at this famous store.</p>

<p>Reading the case description these are the <strong>clues</strong> we can pick up:</p>

<ul>
  <li>Location: <strong>West Hollywood Records</strong></li>
  <li>Date: <strong>July 15, 1983</strong></li>
  <li>Vinyl record was stolen; Type of crime: <strong>theft</strong></li>
</ul>

<h2 id="going-over-the-schema">Going over the schema</h2>

<p>There are 4 tables:</p>
<ul>
  <li>crime_scene:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>witnesses:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
      <li>crime_scene_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">crime_scene</code></li>
    </ul>
  </li>
  <li>suspects:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>interviews:
    <ul>
      <li>suspect_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">suspects</code></li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/articles/sqlnoir_case2/schema.png" alt="case2_schema" /></p>

<h2 id="investigation">Investigation</h2>

<p>We start by looking through all the <strong>thefts</strong> that happened on <strong>July 15, 1983</strong> at <strong>West Hollywood Records</strong>.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">crime_scene</span> <span class="k">where</span> <span class="k">location</span> <span class="o">=</span> <span class="s1">'West Hollywood Records'</span> <span class="k">and</span> <span class="k">type</span> <span class="o">=</span> <span class="s1">'theft'</span> <span class="k">and</span> <span class="nb">date</span> <span class="o">=</span> <span class="mi">19830715</span><span class="p">;</span>
</code></pre></div></div>

<p>With the query result we confirm that we are looking at the correct crime.</p>

<p>We now look into the witnesses related to this crime. We can do this by using a <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">crime_scene</code> and <code class="language-html highlighter-rouge">witnesses</code> tables on their common key, using the filters we just used.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">witnesses</span><span class="p">.</span><span class="n">id</span><span class="p">,</span> <span class="n">witnesses</span><span class="p">.</span><span class="n">clue</span> <span class="k">from</span> <span class="n">witnesses</span> 
<span class="k">join</span> <span class="n">crime_scene</span> <span class="k">on</span> <span class="n">witnesses</span><span class="p">.</span><span class="n">crime_scene_id</span> <span class="o">=</span> <span class="n">crime_scene</span><span class="p">.</span><span class="n">id</span> 
<span class="k">where</span> <span class="k">location</span> <span class="o">=</span> <span class="s1">'West Hollywood Records'</span> <span class="k">and</span> 
<span class="k">type</span> <span class="o">=</span> <span class="s1">'theft'</span> <span class="k">and</span> <span class="nb">date</span> <span class="o">=</span> <span class="mi">19830715</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>“I saw a man wearing a red bandana rushing out of the store.” ~ witness #1</p>
</blockquote>

<blockquote>
  <p>“The main thing I remember is that he had a distinctive gold watch on his wrist.” ~ witness #2</p>
</blockquote>

<p>New <strong>clues</strong>:</p>
<ul>
  <li>Suspect was wearing a <strong>red bandana</strong></li>
  <li>Suspect had a <strong>gold watch</strong></li>
</ul>

<p>We have enough information on the suspect, so we look in the <code class="language-html highlighter-rouge">suspects</code> table where the bandana color is red and accessory is a gold watch.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">suspects</span> 
<span class="k">where</span> <span class="n">bandana_color</span> <span class="o">=</span> <span class="s1">'red'</span> <span class="k">and</span> 
<span class="n">accessory</span> <span class="o">=</span> <span class="s1">'gold watch'</span><span class="p">;</span>
</code></pre></div></div>

<p>There are three suspects <em>Tony Ramirez</em>, <em>Mickey Rivera</em>, and <em>Rico Delgado</em> who match the description.</p>

<p>We can now look at the interviews for these three suspects to see who our culprit is. We will use a <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">suspects</code> and <code class="language-html highlighter-rouge">interviews</code> tables as they share a common key, using the filters we just used.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">suspect_id</span><span class="p">,</span> <span class="n">transcript</span><span class="p">,</span> <span class="n">name</span> <span class="k">from</span> <span class="n">interviews</span> 
<span class="k">join</span> <span class="n">suspects</span> <span class="k">on</span> <span class="n">suspects</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">interviews</span><span class="p">.</span><span class="n">suspect_id</span> 
<span class="k">where</span> <span class="n">bandana_color</span> <span class="o">=</span> <span class="s1">'red'</span> <span class="k">and</span> <span class="n">accessory</span> <span class="o">=</span> <span class="s1">'gold watch'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>“I couldn’t help it. I snapped and took the record.” ~ Rico Delgado</p>
</blockquote>

<p>We got him. Turns out the vinyl played both sides—and side B had all the evidence.</p>

<hr />

<p>Thank you <a href="https://github.com/hristo2612">Chris</a> for creating <a href="https://www.sqlnoir.com/">SQL Noir</a>.</p>]]></content><author><name>Atharva Bhagwat</name></author><category term="projects" /><summary type="html"><![CDATA[In the neon glow of 1980s Los Angeles, the West Hollywood Records store was rocked by a daring theft. A prized vinyl record, worth over $10,000, vanished during a busy evening, leaving the store owner desperate for answers. Vaguely recalling the details, you know the incident occurred on July 15, 1983, at this famous store. Reading the case description these are the clues we can pick up: Location: West Hollywood Records Date: July 15, 1983 Vinyl record was stolen; Type of crime: theft Going over the schema There are 4 tables: crime_scene: id: PRIMARY KEY witnesses: id: PRIMARY KEY crime_scene_id: FOREIGN KEY referencing id in crime_scene suspects: id: PRIMARY KEY interviews: suspect_id: FOREIGN KEY referencing id in suspects Investigation We start by looking through all the thefts that happened on July 15, 1983 at West Hollywood Records. select * from crime_scene where location = 'West Hollywood Records' and type = 'theft' and date = 19830715; With the query result we confirm that we are looking at the correct crime. We now look into the witnesses related to this crime. We can do this by using a JOIN on crime_scene and witnesses tables on their common key, using the filters we just used. select witnesses.id, witnesses.clue from witnesses join crime_scene on witnesses.crime_scene_id = crime_scene.id where location = 'West Hollywood Records' and type = 'theft' and date = 19830715; “I saw a man wearing a red bandana rushing out of the store.” ~ witness #1 “The main thing I remember is that he had a distinctive gold watch on his wrist.” ~ witness #2 New clues: Suspect was wearing a red bandana Suspect had a gold watch We have enough information on the suspect, so we look in the suspects table where the bandana color is red and accessory is a gold watch. select * from suspects where bandana_color = 'red' and accessory = 'gold watch'; There are three suspects Tony Ramirez, Mickey Rivera, and Rico Delgado who match the description. We can now look at the interviews for these three suspects to see who our culprit is. We will use a JOIN on suspects and interviews tables as they share a common key, using the filters we just used. select suspect_id, transcript, name from interviews join suspects on suspects.id = interviews.suspect_id where bandana_color = 'red' and accessory = 'gold watch'; “I couldn’t help it. I snapped and took the record.” ~ Rico Delgado We got him. Turns out the vinyl played both sides—and side B had all the evidence. Thank you Chris for creating SQL Noir.]]></summary></entry><entry><title type="html">Case #001: The Vanishing Briefcase</title><link href="https://atharvabhagwat.dev/projects/sqlnoir-case-1" rel="alternate" type="text/html" title="Case #001: The Vanishing Briefcase" /><published>2025-05-20T00:00:00+00:00</published><updated>2025-05-20T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/projects/sqlnoir-case-1</id><content type="html" xml:base="https://atharvabhagwat.dev/projects/sqlnoir-case-1"><![CDATA[<!-- markdownlint-disable MD032 MD033 -->

<p>Set in the gritty 1980s, a valuable briefcase has disappeared from the Blue Note Lounge. A witness reported that a man in a trench coat was seen fleeing the scene.</p>

<p>Reading the case description these are the <strong>clues</strong> we can pick up:</p>

<ul>
  <li>Crime happened in the 1980s</li>
  <li>Briefcase disappeared; Type of crime: <strong>theft</strong></li>
  <li>Location: <strong>Blue Note Lounge</strong></li>
  <li>Man in a <strong>trench coat</strong> was seen fleeing the scene</li>
</ul>

<h2 id="going-over-the-schema">Going over the schema</h2>

<p>There are 3 tables:</p>
<ul>
  <li>crime_scene:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>suspects:
    <ul>
      <li>id: <strong>PRIMARY KEY</strong></li>
    </ul>
  </li>
  <li>interviews:
    <ul>
      <li>suspect_id: <strong>FOREIGN KEY</strong> referencing <code class="language-html highlighter-rouge">id</code> in <code class="language-html highlighter-rouge">suspects</code></li>
    </ul>
  </li>
</ul>

<p><img src="/assets/images/articles/sqlnoir_case1/schema.png" alt="case1_schema" /></p>

<h2 id="investigation">Investigation</h2>

<p>We start by looking through all the crime scenes that happened at the <strong>Blue Note Lounge</strong>.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">crime_scene</span> <span class="k">where</span> <span class="k">location</span> <span class="o">=</span> <span class="s1">'Blue Note Lounge'</span><span class="p">;</span>
</code></pre></div></div>

<p>We get this description of the crime:</p>

<blockquote>
  <p>“A briefcase containing sensitive documents vanished. A witness reported a man in a trench coat with a scar on his left cheek fleeing the scene.”</p>
</blockquote>

<p>New <strong>clue</strong>:</p>

<ul>
  <li>Suspect has a <strong>scar</strong> on his <strong>left cheek</strong></li>
</ul>

<p>We have enough information on the suspect, so we look in the <strong>suspects</strong> table where the attire is trench coat and there is a scar on the left cheek.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">suspects</span> <span class="k">where</span> <span class="n">attire</span> <span class="o">=</span> <span class="s1">'trench coat'</span> <span class="k">and</span> <span class="n">scar</span> <span class="o">=</span> <span class="s1">'left cheek'</span><span class="p">;</span>
</code></pre></div></div>

<p>There are two suspects <em>Frankie Lombardi</em> and <em>Vincent Malone</em> who match the description.</p>

<p>We can now look at the interviews for these two suspects to see who our culprit is. This can be done in many ways, we simply use a <code class="language-html highlighter-rouge">JOIN</code> on <code class="language-html highlighter-rouge">suspects</code> and <code class="language-html highlighter-rouge">interviews</code> tables as they share a common key, filtered using conditions on attire and scar.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">select</span> <span class="n">suspect_id</span><span class="p">,</span> <span class="n">transcript</span><span class="p">,</span> <span class="n">name</span> <span class="k">from</span> <span class="n">interviews</span> 
<span class="k">join</span> <span class="n">suspects</span> <span class="k">on</span> <span class="n">suspects</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">interviews</span><span class="p">.</span><span class="n">suspect_id</span> 
<span class="k">where</span> <span class="n">attire</span> <span class="o">=</span> <span class="s1">'trench coat'</span> <span class="k">and</span> <span class="n">scar</span> <span class="o">=</span> <span class="s1">'left cheek'</span><span class="p">;</span>
</code></pre></div></div>

<blockquote>
  <p>“I wasn’t going to steal it, but I did.” ~ Vincent Malone</p>
</blockquote>

<p>We got the guy. The briefcase didn’t grow legs—just found the wrong hands.</p>

<hr />

<p>Thank you <a href="https://github.com/hristo2612">Chris</a> for creating <a href="https://www.sqlnoir.com/">SQL Noir</a>.</p>]]></content><author><name>Atharva Bhagwat</name></author><category term="projects" /><summary type="html"><![CDATA[Set in the gritty 1980s, a valuable briefcase has disappeared from the Blue Note Lounge. A witness reported that a man in a trench coat was seen fleeing the scene. Reading the case description these are the clues we can pick up: Crime happened in the 1980s Briefcase disappeared; Type of crime: theft Location: Blue Note Lounge Man in a trench coat was seen fleeing the scene Going over the schema There are 3 tables: crime_scene: id: PRIMARY KEY suspects: id: PRIMARY KEY interviews: suspect_id: FOREIGN KEY referencing id in suspects Investigation We start by looking through all the crime scenes that happened at the Blue Note Lounge. select * from crime_scene where location = 'Blue Note Lounge'; We get this description of the crime: “A briefcase containing sensitive documents vanished. A witness reported a man in a trench coat with a scar on his left cheek fleeing the scene.” New clue: Suspect has a scar on his left cheek We have enough information on the suspect, so we look in the suspects table where the attire is trench coat and there is a scar on the left cheek. select * from suspects where attire = 'trench coat' and scar = 'left cheek'; There are two suspects Frankie Lombardi and Vincent Malone who match the description. We can now look at the interviews for these two suspects to see who our culprit is. This can be done in many ways, we simply use a JOIN on suspects and interviews tables as they share a common key, filtered using conditions on attire and scar. select suspect_id, transcript, name from interviews join suspects on suspects.id = interviews.suspect_id where attire = 'trench coat' and scar = 'left cheek'; “I wasn’t going to steal it, but I did.” ~ Vincent Malone We got the guy. The briefcase didn’t grow legs—just found the wrong hands. Thank you Chris for creating SQL Noir.]]></summary></entry><entry><title type="html">Understanding 10x Xenium Data Analysis</title><link href="https://atharvabhagwat.dev/articles/10x-xenium" rel="alternate" type="text/html" title="Understanding 10x Xenium Data Analysis" /><published>2025-05-02T00:00:00+00:00</published><updated>2025-05-02T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/articles/10x-xenium</id><content type="html" xml:base="https://atharvabhagwat.dev/articles/10x-xenium"><![CDATA[<h2 id="overview-of-spatial-transcriptomics-st">Overview of Spatial Transcriptomics (ST)</h2>

<p>Traditional single-cell RNA sequencing (scRNA-seq) dissociates cells and profiles gene expression at single cell resolution. It is able to capture the heterogeneity within tissues and gives high resolution insight into cellular functions.</p>

<p>While this type of data can be used to analyze variations in gene expression, it lacks the spatial information for cells, which adds a dimension of information. Enter ‘Spatial Transcriptomics’ (ST)! After being named the Method of the year 2020<sup>[<a href="#ref1">1</a>]</sup> ST has revolutionized our ability to understand biology by capturing the spatial information. Having spatial context allows us to look deeper into cell-cell interactions, cellular niches, and various microenvironments across conditions.</p>

<p>Over the last few years, spatial transcriptomics technologies have advanced rapidly and each come with various advantages. Detailed table can be found <a href="https://divingintogeneticsandgenomics.com/post/python-visium/">here</a>.</p>

<h2 id="overview-of-xenium">Overview of Xenium</h2>

<p>Xenium is a single-cell resolution technology commercialized by 10x genomics in 2023. It uses RNA based transcripts and can target up to 5000 genes. It captures transcripts at subcellular level. 10x also has nuclear and cell membrane staining which are used for cell segmentation downstream, as compared to the default which only has nuclear staining and cells are detected based on cell-boundary expansion after nucleus segmentation<sup>[<a href="#ref2">2</a>]</sup>.</p>

<p>A few caveots to note for xenium data are that the data generation for large number of samples for entire tissue sections is expensive. So the general practice is to build a Tissue Microarray (TMA) with 30-45 cores of 1.5mm-2mm diameter. Selecting these cores haphazardly can induce data bias as it captures a small section of the condition to be captured. So, building TMA with help of expert pathalogists is a necessary step. Ex: When it comes to studying cancer, the most interesting parts are boundaries between either tumor and immune cells or tumor and stromal cells. These regions are full of potential, allowing us to dive deeper into finding interactions and spatial structures between in such regions.</p>

<h2 id="understand-10x-output-files">Understand 10x output files</h2>

<p>The Xenium analyzer has numerous outputs we only need some of them to start with data analysis. Here are those files:</p>

<table>
  <thead>
    <tr>
      <th>File Type</th>
      <th>File and Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Cell summary</strong></td>
      <td><code class="language-html highlighter-rouge">cells.parquet</code>: Cell summary file in Parquet format.</td>
    </tr>
    <tr>
      <td><strong>Cell-feature matrix</strong></td>
      <td><code class="language-html highlighter-rouge">cell_feature_matrix.h5</code>: Cell-feature matrix file in HDF5 format.</td>
    </tr>
  </tbody>
</table>

<p><strong>Table 2: Xenium Onboard Analysis Output Files</strong><sup>[<a href="#ref3">3</a>]</sup></p>

<h2 id="getting-started-with-data-analysis">Getting started with data analysis</h2>

<p>I will use the <a href="https://www.10xgenomics.com/datasets/preview-data-ffpe-human-lung-cancer-with-xenium-multimodal-cell-segmentation-1-standard">Human Lung Cancer with Xenium Multimodal Cell Segmentation data</a> for showcase.</p>

<p>We can get started once <code class="language-html highlighter-rouge">Xenium_V1_humanLung_Cancer_FFPE_outs.zip</code> is downloaded.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="syntax"><code>unzip <span class="nt">-d</span> data Xenium_V1_humanLung_Cancer_FFPE_outs.zip
</code></pre></div></div>

<h3 id="installing-necessary-libraries">Installing necessary libraries</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="syntax"><code>pip <span class="nb">install </span>anndata scanpy squidpy
</code></pre></div></div>

<h3 id="loading-the-data-as-an-anndata-object-from-raw-output-files">Loading the data as an AnnData object from raw output files</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="n">pd</span>
<span class="kn">import</span> <span class="nn">anndata</span> <span class="k">as</span> <span class="n">ad</span>
<span class="kn">import</span> <span class="nn">scanpy</span> <span class="k">as</span> <span class="n">sc</span>
<span class="kn">import</span> <span class="nn">squidpy</span> <span class="k">as</span> <span class="n">sq</span>

<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="n">plt</span><span class="p">.</span><span class="n">rcParams</span><span class="p">[</span><span class="s">'figure.dpi'</span><span class="p">]</span> <span class="o">=</span> <span class="mi">250</span>        <span class="c1"># increase figure dpi for better quality plots
</span>
<span class="c1"># load count matrix
</span><span class="n">adata</span> <span class="o">=</span> <span class="n">sc</span><span class="p">.</span><span class="n">read_10x_h5</span><span class="p">(</span><span class="s">'data/cell_feature_matrix.h5'</span><span class="p">)</span>

<span class="c1"># load cells metadata
</span><span class="n">cells</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="n">read_parquet</span><span class="p">(</span><span class="s">'data/cells.parquet'</span><span class="p">)</span>
<span class="n">cells</span><span class="p">.</span><span class="n">index</span> <span class="o">=</span> <span class="n">cells</span><span class="p">[</span><span class="s">'cell_id'</span><span class="p">]</span>
<span class="n">cells</span><span class="p">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'cell_id'</span><span class="p">],</span> <span class="n">inplace</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="n">adata</span><span class="p">.</span><span class="n">obs</span> <span class="o">=</span> <span class="n">cells</span><span class="p">.</span><span class="n">copy</span><span class="p">()</span>

<span class="c1"># set spatial info
</span><span class="n">adata</span><span class="p">.</span><span class="n">obsm</span><span class="p">[</span><span class="s">"spatial"</span><span class="p">]</span> <span class="o">=</span> <span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">[[</span><span class="s">"x_centroid"</span><span class="p">,</span> <span class="s">"y_centroid"</span><span class="p">]].</span><span class="n">copy</span><span class="p">().</span><span class="n">to_numpy</span><span class="p">()</span>

<span class="n">adata</span><span class="p">.</span><span class="n">write_h5ad</span><span class="p">(</span><span class="s">'objects/xenium_adata.h5ad'</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="understanding-xenium-data-structure">Understanding xenium data structure</h3>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="n">AnnData</span> <span class="nb">object</span> <span class="k">with</span> <span class="n">n_obs</span> <span class="err">×</span> <span class="n">n_vars</span> <span class="o">=</span> <span class="mi">162254</span> <span class="err">×</span> <span class="mi">377</span>
    <span class="n">obs</span><span class="p">:</span> <span class="s">'x_centroid'</span><span class="p">,</span> <span class="s">'y_centroid'</span><span class="p">,</span> <span class="s">'transcript_counts'</span><span class="p">,</span> <span class="s">'control_probe_counts'</span><span class="p">,</span>
    <span class="s">'control_codeword_counts'</span><span class="p">,</span> <span class="s">'unassigned_codeword_counts'</span><span class="p">,</span> <span class="s">'deprecated_codeword_counts'</span><span class="p">,</span> 
    <span class="s">'total_counts'</span><span class="p">,</span> <span class="s">'cell_area'</span><span class="p">,</span> <span class="s">'nucleus_area'</span>
    <span class="n">var</span><span class="p">:</span> <span class="s">'gene_ids'</span><span class="p">,</span> <span class="s">'feature_types'</span><span class="p">,</span> <span class="s">'genome'</span>
    <span class="n">obsm</span><span class="p">:</span> <span class="s">'spatial'</span>
</code></pre></div></div>

<p><code class="language-html highlighter-rouge">adata.obs</code> stores the metadata. <code class="language-html highlighter-rouge">adata.var</code> stores information about the genes on the panel. More information on AnnData structure can be found <a href="https://anndata.readthedocs.io/en/stable/">here</a>. <code class="language-html highlighter-rouge">x_centroid</code> and <code class="language-html highlighter-rouge">y_xentroid</code> are the x and y coordinates of the cells.</p>

<h4 id="qc">QC</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'Shape of object before filtering: </span><span class="si">{</span><span class="n">adata</span><span class="p">.</span><span class="n">shape</span><span class="si">}</span><span class="s">'</span><span class="p">)</span>

<span class="n">sc</span><span class="p">.</span><span class="n">pp</span><span class="p">.</span><span class="n">calculate_qc_metrics</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">percent_top</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">inplace</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="n">sc</span><span class="p">.</span><span class="n">pp</span><span class="p">.</span><span class="n">filter_cells</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">min_counts</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>

<span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'Shape of object after filtering: </span><span class="si">{</span><span class="n">adata</span><span class="p">.</span><span class="n">shape</span><span class="si">}</span><span class="s">'</span><span class="p">)</span>
</code></pre></div></div>

<p>As part of quality control we drop cells with <code class="language-html highlighter-rouge">n_genes_by_counts</code> &lt; 10.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="n">AnnData</span> <span class="nb">object</span> <span class="k">with</span> <span class="n">n_obs</span> <span class="err">×</span> <span class="n">n_vars</span> <span class="o">=</span> <span class="mi">154472</span> <span class="err">×</span> <span class="mi">377</span>
    <span class="n">obs</span><span class="p">:</span> <span class="s">'x_centroid'</span><span class="p">,</span> <span class="s">'y_centroid'</span><span class="p">,</span> <span class="s">'transcript_counts'</span><span class="p">,</span> <span class="s">'control_probe_counts'</span><span class="p">,</span> 
    <span class="s">'control_codeword_counts'</span><span class="p">,</span> <span class="s">'unassigned_codeword_counts'</span><span class="p">,</span> 
    <span class="s">'deprecated_codeword_counts'</span><span class="p">,</span> <span class="s">'total_counts'</span><span class="p">,</span> <span class="s">'cell_area'</span><span class="p">,</span> <span class="s">'nucleus_area'</span><span class="p">,</span> 
    <span class="s">'n_genes_by_counts'</span><span class="p">,</span> <span class="s">'log1p_n_genes_by_counts'</span><span class="p">,</span> <span class="s">'log1p_total_counts'</span><span class="p">,</span> <span class="s">'n_counts'</span>
    <span class="n">var</span><span class="p">:</span> <span class="s">'gene_ids'</span><span class="p">,</span> <span class="s">'feature_types'</span><span class="p">,</span> <span class="s">'genome'</span><span class="p">,</span> <span class="s">'n_cells_by_counts'</span><span class="p">,</span> 
    <span class="s">'mean_counts'</span><span class="p">,</span> <span class="s">'log1p_mean_counts'</span><span class="p">,</span> <span class="s">'pct_dropout_by_counts'</span><span class="p">,</span> <span class="s">'total_counts'</span><span class="p">,</span> <span class="s">'log1p_total_counts'</span>
    <span class="n">obsm</span><span class="p">:</span> <span class="s">'spatial'</span>
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="n">Shape</span> <span class="n">of</span> <span class="nb">object</span> <span class="n">before</span> <span class="n">filtering</span><span class="p">:</span> <span class="p">(</span><span class="mi">162254</span><span class="p">,</span> <span class="mi">377</span><span class="p">)</span>
<span class="n">Shape</span> <span class="n">of</span> <span class="nb">object</span> <span class="n">after</span> <span class="n">filtering</span><span class="p">:</span> <span class="p">(</span><span class="mi">154472</span><span class="p">,</span> <span class="mi">377</span><span class="p">)</span>
</code></pre></div></div>

<p>Referring to <a href="https://doi.org/10.1038/s41592-025-02617-2">this</a> paper we’ll normalize <code class="language-html highlighter-rouge">target_sum=100</code> and log normalize.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="c1"># Normalize total
</span><span class="n">sc</span><span class="p">.</span><span class="n">pp</span><span class="p">.</span><span class="n">normalize_total</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">target_sum</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>

<span class="c1"># Log-normalize
</span><span class="n">sc</span><span class="p">.</span><span class="n">pp</span><span class="p">.</span><span class="n">log1p</span><span class="p">(</span><span class="n">adata</span><span class="p">)</span>
</code></pre></div></div>

<p>We will apply dimensionality reduction methods</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="c1"># Run PCA
</span><span class="n">sc</span><span class="p">.</span><span class="n">pp</span><span class="p">.</span><span class="n">pca</span><span class="p">(</span><span class="n">adata</span><span class="p">)</span>

<span class="c1"># Calculate neighbors
</span><span class="n">sc</span><span class="p">.</span><span class="n">pp</span><span class="p">.</span><span class="n">neighbors</span><span class="p">(</span><span class="n">adata</span><span class="p">)</span>

<span class="c1"># Leiden clustering
</span><span class="n">sc</span><span class="p">.</span><span class="n">tl</span><span class="p">.</span><span class="n">leiden</span><span class="p">(</span><span class="n">adata</span><span class="p">)</span>

<span class="c1"># Computing UMAP
</span><span class="n">sc</span><span class="p">.</span><span class="n">tl</span><span class="p">.</span><span class="n">umap</span><span class="p">(</span><span class="n">adata</span><span class="p">)</span>
</code></pre></div></div>

<p>We will plot the UMAP and color on leiden clusters using <code class="language-html highlighter-rouge">sc.pl.umap(adata, color='leiden', legend_loc='on data')</code></p>

<p><em>NOTE: I have merged some leiden clusters to group similar clusters together in a new column ‘clusters’</em></p>

<p><img src="/assets/images/articles/10x_xenium/clusters.png" alt="clusters" /></p>

<h2 id="layers-of-spatial-data">Layers of spatial data</h2>

<h3 id="neighborhood-enrichment">Neighborhood enrichment</h3>

<p><em>The</em> reason for spatial data generation is having the <code class="language-html highlighter-rouge">x_centroid</code> and <code class="language-html highlighter-rouge">y_centroid</code> for each cell. This allows us to build a neighborhood graph.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="n">sq</span><span class="p">.</span><span class="n">gr</span><span class="p">.</span><span class="n">spatial_neighbors</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">radius</span><span class="o">=</span><span class="mi">50</span><span class="p">,</span> <span class="n">coord_type</span><span class="o">=</span><span class="s">'generic'</span><span class="p">)</span> <span class="c1"># radius in µm
</span></code></pre></div></div>

<p>By default this creates an entries ‘spatial_connectivities’ and ‘spatial_distances’ in in <code class="language-html highlighter-rouge">adata.obsp</code>.</p>

<p>We can now run neighborhood enrichment to see which cells group together using:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="c1"># set seed=0 for reproducibility
</span><span class="n">sq</span><span class="p">.</span><span class="n">gr</span><span class="p">.</span><span class="n">nhood_enrichment</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">cluster_key</span><span class="o">=</span><span class="s">'clusters'</span><span class="p">,</span> <span class="n">seed</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
</code></pre></div></div>

<p>Using <code class="language-html highlighter-rouge">sq.pl.nhood_enrichment(adata, cluster_key='clusters', cmap='bwr', vmin=-10, vmax=10)</code> we can plot the neighborhood enrichment.</p>

<p><img src="/assets/images/articles/10x_xenium/nhood.png" alt="nhood" /></p>

<h3 id="neighborhood-and-proximity-scores">Neighborhood and Proximity scores</h3>

<p>Another interesting analysis that is possible with spatial information is looking into neighborhoods at single-cell resolution. Using the method defined in Barkley et al<sup>[<a href="#ref4">4</a>]</sup>.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="syntax"><code><span class="n">connections</span> <span class="o">=</span> <span class="n">adata</span><span class="p">.</span><span class="n">obsp</span><span class="p">[</span><span class="s">'spatial_connectivities'</span><span class="p">].</span><span class="n">tocsr</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">fetch_neighbors</span><span class="p">(</span><span class="n">connections</span><span class="p">,</span> <span class="n">cell_id</span><span class="p">):</span>
    <span class="n">row_idx</span> <span class="o">=</span> <span class="n">adata</span><span class="p">.</span><span class="n">obs_names</span><span class="p">.</span><span class="n">get_loc</span><span class="p">(</span><span class="s">'cell_name'</span><span class="p">)</span>
    <span class="n">neighbor_idx</span> <span class="o">=</span> <span class="n">connections</span><span class="p">[</span><span class="n">row_idx</span><span class="p">].</span><span class="n">indices</span>
    <span class="k">return</span> <span class="n">adata</span><span class="p">.</span><span class="n">obs_names</span><span class="p">[</span><span class="n">neighbor_idx</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">get_neighborhood_score</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">spot_id</span><span class="p">,</span> <span class="n">target_column</span><span class="p">):</span>
    <span class="s">"""Returns neighborhood score
    Args:
    adata(anndata.AnnData): input anndata object
    spot_id(str): cell id
    target_column(str): celltype/cluster column
    """</span>
    <span class="n">neighbors</span> <span class="o">=</span> <span class="n">fetch_neighbors</span><span class="p">(</span><span class="n">connections</span><span class="p">,</span> <span class="n">spot_id</span><span class="p">)</span>
    <span class="n">cluster</span> <span class="o">=</span> <span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">neighbors</span><span class="o">+</span><span class="p">[</span><span class="n">spot_id</span><span class="p">]]</span>
    <span class="k">return</span> <span class="n">cluster</span><span class="p">[</span><span class="n">target_column</span><span class="p">].</span><span class="n">value_counts</span><span class="p">()</span> <span class="o">/</span> <span class="n">cluster</span><span class="p">[</span><span class="n">target_column</span><span class="p">].</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">get_proximity_score</span><span class="p">(</span><span class="n">adata</span><span class="p">,</span> <span class="n">spot_id</span><span class="p">,</span> <span class="n">target_column</span><span class="p">):</span>
    <span class="s">"""Returns proximity score
    Args:
    adata(anndata.AnnData): input anndata object
    spot_id(str): cell id
    target_column(str): celltype/cluster column
    """</span>
    <span class="n">source</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">(</span><span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">spot_id</span><span class="p">,</span> <span class="p">[</span><span class="s">'x_centroid'</span><span class="p">,</span> <span class="s">'y_centroid'</span><span class="p">]].</span><span class="n">values</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="p">.</span><span class="n">float64</span><span class="p">)</span>
    <span class="n">proximity</span> <span class="o">=</span> <span class="p">{}</span>

    <span class="n">centroids</span> <span class="o">=</span> <span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">.</span><span class="n">index</span> <span class="o">!=</span> <span class="n">spot_id</span><span class="p">,</span> <span class="p">[</span><span class="s">'x_centroid'</span><span class="p">,</span> <span class="s">'y_centroid'</span><span class="p">]].</span><span class="n">values</span>
    <span class="n">target_celltypes</span> <span class="o">=</span> <span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="n">adata</span><span class="p">.</span><span class="n">obs</span><span class="p">.</span><span class="n">index</span> <span class="o">!=</span> <span class="n">spot_id</span><span class="p">,</span> <span class="n">target_column</span><span class="p">]</span>

    <span class="k">for</span> <span class="n">target_oi</span> <span class="ow">in</span> <span class="n">np</span><span class="p">.</span><span class="n">unique</span><span class="p">(</span><span class="n">target_celltypes</span><span class="p">):</span>
        <span class="n">target_idx</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">where</span><span class="p">(</span><span class="n">target_celltypes</span> <span class="o">==</span> <span class="n">target_oi</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
        <span class="n">target_coords</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">(</span><span class="n">centroids</span><span class="p">[</span><span class="n">target_idx</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="p">.</span><span class="n">float64</span><span class="p">)</span>
        <span class="n">distances</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">linalg</span><span class="p">.</span><span class="n">norm</span><span class="p">(</span><span class="n">target_coords</span> <span class="o">-</span> <span class="n">source</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">proximity</span><span class="p">[</span><span class="n">target_oi</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">/</span> <span class="p">(</span><span class="mi">1</span> <span class="o">+</span> <span class="n">np</span><span class="p">.</span><span class="nb">min</span><span class="p">(</span><span class="n">distances</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">pd</span><span class="p">.</span><span class="n">Series</span><span class="p">(</span><span class="n">proximity</span><span class="p">)</span>
</code></pre></div></div>

<p>The paper defines this for visium, the code provided here is updated to support xenium data. We can compare neighborhood and proximity scores between conditions across a cohort or compare these scores between different neighborhoods within the same core.</p>

<!-- markdownlint-disable no-trailing-punctuation -->
<h2 id="lot-of-work-ahead">Lot of work ahead…</h2>

<h3 id="qc---filtering-cells">QC - filtering cells</h3>

<p>Filtering cells using a global threshold for metrics like <code class="language-html highlighter-rouge">n_genes_by_counts</code> or <code class="language-html highlighter-rouge">total_counts</code> can lead to suboptimal results by discarding biologically relevant cells that appear low-quality in a global context but are consistent with their local tissue environment. This is because global thresholds ignore the inherent spatial structure of tissues, potentially confounding biological variation with technical noise. SpotSweeper<sup>[<a href="#ref5">5</a>]</sup> addresses this limitation by introducing a spatially aware quality control framework that leverages local neighborhood information to detect outliers based on a zscore.</p>

<h2 id="references">References</h2>

<p id="ref1">[1] Marx, V. Method of the Year: spatially resolved transcriptomics. Nat Methods 18, 9–14 (2021). <a href="https://doi.org/10.1038/s41592-020-01033-y">https://doi.org/10.1038/s41592-020-01033-y</a></p>
<p id="ref2">[2] Xenium In Situ Multimodal Cell Segmentation: Workflow and Data Highlights. <a href="https://cdn.10xgenomics.com/image/upload/v1710785020/CG000750_XeniumInSitu_CellSegmentation_TechNote_RevA.pdf">https://cdn.10xgenomics.com/image/upload/v1710785020/CG000750_XeniumInSitu_CellSegmentation_TechNote_RevA.pdf</a></p>
<p id="ref3">[3] Xenium Output Files at a Glance. <a href="https://www.10xgenomics.com/support/software/xenium-onboard-analysis/2.0/tutorials/outputs/xoa-output-at-a-glance">https://www.10xgenomics.com/support/software/xenium-onboard-analysis/2.0/tutorials/outputs/xoa-output-at-a-glance</a></p>
<p id="ref4">[4] Barkley, D., Moncada, R., Pour, M. et al. Cancer cell states recur across tumor types and form specific interactions with the tumor microenvironment. Nat Genet 54, 1192–1201 (2022). <a href="https://doi.org/10.1038/s41588-022-01141-9">https://doi.org/10.1038/s41588-022-01141-9</a></p>
<p id="ref5">[5] Totty, M., Hicks, S.C. &amp; Guo, B. SpotSweeper: spatially aware quality control for spatial transcriptomics. Nat Methods 22, 1520–1530 (2025). <a href="https://doi.org/10.1038/s41592-025-02713-3">https://doi.org/10.1038/s41592-025-02713-3</a></p>]]></content><author><name>Atharva Bhagwat</name></author><category term="articles" /><summary type="html"><![CDATA[Overview of Spatial Transcriptomics (ST) Traditional single-cell RNA sequencing (scRNA-seq) dissociates cells and profiles gene expression at single cell resolution. It is able to capture the heterogeneity within tissues and gives high resolution insight into cellular functions. While this type of data can be used to analyze variations in gene expression, it lacks the spatial information for cells, which adds a dimension of information. Enter ‘Spatial Transcriptomics’ (ST)! After being named the Method of the year 2020[1] ST has revolutionized our ability to understand biology by capturing the spatial information. Having spatial context allows us to look deeper into cell-cell interactions, cellular niches, and various microenvironments across conditions. Over the last few years, spatial transcriptomics technologies have advanced rapidly and each come with various advantages. Detailed table can be found here. Overview of Xenium Xenium is a single-cell resolution technology commercialized by 10x genomics in 2023. It uses RNA based transcripts and can target up to 5000 genes. It captures transcripts at subcellular level. 10x also has nuclear and cell membrane staining which are used for cell segmentation downstream, as compared to the default which only has nuclear staining and cells are detected based on cell-boundary expansion after nucleus segmentation[2]. A few caveots to note for xenium data are that the data generation for large number of samples for entire tissue sections is expensive. So the general practice is to build a Tissue Microarray (TMA) with 30-45 cores of 1.5mm-2mm diameter. Selecting these cores haphazardly can induce data bias as it captures a small section of the condition to be captured. So, building TMA with help of expert pathalogists is a necessary step. Ex: When it comes to studying cancer, the most interesting parts are boundaries between either tumor and immune cells or tumor and stromal cells. These regions are full of potential, allowing us to dive deeper into finding interactions and spatial structures between in such regions. Understand 10x output files The Xenium analyzer has numerous outputs we only need some of them to start with data analysis. Here are those files: File Type File and Description Cell summary cells.parquet: Cell summary file in Parquet format. Cell-feature matrix cell_feature_matrix.h5: Cell-feature matrix file in HDF5 format. Table 2: Xenium Onboard Analysis Output Files[3] Getting started with data analysis I will use the Human Lung Cancer with Xenium Multimodal Cell Segmentation data for showcase. We can get started once Xenium_V1_humanLung_Cancer_FFPE_outs.zip is downloaded. unzip -d data Xenium_V1_humanLung_Cancer_FFPE_outs.zip Installing necessary libraries pip install anndata scanpy squidpy Loading the data as an AnnData object from raw output files import os import pandas as pd import anndata as ad import scanpy as sc import squidpy as sq import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] = 250 # increase figure dpi for better quality plots # load count matrix adata = sc.read_10x_h5('data/cell_feature_matrix.h5') # load cells metadata cells = pd.read_parquet('data/cells.parquet') cells.index = cells['cell_id'] cells.drop(['cell_id'], inplace=True, axis=1) adata.obs = cells.copy() # set spatial info adata.obsm["spatial"] = adata.obs[["x_centroid", "y_centroid"]].copy().to_numpy() adata.write_h5ad('objects/xenium_adata.h5ad') Understanding xenium data structure AnnData object with n_obs × n_vars = 162254 × 377 obs: 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'control_codeword_counts', 'unassigned_codeword_counts', 'deprecated_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area' var: 'gene_ids', 'feature_types', 'genome' obsm: 'spatial' adata.obs stores the metadata. adata.var stores information about the genes on the panel. More information on AnnData structure can be found here. x_centroid and y_xentroid are the x and y coordinates of the cells. QC print(f'Shape of object before filtering: {adata.shape}') sc.pp.calculate_qc_metrics(adata, percent_top=None, inplace=True) sc.pp.filter_cells(adata, min_counts=10) print(f'Shape of object after filtering: {adata.shape}') As part of quality control we drop cells with n_genes_by_counts &lt; 10. AnnData object with n_obs × n_vars = 154472 × 377 obs: 'x_centroid', 'y_centroid', 'transcript_counts', 'control_probe_counts', 'control_codeword_counts', 'unassigned_codeword_counts', 'deprecated_codeword_counts', 'total_counts', 'cell_area', 'nucleus_area', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'log1p_total_counts', 'n_counts' var: 'gene_ids', 'feature_types', 'genome', 'n_cells_by_counts', 'mean_counts', 'log1p_mean_counts', 'pct_dropout_by_counts', 'total_counts', 'log1p_total_counts' obsm: 'spatial' Shape of object before filtering: (162254, 377) Shape of object after filtering: (154472, 377) Referring to this paper we’ll normalize target_sum=100 and log normalize. # Normalize total sc.pp.normalize_total(adata, target_sum=100) # Log-normalize sc.pp.log1p(adata) We will apply dimensionality reduction methods # Run PCA sc.pp.pca(adata) # Calculate neighbors sc.pp.neighbors(adata) # Leiden clustering sc.tl.leiden(adata) # Computing UMAP sc.tl.umap(adata) We will plot the UMAP and color on leiden clusters using sc.pl.umap(adata, color='leiden', legend_loc='on data') NOTE: I have merged some leiden clusters to group similar clusters together in a new column ‘clusters’ Layers of spatial data Neighborhood enrichment The reason for spatial data generation is having the x_centroid and y_centroid for each cell. This allows us to build a neighborhood graph. sq.gr.spatial_neighbors(adata, radius=50, coord_type='generic') # radius in µm By default this creates an entries ‘spatial_connectivities’ and ‘spatial_distances’ in in adata.obsp. We can now run neighborhood enrichment to see which cells group together using: # set seed=0 for reproducibility sq.gr.nhood_enrichment(adata, cluster_key='clusters', seed=0) Using sq.pl.nhood_enrichment(adata, cluster_key='clusters', cmap='bwr', vmin=-10, vmax=10) we can plot the neighborhood enrichment. Neighborhood and Proximity scores Another interesting analysis that is possible with spatial information is looking into neighborhoods at single-cell resolution. Using the method defined in Barkley et al[4]. connections = adata.obsp['spatial_connectivities'].tocsr() def fetch_neighbors(connections, cell_id): row_idx = adata.obs_names.get_loc('cell_name') neighbor_idx = connections[row_idx].indices return adata.obs_names[neighbor_idx] def get_neighborhood_score(adata, spot_id, target_column): """Returns neighborhood score Args: adata(anndata.AnnData): input anndata object spot_id(str): cell id target_column(str): celltype/cluster column """ neighbors = fetch_neighbors(connections, spot_id) cluster = adata.obs.loc[neighbors+[spot_id]] return cluster[target_column].value_counts() / cluster[target_column].shape[0] def get_proximity_score(adata, spot_id, target_column): """Returns proximity score Args: adata(anndata.AnnData): input anndata object spot_id(str): cell id target_column(str): celltype/cluster column """ source = np.array(adata.obs.loc[spot_id, ['x_centroid', 'y_centroid']].values, dtype=np.float64) proximity = {} centroids = adata.obs.loc[adata.obs.index != spot_id, ['x_centroid', 'y_centroid']].values target_celltypes = adata.obs.loc[adata.obs.index != spot_id, target_column] for target_oi in np.unique(target_celltypes): target_idx = np.where(target_celltypes == target_oi)[0] target_coords = np.array(centroids[target_idx], dtype=np.float64) distances = np.linalg.norm(target_coords - source, axis=1) proximity[target_oi] = 1 / (1 + np.min(distances)) return pd.Series(proximity) The paper defines this for visium, the code provided here is updated to support xenium data. We can compare neighborhood and proximity scores between conditions across a cohort or compare these scores between different neighborhoods within the same core. Lot of work ahead… QC - filtering cells Filtering cells using a global threshold for metrics like n_genes_by_counts or total_counts can lead to suboptimal results by discarding biologically relevant cells that appear low-quality in a global context but are consistent with their local tissue environment. This is because global thresholds ignore the inherent spatial structure of tissues, potentially confounding biological variation with technical noise. SpotSweeper[5] addresses this limitation by introducing a spatially aware quality control framework that leverages local neighborhood information to detect outliers based on a zscore. References [1] Marx, V. Method of the Year: spatially resolved transcriptomics. Nat Methods 18, 9–14 (2021). https://doi.org/10.1038/s41592-020-01033-y [2] Xenium In Situ Multimodal Cell Segmentation: Workflow and Data Highlights. https://cdn.10xgenomics.com/image/upload/v1710785020/CG000750_XeniumInSitu_CellSegmentation_TechNote_RevA.pdf [3] Xenium Output Files at a Glance. https://www.10xgenomics.com/support/software/xenium-onboard-analysis/2.0/tutorials/outputs/xoa-output-at-a-glance [4] Barkley, D., Moncada, R., Pour, M. et al. Cancer cell states recur across tumor types and form specific interactions with the tumor microenvironment. Nat Genet 54, 1192–1201 (2022). https://doi.org/10.1038/s41588-022-01141-9 [5] Totty, M., Hicks, S.C. &amp; Guo, B. SpotSweeper: spatially aware quality control for spatial transcriptomics. Nat Methods 22, 1520–1530 (2025). https://doi.org/10.1038/s41592-025-02713-3]]></summary></entry><entry><title type="html">School Shootings in the US</title><link href="https://atharvabhagwat.dev/articles/school-shootings" rel="alternate" type="text/html" title="School Shootings in the US" /><published>2022-12-15T00:00:00+00:00</published><updated>2022-12-15T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/articles/school-shootings-in-the-us</id><content type="html" xml:base="https://atharvabhagwat.dev/articles/school-shootings"><![CDATA[<h2 id="introduction">Introduction</h2>

<p>United states is one of the most diverse and multi-cultural places in the world. It is home to approximately 332 million, of which more than 25% are people under 17 years of age.</p>

<p>When compared to other countries, the US has a ratio of 120.5 firearms per 100 residents, up from 88 per 100 in 2011, highest among that of other countries around the world.</p>

<p>With increasing number of deaths among people under 17 due to gun violence, schools are eager to find ways to better protect their students. But the steps they are taking like clear bag packs(no bag packs in some cases), risk reinforcing an unhealthy culture of surveillance without actually preventing violence. With recent legislation pushing for gun control within US, we would like to answer questions based on the K-12 school shooting database.</p>

<p>Purpose of the project is to look into K-12 school shooting dataset and perform exploratory analysis using visualization techniques in answering potential questions that lawmakers will be interested in, and provide a factual report of these incidents and make this information easily available and understandable.</p>

<p>Getting a better grasp of school shootings, as challenging as it might be, is a clear priority for preventing harm and disruption for kids, staff, and families.</p>

<p>We would like to start with the number of K-12 schools in the US where school shooting has occurred, by year, with respect to number of victims, analyse patterns across seasons, quarters, and geographical locations.</p>

<h2 id="about-the-data">About the Data</h2>

<p><strong>Source:</strong> <a href="https://k12ssdb.org/all-shootings">K-12 School Shooting Database</a>. Riedman, David (2022).</p>

<p><strong>Description:</strong></p>

<p>K-12 School Shooting Database is an open source database launched and managed by David Riedman in 2018.</p>

<p>The data consists of all incidents from 1970 to 2022 and is consistently updated. The dataset is divided in to 4 tables: Incident, Shooter, Victim, and Weapon.</p>

<p>We are using subsets of the incident, weapon, and shooter data tables to generate visualization and answer our questions.</p>

<p>Subset of indicent table has 2171 entries and 19 columns. All tables have features with missing values, this will be handled during the data analysis phase.</p>

<h2 id="incident-table">Incident Table</h2>

<p>The table contains 2171 incidents from year 1970 to 2022.</p>

<p>Out of all the features in the incident table, analysis focuses on:</p>

<ul>
  <li>Measures like <code class="language-html highlighter-rouge">victims killed</code>, <code class="language-html highlighter-rouge">wounded</code>, and <code class="language-html highlighter-rouge">total number of victims</code></li>
  <li>Time series data like <code class="language-html highlighter-rouge">date</code> and <code class="language-html highlighter-rouge">quarter</code></li>
  <li>Geographical information like <code class="language-html highlighter-rouge">state</code></li>
</ul>

<h2 id="weapon-table">Weapon Table</h2>

<p>The original data containted a lot of empty values in the <code class="language-html highlighter-rouge">Weapon_Type</code> column. We filled this with label <code class="language-html highlighter-rouge">unknown</code>.</p>

<h2 id="shooter-table">Shooter Table</h2>

<p>The <code class="language-html highlighter-rouge">Age</code> column in this table consists of <code class="language-html highlighter-rouge">string</code> data, like: Adult and <code class="language-html highlighter-rouge">integer</code> data like, 17. While data cleaning, these values were grouped into the following bins:</p>

<ul>
  <li>0-12</li>
  <li>13-17</li>
  <li>18-21</li>
  <li>22-30</li>
  <li>31-50</li>
  <li>50+</li>
</ul>

<p>The missing values in the gender column were set to <code class="language-html highlighter-rouge">unknown</code>.</p>

<h2 id="more-frequent">More Frequent</h2>

<p>In the last decade, school schootings have become a frequent occuring and have been in the news regularly. This motivated us to begin our exploratory data analysis with a time series of the number of incidents in last 50 years in the US to understand how much things have changed. We used the incident table which has shooting incident records from 1970 till now.</p>

<div id="incident_over_time">
</div>

<p>We notice a rising trend in the number of shootings over the years which is almost 1200% increase in five decades. Where in during the 70s the yearly shooting occurrence was as low as 20, to the current time where it is almost 260 yearly. We notice a jump in the number of incidents after 2015 where it has increased almost 4 times.</p>

<h2 id="and-deadlier">…and Deadlier</h2>

<div id="injuried_death_ratio_legend">
</div>

<div id="injuried_death_ratio">
</div>

<p>We focus on the incidents in the 21st century and look at how the number of injuries and deaths has changed over the years. We use a stacked bar chart to better show both number of injuries and deaths in a year. From the graph above we can see an overview of the injuries and deaths ratio, where injuries are more than deaths however we notice that the death to injury ratio was higher in 2012 compared to the rest of the years. Looking at the data of 2012, the Sandy Hook Elementary School incident led to over 25 deaths and is more likely to have skewed the ratio.</p>

<p>Looking at the last 5 years, we see not only the number of incidents which has gone up, but also the number of deaths have increased.</p>

<h2 id="is-it-the-same-for-everywhere">Is it the same for everywhere?</h2>

<div id="statewise">
</div>

<p>Now lets see the state-wise spread of indicidents over the years. To visualize this we used a spike map. Here the length of the spike shows the number of total shooting incidents. As we can observe states like California, Texas, Florida have highest number of incidents followed by Illinois, Michigan, Pennsylvania, Ohio and New York.</p>

<p>On paper these states can also be classified highly populated states, so one might believe thats the reason for the high incident count. California is the most populated state followed by Texas, Florida, New York. These states rank in the top 10 states in terms of population. But, when we look ar population density, these states fall down rank. New Jersey which ranks 2nd in population density has very less shooting incidents (21 incidents) as compared to its neighbour New York (83 incidents). So high population cannot be the sole factor for the incident counts across the states.</p>

<p>Since, we cant generalize the occurences of incidents across all states, we delve further and look at the spread of incidents for each state across the timespan from 1970 to 2022. We can use a heatmap to visualize as it help compare all the states with each other using a sequential color scale.</p>

<div id="heatmap_legend">
</div>
<div id="heatmap">
</div>

<p>As we notice, this visualization is highly similar to the cumulative incident distribution over the years we see initially. There seems to a sharp increase in number of incidents after 2015 across most of the states, denoted by a orange to dark-red shades in the right side of the visualization. Large number of white spaces in heatmap signifies that there is little to no incidents for majortiy of the states for large number of years.</p>

<p>This motivates us to understand recent trends inorder to correlate with current state laws. Hence we shift our focus only to incident occurence after the year 2000. Interesting patterns arise when we inspect state-wise breakdown of data from year 2000. States like California, Texas, Illinois, Florida, Pittsburgh, Ohio has seen higher incidents when compared to rest of the country, with California topping the list five times over the last 6 years. Average number of incidents across the top 5 states over the last 22 years seems to over 7. Sadly, there has been only 15 occurences where the top 5 states didnt have a single incident for an entire year over the last 22 years. Illinois has also the highest number of incidents in the recent years, which motivates us further to focus on this group of states.</p>

<p>If we look at the other end of the spectrum, States like Hawaii, Idaho, North Dakota, US Virgin Islands, West Virginia has low incident count with an average incident occurence of 3.8 per years over the last 22 years. Hence, we decide to compare on these two groups of state in our analysis further.</p>

<div id="heatmap_small_legend">
</div>
<div id="heatmap_small">
</div>

<h2 id="what-weapons-are-the-most-common">What weapons are the most common?</h2>

<div id="piechart_legend">
</div>

<p><strong>States with highest number of incidents</strong></p>

<div id="piechart_high">
</div>

<p><strong>States with lowest number of incidents</strong></p>

<div id="piechart_low">
</div>

<p>Taking a look at the distribution of weapons used in states with the highest and the lowest number of incidents after the year 2000 and dig deeper by looking into the state gun laws. We use a pie chart to visualize this information between the two groups of interest.</p>

<p>Looking at the visualization, <em>handguns</em>, followed by <em>rifles</em> are the top 2 types of weapons used across states with the highest incidents. Interestingly, <em>rifles</em> are not involved in states with lower number of incidents.</p>

<p>While there are one or two incidents where a <em>rifle</em> or <em>multiple rifles</em> were used, the number of casualties in these case is extremely high. Looking at the visualization below, we can see this in the state of Texas, while there was only one incident where <em>multiple rifles</em> were used, the number of deaths in that event contributes nearly to a <strong>quarter</strong> of the total deaths in the state. We see similiar cases in other states with higher number of incidents, like California and Florida.</p>

<h3 id="victims-killed-vs-weapon-used">Victims Killed vs Weapon Used</h3>

<div id="killed_vs_weapon_legend">
</div>
<div id="killed_vs_weapon">
</div>

<h2 id="how-old">How old?</h2>

<div id="age_legend">
</div>
<div id="age">
</div>

<p>After looking at what weapons are used, we now look into who uses them. To get a closer look, the gender of the shooters and to which age group they belong to are visualized. We grouped the ages into six categories: 0-12, 13-17, 18-21, 22-30, 31-50, and 50+ years.</p>

<p>It is highly evident that majority of the shooters were male. The age category of 13-17 cause most number of incidents followed by 18-21 age category. Even among the female gender, we observe age category of 13-17 contribute the highest to the total number of incidents.</p>

<p>This raises concern for school authorities. There can be some psychological reason for that to happen. Our dataset contained two possible reasons namely Domestic Abuse or Bullying. We found these incidents to be not related to them. No domestic violence was found for 1892 incidents out of the total incidents, while 1771 indicated no bullying. So there can be some other reasons, which are not present in our dataset.</p>

<h2 id="gun-laws">Gun Laws</h2>

<p>To make sense of access to the weapons used, we refer to gun laws in states with the highest and lowest incidents.</p>

<p>All states in top 5 except for California and Illinois have little to no restrictions on sales of weapon type, magazine size, and necessity of background checks. Texas is the only state to have <em>campus carry</em>. Campus carry is allows carrying of guns in parking lots, outdoor walkways on campus, and concealed carry in campus buildings.</p>

<p>While some states with least amount of incidents have little to no restrictions, their low number of incidents can be because of extremely low population in these states. States like Hawaii, Idaho, and West Virginia have population less than 2 million, where as North Dakota has population of about 750k and the US Virgin Islands have the least population, around 110k.</p>

<p>In addition to having low population, the state of Hawaii also has stricter gun laws.</p>

<h2 id="do-we-see-a-pattern">Do we see a pattern?</h2>

<div id="trend_legend">
</div>
<div id="trend">
</div>

<p>To uncover seasonality trends, we were interested into seeing what quarter of the year has the most number of incidents. For this, we use a line chart highlighting the last 5 years and plotting number of incidents over quarters.</p>

<p>We observed a couple of things:</p>

<ul>
  <li>There has been a tremendous increase in number of incidents in last 5 years.</li>
  <li>All years have higher number of incidents in Fall.</li>
</ul>

<h2 id="conclusion">Conclusion</h2>

<p>While most states have an age limit of 18 to purchase weapons, We observed that the shooters aged 13-17 contribute the highest. Since they can’t legally buy a weapon, one possible measure is to increase <strong>safe keeping of guns</strong> among adults. Gun safe keeping programs can also be mandated when one purchases a weapon.</p>

<p>In addition to this, increasing the age limit for purchasing weapons to 21 will benefit, as the age range 18-21 has the 2nd highest amount of shooters.</p>

<p>States with no laws restricting access to rifles leads to incidents with higher casualties. Restricting access to automatic rifles, in
all states will significantly reduce the number of fatalities.</p>

<p>Since there are a lot of <em>unknowns</em> in the weapon type feature of the weapons’ table, reducing this could help us uncover patterns.</p>

<p>Looking into the possibility of psychological reasons, we analysed two features from the incident table, namely <em>Domestic Abuse</em> and <em>Bullied</em>. No domestice violence was found for 87% of 2171 total incidents, while 81% indicated no bullying. So there can be many other factors that can be the causes. States should focus on helping schools build a safe space for students to open up about their problems and anxieties and take necessary steps to help them.</p>

<p>These incidents are rising at an alarming rate and have happened in every part of the country. From our analysis, we infer that,there is no single reason which cause school shootings and we believe there cannot be any one single solution that is going to address this problem.</p>

<hr class="l-page home-hr" />

<p><strong>Team:</strong> Atharva Bhagwat, Danna Alamer, Karthik Udhayakumar, Shreeraj Pawar</p>

<script>
  plot1();
  const plot2_legend = {Injuries: '#fed976', Deaths: '#b10026'};
  colorize(plot2_legend, 'injuried_death_ratio_legend');
  plot2();
  plot3();
  plot4();
  plot5();
  const plot678_legend = {Unknown: 'lightgray', Handgun: '#377eb8', Other: '#4daf4a', Rifle: '#984ea3', 'Multiple Handguns': '#ff7f00', 'Multiple Rifles': '#ffff33', Shotgun: '#e41a1c'};
  colorize(plot678_legend, 'piechart_legend');
  colorize(plot678_legend, 'killed_vs_weapon_legend');
  plot678();
  const age_legend = {Unknown: "#1f77b4", Male: "#ff7f0e", Female: "#2ca02c", Transgender: "#d62728"};
  colorize(age_legend, 'age_legend');
  plot9();
  const trend_legend = {2018: "#1f77b4", 2019: "#ff7f0e", 2020: "#2ca02c", 2021: "#d62728", 2022: "#9467bd"};
  colorize(trend_legend, 'trend_legend');
  plot10();
</script>]]></content><author><name>Atharva Bhagwat</name></author><category term="articles" /><summary type="html"><![CDATA[Introduction United states is one of the most diverse and multi-cultural places in the world. It is home to approximately 332 million, of which more than 25% are people under 17 years of age. When compared to other countries, the US has a ratio of 120.5 firearms per 100 residents, up from 88 per 100 in 2011, highest among that of other countries around the world. With increasing number of deaths among people under 17 due to gun violence, schools are eager to find ways to better protect their students. But the steps they are taking like clear bag packs(no bag packs in some cases), risk reinforcing an unhealthy culture of surveillance without actually preventing violence. With recent legislation pushing for gun control within US, we would like to answer questions based on the K-12 school shooting database. Purpose of the project is to look into K-12 school shooting dataset and perform exploratory analysis using visualization techniques in answering potential questions that lawmakers will be interested in, and provide a factual report of these incidents and make this information easily available and understandable. Getting a better grasp of school shootings, as challenging as it might be, is a clear priority for preventing harm and disruption for kids, staff, and families. We would like to start with the number of K-12 schools in the US where school shooting has occurred, by year, with respect to number of victims, analyse patterns across seasons, quarters, and geographical locations. About the Data Source: K-12 School Shooting Database. Riedman, David (2022). Description: K-12 School Shooting Database is an open source database launched and managed by David Riedman in 2018. The data consists of all incidents from 1970 to 2022 and is consistently updated. The dataset is divided in to 4 tables: Incident, Shooter, Victim, and Weapon. We are using subsets of the incident, weapon, and shooter data tables to generate visualization and answer our questions. Subset of indicent table has 2171 entries and 19 columns. All tables have features with missing values, this will be handled during the data analysis phase. Incident Table The table contains 2171 incidents from year 1970 to 2022. Out of all the features in the incident table, analysis focuses on: Measures like victims killed, wounded, and total number of victims Time series data like date and quarter Geographical information like state Weapon Table The original data containted a lot of empty values in the Weapon_Type column. We filled this with label unknown. Shooter Table The Age column in this table consists of string data, like: Adult and integer data like, 17. While data cleaning, these values were grouped into the following bins: 0-12 13-17 18-21 22-30 31-50 50+ The missing values in the gender column were set to unknown. More Frequent In the last decade, school schootings have become a frequent occuring and have been in the news regularly. This motivated us to begin our exploratory data analysis with a time series of the number of incidents in last 50 years in the US to understand how much things have changed. We used the incident table which has shooting incident records from 1970 till now. We notice a rising trend in the number of shootings over the years which is almost 1200% increase in five decades. Where in during the 70s the yearly shooting occurrence was as low as 20, to the current time where it is almost 260 yearly. We notice a jump in the number of incidents after 2015 where it has increased almost 4 times. …and Deadlier We focus on the incidents in the 21st century and look at how the number of injuries and deaths has changed over the years. We use a stacked bar chart to better show both number of injuries and deaths in a year. From the graph above we can see an overview of the injuries and deaths ratio, where injuries are more than deaths however we notice that the death to injury ratio was higher in 2012 compared to the rest of the years. Looking at the data of 2012, the Sandy Hook Elementary School incident led to over 25 deaths and is more likely to have skewed the ratio. Looking at the last 5 years, we see not only the number of incidents which has gone up, but also the number of deaths have increased. Is it the same for everywhere? Now lets see the state-wise spread of indicidents over the years. To visualize this we used a spike map. Here the length of the spike shows the number of total shooting incidents. As we can observe states like California, Texas, Florida have highest number of incidents followed by Illinois, Michigan, Pennsylvania, Ohio and New York. On paper these states can also be classified highly populated states, so one might believe thats the reason for the high incident count. California is the most populated state followed by Texas, Florida, New York. These states rank in the top 10 states in terms of population. But, when we look ar population density, these states fall down rank. New Jersey which ranks 2nd in population density has very less shooting incidents (21 incidents) as compared to its neighbour New York (83 incidents). So high population cannot be the sole factor for the incident counts across the states. Since, we cant generalize the occurences of incidents across all states, we delve further and look at the spread of incidents for each state across the timespan from 1970 to 2022. We can use a heatmap to visualize as it help compare all the states with each other using a sequential color scale. As we notice, this visualization is highly similar to the cumulative incident distribution over the years we see initially. There seems to a sharp increase in number of incidents after 2015 across most of the states, denoted by a orange to dark-red shades in the right side of the visualization. Large number of white spaces in heatmap signifies that there is little to no incidents for majortiy of the states for large number of years. This motivates us to understand recent trends inorder to correlate with current state laws. Hence we shift our focus only to incident occurence after the year 2000. Interesting patterns arise when we inspect state-wise breakdown of data from year 2000. States like California, Texas, Illinois, Florida, Pittsburgh, Ohio has seen higher incidents when compared to rest of the country, with California topping the list five times over the last 6 years. Average number of incidents across the top 5 states over the last 22 years seems to over 7. Sadly, there has been only 15 occurences where the top 5 states didnt have a single incident for an entire year over the last 22 years. Illinois has also the highest number of incidents in the recent years, which motivates us further to focus on this group of states. If we look at the other end of the spectrum, States like Hawaii, Idaho, North Dakota, US Virgin Islands, West Virginia has low incident count with an average incident occurence of 3.8 per years over the last 22 years. Hence, we decide to compare on these two groups of state in our analysis further. What weapons are the most common? States with highest number of incidents States with lowest number of incidents Taking a look at the distribution of weapons used in states with the highest and the lowest number of incidents after the year 2000 and dig deeper by looking into the state gun laws. We use a pie chart to visualize this information between the two groups of interest. Looking at the visualization, handguns, followed by rifles are the top 2 types of weapons used across states with the highest incidents. Interestingly, rifles are not involved in states with lower number of incidents. While there are one or two incidents where a rifle or multiple rifles were used, the number of casualties in these case is extremely high. Looking at the visualization below, we can see this in the state of Texas, while there was only one incident where multiple rifles were used, the number of deaths in that event contributes nearly to a quarter of the total deaths in the state. We see similiar cases in other states with higher number of incidents, like California and Florida. Victims Killed vs Weapon Used How old? After looking at what weapons are used, we now look into who uses them. To get a closer look, the gender of the shooters and to which age group they belong to are visualized. We grouped the ages into six categories: 0-12, 13-17, 18-21, 22-30, 31-50, and 50+ years. It is highly evident that majority of the shooters were male. The age category of 13-17 cause most number of incidents followed by 18-21 age category. Even among the female gender, we observe age category of 13-17 contribute the highest to the total number of incidents. This raises concern for school authorities. There can be some psychological reason for that to happen. Our dataset contained two possible reasons namely Domestic Abuse or Bullying. We found these incidents to be not related to them. No domestic violence was found for 1892 incidents out of the total incidents, while 1771 indicated no bullying. So there can be some other reasons, which are not present in our dataset. Gun Laws To make sense of access to the weapons used, we refer to gun laws in states with the highest and lowest incidents. All states in top 5 except for California and Illinois have little to no restrictions on sales of weapon type, magazine size, and necessity of background checks. Texas is the only state to have campus carry. Campus carry is allows carrying of guns in parking lots, outdoor walkways on campus, and concealed carry in campus buildings. While some states with least amount of incidents have little to no restrictions, their low number of incidents can be because of extremely low population in these states. States like Hawaii, Idaho, and West Virginia have population less than 2 million, where as North Dakota has population of about 750k and the US Virgin Islands have the least population, around 110k. In addition to having low population, the state of Hawaii also has stricter gun laws. Do we see a pattern? To uncover seasonality trends, we were interested into seeing what quarter of the year has the most number of incidents. For this, we use a line chart highlighting the last 5 years and plotting number of incidents over quarters. We observed a couple of things: There has been a tremendous increase in number of incidents in last 5 years. All years have higher number of incidents in Fall. Conclusion While most states have an age limit of 18 to purchase weapons, We observed that the shooters aged 13-17 contribute the highest. Since they can’t legally buy a weapon, one possible measure is to increase safe keeping of guns among adults. Gun safe keeping programs can also be mandated when one purchases a weapon. In addition to this, increasing the age limit for purchasing weapons to 21 will benefit, as the age range 18-21 has the 2nd highest amount of shooters. States with no laws restricting access to rifles leads to incidents with higher casualties. Restricting access to automatic rifles, in all states will significantly reduce the number of fatalities. Since there are a lot of unknowns in the weapon type feature of the weapons’ table, reducing this could help us uncover patterns. Looking into the possibility of psychological reasons, we analysed two features from the incident table, namely Domestic Abuse and Bullied. No domestice violence was found for 87% of 2171 total incidents, while 81% indicated no bullying. So there can be many other factors that can be the causes. States should focus on helping schools build a safe space for students to open up about their problems and anxieties and take necessary steps to help them. These incidents are rising at an alarming rate and have happened in every part of the country. From our analysis, we infer that,there is no single reason which cause school shootings and we believe there cannot be any one single solution that is going to address this problem. Team: Atharva Bhagwat, Danna Alamer, Karthik Udhayakumar, Shreeraj Pawar]]></summary></entry><entry><title type="html">Separating Perception and Reasoning via Relation Networks</title><link href="https://atharvabhagwat.dev/articles/relation-networks" rel="alternate" type="text/html" title="Separating Perception and Reasoning via Relation Networks" /><published>2022-12-11T00:00:00+00:00</published><updated>2022-12-11T00:00:00+00:00</updated><id>https://atharvabhagwat.dev/articles/relation-networks</id><content type="html" xml:base="https://atharvabhagwat.dev/articles/relation-networks"><![CDATA[<p>Visual Question Answering (VQA) is a multi-modal task relating text and images through captions or a questionnaire. For example, with a picture of a busy highway, there could be a question: “How many red cars are there?” or “Are there more motorbikes than cars?”. It is a very challenging task since it requires high-level understanding of both the text and the image and the relationships between them.</p>

<p>In this project, we study the Relation Networks implementations of AI approaches that offer the ability to combine neural and symbolic representations to answer VQA task.</p>

<h2 id="relation-network">Relation Network</h2>

<p>Relation Network is a neural network that works best for relational reasoning. The design philosophy behind RNs is to constrain the functional form of a neural network so that it captures the core common properties of relational reasoning.</p>

<p>The simplest form of RN composite function is:  $RN(O) = f_ϕ(Σ_{i,j}g_θ(o_i, o_j))$ where,</p>

<ul>
  <li>the input is a set of “objects” $O = {o_1, o_2, …, o_n}, o_i ∈ R^m$ is the $i^{th}$ object in an image</li>
  <li>$f_ϕ$ and $g_θ$ are multi-layer perceptrons(MLPs) for the functions with parameters $ϕ$ and $θ$ respectively.</li>
  <li>The role of $g_θ$ is to infer the ways in which two objects are related, or if they are even related at all and $f_ϕ$ is the classifier</li>
</ul>

<h3 id="sort-of-clevr-dataset">Sort-of-CLEVR Dataset</h3>

<p>We’ll be using Sort-of-CLEVR dataset for our RN network.</p>

<p>The Sort-of-CLEVR dataset contains 10000 images of size 75 <em>75</em> 3, 200 of which are used as the validation set.</p>

<p>There are 20 questions for each image (10 non-relational and 10 relational).</p>

<p>The non-relational questions are divided into 3 subtypes:</p>

<ul>
  <li>Query shape, ex: What is the shape of the red object?</li>
  <li>Query horizontal position, ex: Is the red object on the left or right of the image?</li>
  <li>Query vertical position, ex: Iss the red object on the top or bottom of the image?</li>
</ul>

<p>The relational questions are divided into 3 subtypes:</p>

<ul>
  <li>Closest to, ex: What is the shape of the object that is closest to the green object?</li>
  <li>Furthest from, ex: What is the shape of the object that is furthest to the green object?</li>
  <li>Count, ex: How many objects have the shape of the green object?</li>
</ul>

<p>Questions are encoded as binary strings of length 11, where the first 6 bits identify the color of the object mentioned in the question, as a one-hot vector, and the last 5 bits identify the question type and the subtype.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="syntax"><code>[index_0-5 → one-hot vector of 6 colors,

index_6 → non_rel_ques,

index_7 → rel_ques,

index_8,9,10 → question_subtype]
</code></pre></div></div>

<p>Answers are represented as a one-hot vector of size 10.</p>

<p>For non-relational questions the answers are of the form:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="syntax"><code>[index_0,1 → yes, no,

index_2,3 → is rectangle?, is circle?,

index_4-9 → one-hot vector of 6 colors (red, green, blue, orange, gray, yellow)]
</code></pre></div></div>

<p>For relational questions the answers are of the form:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="syntax"><code>[index_0,1 → n/a, n/a,

index_2,3 → is rectangle?, is circle?,

index_4-9 → count one-hot vector to denote the number of objects 0, 1, ..., 5]
</code></pre></div></div>

<h3 id="rn-model-architecture">RN Model Architecture</h3>

<p><img src="/assets/images/articles/relation_network/RN_model_arch.png" alt="rn_arch" /></p>

<p>Data flow through the network is as follows:-</p>

<ul>
  <li>
    <p>Image and Question-Answer feature map:</p>

    <p>1- <strong>Image Feature Maps</strong> are generated using 4 convolutional layers with 32, 64, 128, and 256 kernels with ReLU activation and batch-normalization</p>

    <p>2- <strong>Questions and Answers (labels)</strong> are encoded as fixed-length binary strings</p>
  </li>
  <li>
    <p>RN:</p>

    <p>3- The questions and the feature maps are passed directly to the RN</p>

    <p>4- <strong>Object pairs with questions</strong> (see detailed explanation below) are generated by concatenating questions to the object pairs generated from the CNN feature maps</p>

    <p>5- <strong>Add coordinates position</strong> information for particle image feature</p>

    <p>6- <strong>$g_θ$  function</strong>: The questions are passed directly to the RN along side the object pairs to a 4 layer MLP consisting of 2000 units per layer with ReLU activation</p>

    <p>7- We apply element-wise sum for the output of  $g_θ$  to scale back to the original batch size</p>

    <p>8- <strong>$f_ϕ$  function</strong>: The output is passed to a 4 layer MLP consisting of 2000, 1000, 500, and 100 units with ReLU activation</p>

    <p>9- The final output linear layer in  $f_ϕ$  has a <strong>softmax</strong> activation over the 10 possible answers (answer is a a one-hot vector of size 10)</p>
  </li>
</ul>

<p><strong>Cross entropy loss function</strong> with Adam optimizer is used to train the network.</p>

<p><strong>Hyperparameters for the network:</strong></p>

<ul>
  <li>batch_size = 64</li>
  <li>learning_rate =  $1e−4$</li>
</ul>

<h4 id="object-pairs-with-questions-for-1-image">Object pairs with questions, for 1 image</h4>

<p><img src="/assets/images/articles/relation_network/obj_pairs.png" alt="obj_pairs" /></p>

<p>Questions:</p>

<ul>
  <li>
    <p>Each question one-hot vector is of size (1,11)</p>
  </li>
  <li>
    <p>We add two axes and repeat the questions across one axes, making the dimension (25,1,11)</p>
  </li>
</ul>

<p>Feature Map:</p>

<ul>
  <li>The output feature map for each image is of size (256,5,5)</li>
</ul>

<p>Object pairs with questions:</p>

<ul>
  <li>
    <p>We reshape and add coordinates to the feature map, making the dimension (25, 258)</p>
  </li>
  <li>
    <p>From this, create set 1 and set 2 data</p>
  </li>
  <li>
    <p>Create set 1: add an axis at loc=0 and repeating pixels across rows: (25, 258) -&gt; (1, 25, 258) -&gt; (25,25,258)</p>
  </li>
  <li>
    <p>Create set 2 by adding an axis at loc=1, adding ques of size 11 along that axis and repeating pixels across columns: (25, 258) -&gt; (25, 1, 258) -&gt; (25, 1, 269) -&gt; (25,25,269)</p>
  </li>
  <li>
    <p>Finally, concatenate set 1 and set 2 along the last axes, making the dimension (25,25,527), where</p>

    <p>last_dim_size=(2 for each set*(256 features + 2 coordinates)) + 11 ques = 527</p>
  </li>
</ul>

<p>Check out the <a href="https://github.com/atharva-bhagwat/CSGY-6613/blob/main/milestone1/milestone1.ipynb">code</a> for detailed description on shapes and data transformation.</p>

<h2 id="vqa-on-sort-of-clevr">VQA on Sort-of-CLEVR</h2>

<ul>
  <li>With the <a href="https://github.com/kimhc6028/relational-networks">github repository</a> as reference, we developed the model architecture, keeping the model size smaller than the one given in the paper, but changing the question embedding shape to match that in the paper (length 11).</li>
  <li>We tried many different architectures: by changing the number of units and number of layers in both $g_\theta$ and $f_\phi$. We also tried with different hyper-parameters: learning rates like, $0.0001, 0.01, 0.1$, and optimizers like SGD, Adam.</li>
  <li>Best model architecture:
    <ul>
      <li>4 conv layer block with 24 kernels each with ReLU activation and batch normalization.</li>
      <li>$g_\theta$ consists of 4 fully connected layers with 256 units and ReLU activations.</li>
      <li>$f_\phi$ consists of 4 fully connected layers with 256 units and ReLU activation and an output layer with 10 units with a softmax activation.</li>
    </ul>
  </li>
  <li>Best hyper-parameters:
    <ul>
      <li>number of epochs: 50</li>
      <li>learning rate: $0.001$</li>
      <li>Optimizer: Adam</li>
      <li>Batch size: 64</li>
    </ul>
  </li>
</ul>

<h4 id="results">Results</h4>

<p>After training the model for 50 epochs, the best final metrics are as follows:</p>

<p><strong>Relational Data</strong></p>

<table>
  <thead>
    <tr>
      <th>Train Accuracy(%)</th>
      <th>Train Loss</th>
      <th>Test Accuracy(%)</th>
      <th>Test Loss</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>98.40</td>
      <td>0.045</td>
      <td>91.28</td>
      <td>0.304</td>
    </tr>
  </tbody>
</table>

<p><strong>Non-Relational Data</strong></p>

<table>
  <thead>
    <tr>
      <th>Train Accuracy(%)</th>
      <th>Train Loss</th>
      <th>Test Accuracy(%)</th>
      <th>Test Loss</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>99.98</td>
      <td>0.001</td>
      <td>99.97</td>
      <td>0.001</td>
    </tr>
  </tbody>
</table>

<p>Sample test outputs:</p>

<p><img src="/assets/images/articles/relation_network/test_0.jpg" alt="test_0" /></p>

<p><img src="/assets/images/articles/relation_network/test_45.jpg" alt="test_45" /></p>

<hr class="l-page home-hr" />

<p><strong>Team:</strong> Atharva Bhagwat, Harini Appansrinivasan, Abdulqadir Zakir</p>

<p><a href="https://github.com/atharva-bhagwat/CSGY-6613">Here</a> is the link to the repository.</p>

<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\\(', '\\)']]
  }
};
</script>

<script id="MathJax-script" async="" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>]]></content><author><name>Atharva Bhagwat</name></author><category term="articles" /><summary type="html"><![CDATA[Visual Question Answering (VQA) is a multi-modal task relating text and images through captions or a questionnaire. For example, with a picture of a busy highway, there could be a question: “How many red cars are there?” or “Are there more motorbikes than cars?”. It is a very challenging task since it requires high-level understanding of both the text and the image and the relationships between them. In this project, we study the Relation Networks implementations of AI approaches that offer the ability to combine neural and symbolic representations to answer VQA task. Relation Network Relation Network is a neural network that works best for relational reasoning. The design philosophy behind RNs is to constrain the functional form of a neural network so that it captures the core common properties of relational reasoning. The simplest form of RN composite function is: $RN(O) = f_ϕ(Σ_{i,j}g_θ(o_i, o_j))$ where, the input is a set of “objects” $O = {o_1, o_2, …, o_n}, o_i ∈ R^m$ is the $i^{th}$ object in an image $f_ϕ$ and $g_θ$ are multi-layer perceptrons(MLPs) for the functions with parameters $ϕ$ and $θ$ respectively. The role of $g_θ$ is to infer the ways in which two objects are related, or if they are even related at all and $f_ϕ$ is the classifier Sort-of-CLEVR Dataset We’ll be using Sort-of-CLEVR dataset for our RN network. The Sort-of-CLEVR dataset contains 10000 images of size 75 75 3, 200 of which are used as the validation set. There are 20 questions for each image (10 non-relational and 10 relational). The non-relational questions are divided into 3 subtypes: Query shape, ex: What is the shape of the red object? Query horizontal position, ex: Is the red object on the left or right of the image? Query vertical position, ex: Iss the red object on the top or bottom of the image? The relational questions are divided into 3 subtypes: Closest to, ex: What is the shape of the object that is closest to the green object? Furthest from, ex: What is the shape of the object that is furthest to the green object? Count, ex: How many objects have the shape of the green object? Questions are encoded as binary strings of length 11, where the first 6 bits identify the color of the object mentioned in the question, as a one-hot vector, and the last 5 bits identify the question type and the subtype. [index_0-5 → one-hot vector of 6 colors, index_6 → non_rel_ques, index_7 → rel_ques, index_8,9,10 → question_subtype] Answers are represented as a one-hot vector of size 10. For non-relational questions the answers are of the form: [index_0,1 → yes, no, index_2,3 → is rectangle?, is circle?, index_4-9 → one-hot vector of 6 colors (red, green, blue, orange, gray, yellow)] For relational questions the answers are of the form: [index_0,1 → n/a, n/a, index_2,3 → is rectangle?, is circle?, index_4-9 → count one-hot vector to denote the number of objects 0, 1, ..., 5] RN Model Architecture Data flow through the network is as follows:- Image and Question-Answer feature map: 1- Image Feature Maps are generated using 4 convolutional layers with 32, 64, 128, and 256 kernels with ReLU activation and batch-normalization 2- Questions and Answers (labels) are encoded as fixed-length binary strings RN: 3- The questions and the feature maps are passed directly to the RN 4- Object pairs with questions (see detailed explanation below) are generated by concatenating questions to the object pairs generated from the CNN feature maps 5- Add coordinates position information for particle image feature 6- $g_θ$ function: The questions are passed directly to the RN along side the object pairs to a 4 layer MLP consisting of 2000 units per layer with ReLU activation 7- We apply element-wise sum for the output of $g_θ$ to scale back to the original batch size 8- $f_ϕ$ function: The output is passed to a 4 layer MLP consisting of 2000, 1000, 500, and 100 units with ReLU activation 9- The final output linear layer in $f_ϕ$ has a softmax activation over the 10 possible answers (answer is a a one-hot vector of size 10) Cross entropy loss function with Adam optimizer is used to train the network. Hyperparameters for the network: batch_size = 64 learning_rate = $1e−4$ Object pairs with questions, for 1 image Questions: Each question one-hot vector is of size (1,11) We add two axes and repeat the questions across one axes, making the dimension (25,1,11) Feature Map: The output feature map for each image is of size (256,5,5) Object pairs with questions: We reshape and add coordinates to the feature map, making the dimension (25, 258) From this, create set 1 and set 2 data Create set 1: add an axis at loc=0 and repeating pixels across rows: (25, 258) -&gt; (1, 25, 258) -&gt; (25,25,258) Create set 2 by adding an axis at loc=1, adding ques of size 11 along that axis and repeating pixels across columns: (25, 258) -&gt; (25, 1, 258) -&gt; (25, 1, 269) -&gt; (25,25,269) Finally, concatenate set 1 and set 2 along the last axes, making the dimension (25,25,527), where last_dim_size=(2 for each set*(256 features + 2 coordinates)) + 11 ques = 527 Check out the code for detailed description on shapes and data transformation. VQA on Sort-of-CLEVR With the github repository as reference, we developed the model architecture, keeping the model size smaller than the one given in the paper, but changing the question embedding shape to match that in the paper (length 11). We tried many different architectures: by changing the number of units and number of layers in both $g_\theta$ and $f_\phi$. We also tried with different hyper-parameters: learning rates like, $0.0001, 0.01, 0.1$, and optimizers like SGD, Adam. Best model architecture: 4 conv layer block with 24 kernels each with ReLU activation and batch normalization. $g_\theta$ consists of 4 fully connected layers with 256 units and ReLU activations. $f_\phi$ consists of 4 fully connected layers with 256 units and ReLU activation and an output layer with 10 units with a softmax activation. Best hyper-parameters: number of epochs: 50 learning rate: $0.001$ Optimizer: Adam Batch size: 64 Results After training the model for 50 epochs, the best final metrics are as follows: Relational Data Train Accuracy(%) Train Loss Test Accuracy(%) Test Loss 98.40 0.045 91.28 0.304 Non-Relational Data Train Accuracy(%) Train Loss Test Accuracy(%) Test Loss 99.98 0.001 99.97 0.001 Sample test outputs: Team: Atharva Bhagwat, Harini Appansrinivasan, Abdulqadir Zakir Here is the link to the repository.]]></summary></entry></feed>