<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Simarpreet Singh Bedi on Medium]]></title>
        <description><![CDATA[Stories by Simarpreet Singh Bedi on Medium]]></description>
        <link>https://medium.com/@simarbedi?source=rss-32a35e0d978------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8bcBLAvqs3z9cTvVnqwiZA.jpeg</url>
            <title>Stories by Simarpreet Singh Bedi on Medium</title>
            <link>https://medium.com/@simarbedi?source=rss-32a35e0d978------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:34:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simarbedi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Agent Systems Don’t Fail Linearly — They Degrade. Here’s What I Found Building One]]></title>
            <link>https://medium.com/@simarbedi/agent-systems-dont-fail-linearly-they-degrade-here-s-what-i-found-building-one-69b2a70bd520?source=rss-32a35e0d978------2</link>
            <guid isPermaLink="false">https://medium.com/p/69b2a70bd520</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Simarpreet Singh Bedi]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 20:05:15 GMT</pubDate>
            <atom:updated>2026-04-28T20:05:15.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYcN3GfI4ls6mp9R2FsLVw.png" /><figcaption>Agent Systems Comparison</figcaption></figure><p><em>Most agent systems look impressive — until you introduce failure</em>:</p><ul><li>“Agents can call tools”</li><li>“Agents can collaborate”</li><li>“Agents can plan”</li></ul><p>But almost no one was talking about what happens when things go wrong.</p><p>Not in theory — in an actual system, under failure.</p><p>So instead of building another agent demo, I built a small system to test something more practical:</p><blockquote>How do different agent communication models behave under real-world conditions?</blockquote><h3>What I Built (and Why)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVL8APtlJ2yFUNw181CRzQ.png" /><figcaption>Agent Protocols</figcaption></figure><p>I built a minimal execution framework with:</p><ul><li>A runtime engine</li><li>Two communication models:</li><li>Tool-based (MCP — style)</li><li>Agent-to-agent (A2A)</li><li>Failure injection (timeouts, exceptions, bad responses)</li><li>Structured observability (logs + traces)</li><li>Basic bench-marking</li></ul><p>One deliberate decision:</p><blockquote><em>I didn’t use an LLM initially.</em></blockquote><p>I wanted to understand system behavior without adding randomness on top.</p><h3>Scenario 1: Tool-Based Execution (MCP)</h3><p>The simplest possible flow:</p><p>User → Fetch Data → Call External API → Return Result</p><p>Very controlled. Very predictable.</p><h4>What actually happens</h4><ul><li>Execution is linear</li><li>Each step is isolated</li><li>Failures are easy to detect and retry</li></ul><h4>What breaks</h4><p>Mostly what you’d expect:</p><ul><li>API timeouts</li><li>Schema mismatches</li><li>Invalid responses</li></ul><p>But the key thing is:</p><blockquote><em>When something fails, you know exactly where and why.</em></blockquote><h4>Takeaway</h4><p><strong>MCP is boring — in a good way.</strong></p><p>It optimizes for:</p><ul><li>Control</li><li>Reliability</li><li>Debugging</li></ul><h3>Scenario 2: Agent-to-Agent Communication (A2A)</h3><p>Now replace tools with agents:</p><p>Planner → Log Agent → Metrics Agent → Result</p><p>Same task, different communication model.</p><h4>What changed immediately</h4><ul><li>Execution is no longer strictly linear</li><li>State flows between multiple actors</li><li>Each agent makes its own decision</li><li>What I noticed</li><li>It’s much more flexible than MCP</li><li>Easier to decompose complex tasks</li><li>But harder to reason about</li><li>A small failure example</li></ul><p>I injected a failure in the metrics agent.</p><p>What I expected:</p><ul><li>That step fails, system retries, done</li></ul><p>What actually happened:</p><ul><li>Logs were processed successfully</li><li>Metrics agent failed twice</li><li>Retry kicked in</li><li>Final output was partially complete</li></ul><p>Nothing crashed.</p><p>But now:</p><blockquote><em>The system succeeded… with incomplete information.</em></blockquote><h3>A failure example</h3><p>I injected a timeout failure in the metrics_agent.</p><p>What I expected:</p><blockquote>That step fails, system retries, done</blockquote><p>What actually happened:</p><ul><li>Logs were processed successfully</li><li>Metrics agent failed</li><li>Retry kicked in</li><li>Execution eventually failed</li></ul><p>Here’s what the failure actually looked like in the system:</p><pre>{<br>  &quot;trace_id&quot;: &quot;fcab4fd0-a142-4a59-830d-b436dba7e038&quot;,<br>  &quot;action&quot;: &quot;metrics_agent&quot;,<br>  &quot;stage&quot;: &quot;START&quot;,<br>  &quot;status&quot;: &quot;IN_PROGRESS&quot;<br>}<br>{<br>  &quot;trace_id&quot;: &quot;fcab4fd0-a142-4a59-830d-b436dba7e038&quot;,<br>  &quot;action&quot;: &quot;metrics_agent&quot;,<br>  &quot;stage&quot;: &quot;ERROR&quot;,<br>  &quot;status&quot;: &quot;FAILED&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;error&quot;: &quot;Injected timeout in metrics_agent&quot;<br>  }<br>}<br>{<br>  &quot;trace_id&quot;: &quot;fcab4fd0-a142-4a59-830d-b436dba7e038&quot;,<br>  &quot;event&quot;: &quot;execution_failed&quot;,<br>  &quot;status&quot;: &quot;FAILED&quot;<br>}</pre><p>The important part isn’t just that it failed.</p><p>It’s that:</p><ul><li>The failure is tied to a specific agent</li><li>It propagates to the overall execution</li><li>You need the full trace to understand what happened</li></ul><p>Nothing crashed blindly.</p><p>But the system didn’t succeed cleanly either.</p><blockquote><em>It failed in a way that required interpretation.</em></blockquote><h4>Takeaway</h4><p><strong>A2A doesn’t fail cleanly — it degrades.</strong></p><p>And that’s harder to reason about than a hard failure.</p><h3>Scenario 3: Distributed Decision System</h3><p>This is where things got interesting.</p><p>Instead of a chain, I ran agents in parallel:</p><ul><li>Log analysis</li><li>Metrics analysis</li><li>Behavior analysis</li><li>Then a final agent aggregates everything into a decision.</li></ul><h3>What I observed</h3><ul><li>Agents sometimes disagreed</li><li>Some agents failed</li><li>The system still had to return a decision</li><li>Real behavior</li><li>1 agent fails → system still works</li><li>2 agents fail → confidence drops</li><li>All agents fail → system returns “insufficient data”</li><li>No single failure point.</li></ul><p>But also:</p><blockquote><em>No single source of truth.</em></blockquote><h3>What breaks here</h3><ul><li>Outputs become probabilistic</li><li>Debugging requires full trace reconstruction</li><li>Small issues compound quickly</li><li>Takeaway</li></ul><p><strong>This is no longer a workflow — it’s a distributed system.</strong></p><h3>What Actually Changes Across Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*kLNV-TW-2Y1XLl1mxlt03A.png" /><figcaption>Model Comparison</figcaption></figure><h3>The Most Important Insight</h3><blockquote><em>Agent systems don’t fail linearly — they fail collectively.</em></blockquote><p>This has real implications:</p><ul><li>You can’t debug them step-by-step anymore</li><li>You need end-to-end observability</li><li>You need to design for partial failure, not just success/failure</li></ul><h3>Benchmark Results Under Failure</h3><p>To understand how these systems behave under stress, I ran each scenario 50 times with <strong>70% timeout injection</strong>.</p><h4>Baseline (No Failures)</h4><ul><li>All systems achieved 100% success</li><li>Latency differences were minimal (in-memory execution)</li></ul><h4>Under Failure (70% Timeout Injection)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*_5xjM6az74kLm0zHGpIkjw.png" /><figcaption>failure comparison</figcaption></figure><h4>What’s happening underneath</h4><ul><li><strong>MCP</strong> retries failed tools, but eventually gives up → hard failures</li><li><strong>A2A</strong> propagates failures across agents → sequential brittleness</li><li><strong>Distributed</strong> ignores failed components and proceeds with partial data</li></ul><h4>The key difference</h4><blockquote><em>MCP and A2A try to </em><strong><em>recover from failure</em></strong><em><br> Distributed systems </em><strong><em>adapt to failure</em></strong></blockquote><h4>The trade off</h4><ul><li>Distributed systems are slower (~0.23 ms vs &lt;0.05 ms)</li><li>But significantly more resilient under failure</li></ul><h4>The real insight</h4><blockquote><em>Distributed systems don’t avoid failure — they absorb it by degrading output quality instead of stopping execution.</em></blockquote><h3>Why I Delayed Using an LLM</h3><p>Most systems start with an LLM.</p><p>I didn’t, because:</p><ul><li>It introduces non-determinism</li><li>It hides system-level issues</li><li>It makes failures harder to reproduce</li></ul><p>Once the system was stable, it became clear:</p><blockquote><em>The LLM is just a decision layer — not the system itself.</em></blockquote><h3>When to Use What</h3><h4>Use MCP when:</h4><ul><li>You need predictability</li><li>Strong contracts matter</li><li>Failures must be explicit</li></ul><h4>Use A2A when:</h4><ul><li>Tasks require decomposition</li><li>Flexibility matters more than control</li><li>You can handle coordination overhead</li></ul><h4>Use Distributed Agents when:</h4><ul><li>You’re combining multiple uncertain signals</li><li>You need fault tolerance across components</li><li>You’re okay with probabilistic outcomes</li></ul><h4>What This Changes</h4><p>Most “agent” discussions focus on:</p><ul><li>Planning</li><li>Tool use</li><li>Prompting</li></ul><p>But in practice, the real challenges are:</p><ul><li>Failure handling</li><li>Observability</li><li>Coordination</li></ul><p>And those look a lot more like <strong>distributed systems problems</strong> than AI problems.</p><h3>Final Thought</h3><p>It’s easy to build an agent that works. It’s much harder to build a system that:</p><ul><li>keeps working when parts fail</li><li>explains what it’s doing</li><li>and can be debugged under pressure</li></ul><p>That’s the difference between a demo and something you can trust.</p><blockquote>We don’t just need smarter agents.<br> We need systems that can <strong>survive them</strong>.</blockquote><h3>Code</h3><p>Full project here:</p><p><a href="https://github.com/simarbedi/agentic-protocols">GitHub - simarbedi/agentic-protocols</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69b2a70bd520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowering Smart Buildings: My Journey with Mqtt, BACnet, IoT, and BACpypes]]></title>
            <link>https://medium.com/@simarbedi/empowering-smart-buildings-my-journey-with-mqtt-bacnet-iot-and-bacpypes-6494c1732929?source=rss-32a35e0d978------2</link>
            <guid isPermaLink="false">https://medium.com/p/6494c1732929</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bacnet]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[smart-buildings]]></category>
            <category><![CDATA[mqtt]]></category>
            <dc:creator><![CDATA[Simarpreet Singh Bedi]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 16:01:26 GMT</pubDate>
            <atom:updated>2025-09-24T16:03:45.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Empowering Smart Buildings: My Journey with BACnet, IOT, and BACpypes</h3><p><em>When I first saw a building automation system (BAS) room, I saw dozens of controllers humming, all speaking a language I didn’t understand — BACnet. That was the beginning of my journey…</em></p><figure><img alt="Empowering Smart Buildings" src="https://cdn-images-1.medium.com/max/640/1*UFEsRmG0ApW7NiaxiEnvcQ.jpeg" /><figcaption>Empowering Smart Buildings</figcaption></figure><p>When people imagine <strong>smart buildings</strong>, they think of shiny dashboards, AI-driven energy savings, or voice-controlled offices. But the unsung heroes are the <strong>protocols and data pipelines</strong> that let thousands of devices coordinate behind the scenes.</p><p>My journey into this world began with <strong>MQTT and IoT</strong> and eventually led me deep into <strong>BACnet</strong>, packet sniffers, and even writing my own <strong>BACnet simulator in Python</strong>. Along the way, I discovered both the beauty and the pain of making systems talk to each other.</p><h3>Phase 1: Learning Scale with MQTT</h3><p>We started with an IoT project where <strong>thousands of data points</strong> had to be fetched at regular intervals from distributed equipment.</p><p>To handle this flood, we built a cloud-native pipeline:</p><ul><li><strong>Fetching services</strong> ran in parallel, each pulling data from a set of devices.</li><li>Data was published via <strong>MQTT</strong> into <strong>AWS Greengrass</strong> for local-first reliability.</li><li>A <strong>queue system</strong> ensured decoupling, and a <strong>Dead Letter Queue (DLQ)</strong> retried failures.</li></ul><blockquote>This was my first big lesson:<br> <strong>Scalability isn’t just about speed, it’s about resilience.</strong> A DLQ might not sound glamorous, but it saved us from countless headaches.</blockquote><p>But then we hit a wall: <strong>legacy building devices don’t speak MQTT</strong>. In fact, most buildings speak <strong>BACnet</strong>, <strong>Modbus</strong>, or <strong>LonWorks</strong> — protocols older than the cloud era, but still running entire skyscrapers.</p><h3>Phase 2: Enter BACnet — A Different World</h3><p>BACnet (Building Automation and Control Networks) was standardized in <strong>1995</strong> by ASHRAE, long before IoT became trendy. It’s still the <strong>de facto protocol</strong> for HVAC, lighting, security, and energy systems in commercial buildings.</p><p>Unlike MQTT, BACnet is:</p><ul><li><strong>Peer-to-peer</strong> → devices discover each other with Who-Is/I-Am. No central broker.</li><li><strong>Object-oriented</strong> → each datapoint is an object (AnalogInput, BinaryOutput) with well-defined properties.</li><li><strong>Stateful</strong> → devices hold their own “truth” (like a setpoint or temperature), not just events.</li><li><strong>Service-driven</strong> → interaction happens via services like ReadProperty, WriteProperty, SubscribeCOV (Change of Value).</li></ul><p>To get my hands dirty, I turned to:</p><ul><li><strong>Wireshark</strong> → to sniff and decode BACnet APDUs.</li><li><strong>YABE (Yet Another BACnet Explorer)</strong> → a great GUI tool for device discovery.</li></ul><p>My first thrill came when I broadcast Who-Is in YABE and saw multiple devices reply with I-Am. Suddenly, the building network wasn’t invisible anymore — it was alive.</p><blockquote><strong>Lesson:</strong> MQTT taught me scale, but BACnet taught me <em>visibility</em>.</blockquote><h3>Phase 3: From Observing to Coding with BACpypes</h3><p>Curiosity pulled me to the next step: could I <strong>write my own BACnet client</strong>?</p><p>That’s when I discovered <a href="https://github.com/JoelBender/bacpypes"><strong>BACpypes</strong></a>, a Python library for BACnet. It gave me the building blocks to:</p><ul><li>Create a <strong>local BACnet device</strong>.</li><li>Send Who-Is and parse I-Am.</li><li>Issue ReadProperty and WriteProperty requests.</li></ul><p>Here’s the first time I successfully <strong>wrote a property</strong>:</p><pre>def write_property(self, target_address, object_identifier, property_identifier, value):<br>    request = WritePropertyRequest(<br>        objectIdentifier=object_identifier,<br>        propertyIdentifier=property_identifier,<br>    )<br>    request.pduDestination = Address(target_address)<br>    request.propertyValue = Any()<br>    request.propertyValue.cast_in(Real(value))<br><br>    iocb = IOCB(request)<br>    self.application.request_io(iocb)<br>    iocb.wait(timeout=10)<br><br>    if iocb.ioError:<br>        print(f&quot;Error: {iocb.ioError}&quot;)<br>    else:<br>        print(f&quot;Success: {iocb.ioResponse}&quot;)</pre><p>I’ll never forget the moment I ran this and the controller’s setpoint actually changed. That was my <strong>“I spoke BACnet” moment</strong>.</p><blockquote><strong>Lesson:</strong> In IoT, you often just consume data. In BACnet, you <strong>control reality</strong>.</blockquote><h3>Phase 4: Building My Own BACnet Simulator</h3><p>But I quickly realized: testing against real devices all the time was risky and inconvenient. Controllers are expensive, and one wrong write could disrupt HVAC in an office.</p><p>So I built a <strong>BACnet Device Simulator</strong> in Python with BACpypes.</p><p>It:</p><ul><li>Hosted an AnalogValue object.</li><li>Responded to Who-Is with I-Am.</li><li>Processed WritePropertyRequest to update its presentValue.</li><li>Sent back SimpleAckPDU confirmations.</li></ul><p>Here’s the critical part where it <strong>handles a write</strong>:</p><pre>isinstance(apdu, WritePropertyRequest):<br>    obj = self.data_store.get(apdu.objectIdentifier)<br>    if obj and apdu.propertyIdentifier == &quot;presentValue&quot;:<br>        obj.presentValue = apdu.propertyValue.cast_out(Real)<br>        print(f&quot;Updated {apdu.objectIdentifier} to {obj.presentValue}&quot;)<br><br>        ack = SimpleAckPDU(context=apdu)<br>        ack.pduDestination = apdu.pduSource<br>        self.application.request(ack)</pre><p>The first time I saw my simulator show up in YABE like a real device, I realized I had built a <strong>virtual BACnet lab</strong> on my laptop.</p><blockquote><strong>Lesson:</strong> Simulation is empowerment. It lets you experiment without fear.</blockquote><h3>Phase 5: Architecture Insights</h3><p>Working with both MQTT and BACnet gave me a few lasting insights:</p><ol><li><strong>Communication model matters</strong></li></ol><ul><li>MQTT → brokered, cloud-friendly, great for IoT.</li><li>BACnet → peer-to-peer, network-first, perfect for local building automation.</li></ul><p><strong>2. Debugging mindset differs</strong></p><ul><li>MQTT → logs, retries, DLQs.</li><li>BACnet → packet sniffing, device discovery, service-level responses.</li></ul><p><strong>3. Bridging is the future</strong><br> The real challenge is not choosing MQTT <em>or</em> BACnet — it’s bridging them. Many modern smart building gateways now speak both, mapping BACnet objects to MQTT topics.</p><p><strong>4. Standardization is key</strong><br> Ontologies like <strong>Brick Schema</strong> are emerging to unify BACnet, Modbus, MQTT, and proprietary points under one semantic layer.</p><blockquote><strong>Big Lesson:</strong> Smart buildings are not about replacing protocols. They’re about orchestrating them together.</blockquote><h3>Practical Walkthrough: Try It Yourself</h3><p>If you want to experiment without hardware, here’s a simple path:</p><ol><li><strong>Install BACpypes</strong></li></ol><pre>pip install bacpype</pre><p><strong>2. Run the Simulator</strong><br> Start the simulator script. It’ll boot as a virtual BACnet device.</p><p><strong>3. Open YABE</strong><br> Broadcast a Who-Is. Watch the simulator reply with I-Am.</p><p><strong>4. Write a Value</strong><br> Change the AnalogValue property in YABE. The simulator updates and sends back an acknowledgment.</p><p><strong>5. Extend It</strong><br> Add more objects, or hook the simulator into your IoT stack via MQTT.</p><h3>Looking Ahead</h3><p>Today, I’m exploring:</p><ul><li><strong>Rule engines</strong> → concurrent evaluation of thousands of building conditions.</li><li><strong>Semantic models</strong> → Brick Schema + BACnet for standardization.</li><li><strong>Natural interfaces</strong> → imagine asking: <em>“What’s the average temperature on Floor 2?”</em> and getting a live answer.</li></ul><p>Every step builds on the foundations I shared above: MQTT taught me resilience. BACnet taught me interoperability. BACpypes gave me the playground.</p><p>For reference to the code you can check my <a href="https://github.com/simarbedi/smart-buildings">GitHub </a>repository</p><h3>References</h3><ul><li><a href="https://bacpypes.readthedocs.io/en/latest/">Welcome to BACpypes - BACpypes</a></li><li><a href="https://sourceforge.net/projects/yetanotherbacnetexplorer/">Yet Another BACnet Explorer</a></li><li><a href="https://mqtt.org/">MQTT - The Standard for IoT Messaging</a></li><li><a href="https://www.wireshark.org/">Wireshark * Go Deep</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6494c1732929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NgRx state management with RxJs]]></title>
            <link>https://medium.com/@simarbedi/ngrx-state-management-with-rxjs-2b33a06a98e2?source=rss-32a35e0d978------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b33a06a98e2</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[ngrx-effects]]></category>
            <category><![CDATA[ngrx-store]]></category>
            <dc:creator><![CDATA[Simarpreet Singh Bedi]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 13:24:45 GMT</pubDate>
            <atom:updated>2023-10-27T13:24:45.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G-VBjdwnL8MJBD1o.png" /><figcaption>NGRX store state management.</figcaption></figure><p>The Store is an RxJS-powered state management tool designed to improve performance in angular applications. This will mainly include four main files for managing the store.</p><ul><li>Reducers: they include the current state and the latest action to compute a new state.</li><li>Actions: they include events that can be dispatched from components and services.</li><li>Selectors: they include functions that are used to select, derive, and compose pieces of state.</li><li>Effects: they are used for interacting with external resources directly through services.</li></ul><p>Let&#39;s get started with the tutorial.</p><h4><strong>Installation</strong></h4><ol><li>Once you have created a new angular application, let’s install the NGRX store in our application using npm install @ngrx/store — save or yarn add @ngrx/store or ng add @ngrx/store. Use the appropriate version as per your angular version</li><li>Then we will add the dev tools dependency for debugging purposes using npm install @ngrx/store-devtools or yarn add @ngrx/store-devtools or ng add @ngrx/store-devtools</li><li>Now we will modify and add imports to our app.module.ts file</li></ol><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br><br>import { AppRoutingModule } from &#39;./app-routing.module&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { StoreModule } from &#39;@ngrx/store&#39;;<br>import { StoreDevtoolsModule } from &#39;@ngrx/store-devtools&#39;;<br>import { environment } from &#39;../environments/environment&#39;;<br>import { notesReducer } from &#39;./state/notes/notes.reducer&#39;;<br>import { EffectsModule } from &#39;@ngrx/effects&#39;;<br>import { NotesEffects } from &#39;./state/notes/notes.effects&#39;;<br><br>@NgModule({<br>    declarations: [AppComponent],<br>    imports: [<br>        BrowserModule,<br>        AppRoutingModule,<br>        StoreModule.forRoot({ notes: notesReducer }),<br>        StoreDevtoolsModule.instrument({ maxAge: 25, logOnly: environment.production }),<br>        EffectsModule.forRoot([NotesEffects]),<br>    ],<br>    providers: [],<br>    bootstrap: [AppComponent],<br>})<br>export class AppModule {}</pre><h4>Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Xh-El7amOWHY7ZSQ7We8bQ.png" /><figcaption>State directory structure</figcaption></figure><p>Create a directory under the app directory named state which will hold all the store-related code for your components. Create a notes folder that will contain the action, reducer, selector, and effects file. Also, create an app.state.ts file for maintaining multiple states.</p><h4>Actions</h4><p>We will start with the notes action file where we will declare all the effects we want to trigger in our code. It can contain things like adding and removing functions which we will define in the reducers file.</p><pre>import { createAction, props } from &#39;@ngrx/store&#39;;<br>import { Note } from &#39;src/app/shared/note.model&#39;;<br><br>export const addNote = createAction(&#39;[Note Page] Add Note&#39;, props&lt;{ note:Note }&gt;());<br><br>export const removeNote = createAction(&#39;[Note Page] Remove Note&#39;, props&lt;{ id: number }&gt;());<br><br>export const loadNotes = createAction(&#39;[Note Page] Load Notes&#39;);<br><br>export const loadNotesSuccess = createAction(&#39;[Note API] Note Load Success&#39;, props&lt;{ notes: Note[] }&gt;());<br><br>export const loadNotesFailure = createAction(&#39;[Note API] Note Load Failure&#39;, props&lt;{ error: string }&gt;());</pre><h4>Reducers</h4><p>Here we define all our actions that work on altering/modifying the store maintained in the store.</p><pre>import { createReducer, on } from &#39;@ngrx/store&#39;;<br>import { Note } from &#39;src/app/shared/note.model&#39;;<br>import { addNote, removeNote, loadNotes, loadNotesSuccess, loadNotesFailure } from &#39;./notes.actions&#39;;<br><br>export interface NotesState {<br>    notes: Note[];<br>    error: string|null;<br>    status: &#39;pending&#39; | &#39;loading&#39; | &#39;error&#39; | &#39;success&#39;;<br>}<br><br>export const initialState: NotesState = {<br>    notes: [],<br>    error: null,<br>    status: &#39;pending&#39;,<br>};<br><br>export const notesReducer = createReducer(<br>    // Supply the initial state<br>    initialState,<br>    // Add the new note to the notes array<br>    on(addNote, (state, { note }) =&gt; ({<br>        ...state,<br>        notes: [...state.notes, note],<br>    })),<br>    // Remove the note from the notes array<br>    on(removeNote, (state, { id }) =&gt; ({<br>        ...state,<br>        notes: state.notes.filter((note) =&gt; note.id !== id),<br>    })),<br>    // Trigger loading the notes<br>    on(loadNotes, (state) =&gt; ({ ...state, status: &#39;loading&#39; })),<br>    // Handle successfully loaded notes<br>    on(loadNotesSuccess, (state, { notes }) =&gt; ({<br>        ...state,<br>        notes: notes,<br>        error: null,<br>        status: &#39;success&#39;,<br>    })),<br>    // Handle notes load failure<br>    on(loadNotesFailure, (state, { error }) =&gt; ({<br>        ...state,<br>        error: error,<br>        status: &#39;error&#39;,<br>    })),<br>);</pre><h4>Selectors</h4><p>These files contain the pure functions that we utilize for getting data from the store.</p><pre>import { createSelector } from &#39;@ngrx/store&#39;;<br>import { AppState } from &#39;../app.state&#39;;<br>import { NotesState } from &#39;./notes.reducer&#39;;<br><br>export const selectNotes = (state: AppState) =&gt; state.notes;<br>export const selectAllNotes = createSelector(selectNotes, (state: NotesState) =&gt; state.notes);</pre><h4>Effects</h4><p>These files contain the logic to be triggered when some action occurs. We connect to the service files through the effects and update the store</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Actions, createEffect, ofType } from &#39;@ngrx/effects&#39;;<br>import { of, from } from &#39;rxjs&#39;;<br>import { switchMap, map, catchError, withLatestFrom } from &#39;rxjs/operators&#39;;<br>import { Store } from &#39;@ngrx/store&#39;;<br>import { AppState } from &#39;../app.state&#39;;<br>import { NotesService } from &#39;src/app/shared/notes.service&#39;;<br>import { addNote, loadNotes, loadNotesFailure, loadNotesSuccess, removeNote } from &#39;./notes.actions&#39;;<br>import { selectAllNotes} from &#39;./notes.selector&#39;;<br><br>@Injectable()<br>export class NotesEffects {<br>    constructor(<br>        private actions$: Actions,<br>        private store: Store&lt;AppState&gt;,<br>        private notesService: NotesService,<br>    ) {}<br><br>    // Run this code when a loadNotes action is dispatched<br>    loadNotes$ = createEffect(() =&gt;<br>        this.actions$.pipe(<br>            ofType(loadNotes),<br>            switchMap(() =&gt;<br>                // Call the getNodes method, convert it to an observable<br>                from(this.notesService.getAll()).pipe(<br>                    // Take the returned value and return a new success action containing the notes<br>                    map((notes) =&gt; loadNotesSuccess({ notes: notes })),<br>                    // Or... if it errors return a new failure action containing the error<br>                    catchError((error) =&gt; of(loadNotesFailure({ error }))),<br>                ),<br>            ),<br>        ),<br>    );<br><br>    // Run this code when the addNote action is dispatched<br>    saveTodos$ = createEffect(<br>        () =&gt;<br>            this.actions$.pipe(<br>                ofType(addNote),<br>                switchMap((action) =&gt; <br>                    from(this.notesService.add(action.note)).pipe(<br>                        map((note)=&gt;{<br>                            console.log(note+&#39;added successfully&#39;);<br>                        }),<br>                    )),<br>            ),<br>        <br>        { dispatch: false },<br>    );<br>}</pre><p>For the app state file, you have to define the state for global usage.</p><pre>import { NotesState } from &quot;./notes/notes.reducer&quot;;<br><br>export interface AppState {<br>    notes: NotesState;<br>}</pre><p>Next, you can call the selector to get the data and use it to render data in your application</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { Store } from &#39;@ngrx/store&#39;;<br>import { Note } from &#39;src/app/shared/note.model&#39;;<br>import { NotesService } from &#39;src/app/shared/notes.service&#39;;<br>import { AppState } from &#39;src/app/state/app.state&#39;;<br>import { loadNotes, removeNote } from &#39;src/app/state/notes/notes.actions&#39;;<br>import { selectAllNotes } from &#39;src/app/state/notes/notes.selector&#39;;<br><br>@Component({<br>    selector: &#39;app-notes-list&#39;,<br>    templateUrl: &#39;./notes-list.component.html&#39;,<br>    styleUrls: [&#39;./notes-list.component.sass&#39;],<br>})<br>export class NotesListComponent implements OnInit {<br>    public notes$ = this.store.select(selectAllNotes);<br>    constructor(<br>        private notesService: NotesService,<br>        private store: Store&lt;AppState&gt;,<br>    ) {}<br><br>    ngOnInit(): void {<br>         this.store.dispatch(loadNotes());<br>    }<br><br>    deleteNote(id: number) {<br>        this.store.dispatch(removeNote(id))<br>    }<br>}</pre><p>You can use an async pipe to directly render the data</p><pre>&lt;div class=&quot;notes-list&quot;&gt;<br>        &lt;app-note-card<br>            *ngFor=&quot;let note of notes$ | async ; index as i&quot;<br>            [link]=&quot;note.id&quot;<br>            (delete)=&quot;deleteNote(note.id)&quot;<br>            [title]=&quot;note.title&quot;<br>            [body]=&quot;note.body&quot;<br>        &gt;&lt;/app-note-card&gt;<br>    &lt;/div&gt;</pre><p>For reference to the code you can check my <a href="https://github.com/simarbedi/notes-app">GitHub</a> repository</p><h4>References</h4><ul><li><a href="https://ngrx.io/">NgRx</a></li><li><a href="https://www.learnrxjs.io/">Introduction | Learn RxJS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b33a06a98e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch functions you didn’t know you needed]]></title>
            <link>https://medium.com/@simarbedi/pytorch-functions-you-didnt-know-you-needed-5d97bb837e45?source=rss-32a35e0d978------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d97bb837e45</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Simarpreet Singh Bedi]]></dc:creator>
            <pubDate>Fri, 29 May 2020 00:22:27 GMT</pubDate>
            <atom:updated>2020-05-29T08:33:07.148Z</atom:updated>
            <content:encoded><![CDATA[<h4>PyTorch for Machine Learning and Deep Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SaBxURdGLX8bnMiRwnxAQ.png" /></figure><blockquote>PyTorch is an open-source machine learning library which is getting very popular nowadays. It seems to have become one of the favourites among deep learning practitioners. It is used for applications such as computer vision and natural language processing and is primarily developed by Facebook’s AI Research lab. It’s a deep learning research platform that provides maximum flexibility and speed. It’s pythonic and easy to understand and deploy especially on mobile platforms.</blockquote><p>In today’s blog, I am going to share some PyTorch Functions which one should know and use in their daily machine learning or deep learning projects. These are some of the essential functions that everyone should take advantage of for simplifying their projects and pipelines.</p><h3>PyTorch Tensors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*--Q49Wp11-t386hdl-LVYg.jpeg" /><figcaption>PyTorch Tensors</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-pytorch-basics%2Fv%2F4%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-pytorch-basics%2Fv%2F4%26cellId%3D6&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1fb6cbb52ae6315038568bceca0c30c/href">https://medium.com/media/d1fb6cbb52ae6315038568bceca0c30c/href</a></iframe><blockquote>Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.</blockquote><blockquote>Tensor Functions</blockquote><h3>1. torch.topk()</h3><blockquote>When we use torch.topk(), it returns the k largest elements of the given input tensor along a given dimension.</blockquote><p>In the below example we have taken a tensor X and are finding out the top 3 values from the tensor. This function also returns the indices of the top values.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D3&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6945264f8c775e226ee6ebf8bd8acacc/href">https://medium.com/media/6945264f8c775e226ee6ebf8bd8acacc/href</a></iframe><p>We can also apply topk function on any dimensional tensor. Here we apply it on a 2D tensor Y and find top 2 values. We can also change the function to find the top smallest value by changing parameter largest=False.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D5&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/368753a64d2365ac96660f345f949c94/href">https://medium.com/media/368753a64d2365ac96660f345f949c94/href</a></iframe><h3>2. torch.pow()</h3><blockquote>When we use torch.pow(), it takes the power of each element in input with exponent and returns a tensor with the result. Exponent can be either a single float number or a Tensor with the same number of elements as input.</blockquote><p>In the example below, we have taken a tensor X and are finding the square of values from the tensor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D11&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f71ecfdd96473eeb5b47daf3ad5f4e7/href">https://medium.com/media/7f71ecfdd96473eeb5b47daf3ad5f4e7/href</a></iframe><p>We can also take different exponential powers for different values of the tensor. Here we take the 1D tensor Y and apply exponents present in exponent tensor over it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D13&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3edf3889feb586a4cd4829ce596baaa8/href">https://medium.com/media/3edf3889feb586a4cd4829ce596baaa8/href</a></iframe><h3>3. torch.unique()</h3><blockquote>When we use torch.unique() function, it returns the unique elements of the input tensor.</blockquote><p>In the example below, we have taken a tensor X and are finding out the unique values from the tensor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D19&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D19&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d5fd6a584e2e188585fdbd34220af6f/href">https://medium.com/media/6d5fd6a584e2e188585fdbd34220af6f/href</a></iframe><p>We can also apply the unique function on any dimensional tensor. Here we apply it on a 2D tensor Y and find all unique values. We can also find the indices of the unique values from the original tensor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D21&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D21&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1ef66b4c93f74dc1639725a04ede197/href">https://medium.com/media/e1ef66b4c93f74dc1639725a04ede197/href</a></iframe><h3>4. torch.det()</h3><blockquote>When we use torch.det() , it calculates and returns the determinant of a square matrix or batches of square matrices.</blockquote><p>In the example below, we have taken a tensor X and are finding out the determinant of the tensor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D27&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f02109953df0239946fb1459f43910ad/href">https://medium.com/media/f02109953df0239946fb1459f43910ad/href</a></iframe><h3>5. torch.chain_matmul()</h3><blockquote>When we use torch.chain_matmul() , it returns the matrix product of the<strong> </strong>provided<strong> N </strong>2-D tensors. This product is efficiently computed using the matrix chain order algorithm which selects the order in which incurs the lowest cost in terms of arithmetic operations.</blockquote><p>In the example below, we have taken tensors A,B,C and D and are doing the chain matrix multiplication of the tensors.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D37&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsimarbedi76%2F01-tensor-operations-90d45%2Fv%2F1%26cellId%3D37&amp;image=https%3A%2F%2Fjovianml.s3.amazonaws.com%2Fpreview-large.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1e244fefb343be73f54e72d9abeb3c0/href">https://medium.com/media/e1e244fefb343be73f54e72d9abeb3c0/href</a></iframe><h3><strong>Conclusion:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pxBktpA3zHEWnHPzMavNgA.png" /></figure><blockquote>In this blog, we have gone through some of the PyTorch functions which are important but people mostly ignore them. One should use them for creating a cleaner and better project.</blockquote><p>For more examples:</p><p><a href="https://jovian.ml/simarbedi76/01-tensor-operations-90d45">https://jovian.ml/simarbedi76/01-tensor-operations-90d45</a></p><h3>References:</h3><ul><li>Official documentation:<a href="https://jovian.ml/outlink?url=https%3A%2F%2Fpytorch.org%2Fdocs%2Fstable%2Ftensors.html">https://pytorch.org/docs/stable/tensors.html</a></li><li>My Code: <a href="https://jovian.ml/simarbedi76/01-tensor-operations-90d45">https://jovian.ml/simarbedi76/01-tensor-operations-90d45</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d97bb837e45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>