<?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 Kaushik Shamantha on Medium]]></title>
        <description><![CDATA[Stories by Kaushik Shamantha on Medium]]></description>
        <link>https://medium.com/@kaushikshamantha?source=rss-702167d2cc2d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4LTYzbKxsEnClo_QDZP2xw@2x.jpeg</url>
            <title>Stories by Kaushik Shamantha on Medium</title>
            <link>https://medium.com/@kaushikshamantha?source=rss-702167d2cc2d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:14:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaushikshamantha/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[Factory + Strategy ETL Example]]></title>
            <link>https://kaushikshamantha.medium.com/factory-strategy-etl-example-53fdb06c22d8?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/53fdb06c22d8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 07:42:00 GMT</pubDate>
            <atom:updated>2026-07-07T07:42:00.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYWGlIy0xy3eRpD2VZcKRA.png" /></figure><p>Factory and Strategy, 2 design patterns that save ETL pipelines from themselves. <strong>The Factory</strong> looks at the new data and picks the right tool and <strong>The Strategy</strong> is the tool itself that processes the data.</p><p>Every data engineer eventually inherits this function,</p><pre>def get_orders(source_type, config):<br>    if source_type == &quot;rest&quot;:<br>        response = ...<br>        data     = ...<br>        orders   = ...<br><br>    elif source_type == &quot;soap&quot;:<br>        client = ...<br>        data   = ...<br>        orders = ...<br><br>    # ... and it keeps growing<br><br>    return orders</pre><p>It works. It ships. And six months later, when the fourth integration partner shows up wanting a GraphQL feed, someone adds an elif.</p><p>Then a fifth partner. Then someone needs to unit test the REST normalization logic in isolation and discovers it’s tangled up with a live REST connection inside the same function.</p><p>This is the point where two classic design patterns<strong> <em>“Factory and Strategy</em>”.</strong></p><ol><li><strong>Which client do I need to talk to this source?</strong> (REST client, SOAP client, SFTP connection, etc)</li><li><strong>How do I map this source’s raw shape into my internal model?</strong> (JSON keys, PascalCase XML fields, CSV columns with European decimal commas)</li></ol><h4>Factory: Encapsulating which object gets created</h4><pre>from abc import ABC, abstractmethod<br><br>class Extractor(ABC):<br>    @abstractmethod<br>    def extract(self) -&gt; list[dict]:<br>        ...<br><br>class RESTExtractor(Extractor):<br>    def __init__(self, endpoint: str, api_key: str):<br>        self.endpoint, self.api_key = endpoint, api_key<br><br>    def extract(self) -&gt; list[dict]:<br>        # impementation<br><br>class SFTPExtractor(Extractor):<br>    def __init__(self, host: str, remote_path: str):<br>        self.host, self.remote_path = host, remote_path<br><br>    def extract(self) -&gt; list[dict]:<br>        # impementation<br><br><br>class ExtractorFactory:<br>    _registry: dict[str, type[Extractor]] = {<br>        &quot;rest&quot;: RESTExtractor,<br>        &quot;sftp&quot;: SFTPExtractor,<br>    }<br><br>    @classmethod<br>    def create(cls, source_type: str, **kwargs) -&gt; Extractor:<br>        try:<br>            return cls._registry[source_type](**kwargs)<br>        except KeyError:<br>            raise ValueError(f&quot;Unknown source type: {source_type!r}&quot;)<br><br>    @classmethod<br>    def register(cls, source_type: str, extractor_cls: type[Extractor]) -&gt; None:<br>        cls._registry[source_type] = extractor_cls</pre><p>The Factory pattern’s job is narrow, given some identifier, hand back the right object and hide the construction details from the caller.</p><p>Adding a sixth source now means writing one new class and adding one line to _registry or even calling register() from a plugin module, without editing ExtractorFactory at all. That&#39;s the Open and Closed Principle in practice that open for extension and closed for modification.</p><h4>Strategy: Encapsulating how the transformation happens</h4><pre>from dataclasses import dataclass<br>from decimal import Decimal<br><br>@dataclass<br>class Order:<br>    order_id: str<br>    customer_email: str<br>    sku: str<br>    quantity: int<br>    total_amount: Decimal = Decimal(0)<br><br><br>class TransformStrategy(ABC):<br>    @abstractmethod<br>    def transform(self, raw: dict) -&gt; Order:<br>        ...<br><br>class RESTTransform(TransformStrategy):<br>    def transform(self, raw: dict) -&gt; Order:<br>        return Order(<br>            order_id=raw[&quot;id&quot;],<br>            customer_email=raw[&quot;email&quot;],<br>            sku=raw[&quot;item&quot;],<br>            quantity=int(raw[&quot;qty&quot;]),<br>            total_amount=Decimal(raw[&quot;price&quot;]),<br>        )<br><br>class SFTPTransform(TransformStrategy):<br>    def transform(self, raw: dict) -&gt; Order:<br>        # the flat file hands back European-style decimal commas<br>        amount = Decimal(raw[&quot;total&quot;].replace(&quot;,&quot;, &quot;.&quot;))<br>        return Order(<br>            order_id=raw[&quot;order_id&quot;],<br>            customer_email=raw[&quot;email&quot;],<br>            sku=raw[&quot;sku&quot;],<br>            quantity=int(raw[&quot;quantity&quot;]),<br>            total_amount=amount,<br>        )</pre><p>Once you have raw data, you still need to shape it into your internal model. This is where Strategy comes in. It takes the “how do I transform this” decision and turns it into an interchangeable object instead of a branch.</p><h4>Wiring them together</h4><pre>class OrderPipeline:<br>    def __init__(self, source_type: str, extractor_kwargs: dict, strategies: dict):<br>        self.extractor = ExtractorFactory.create(source_type, **extractor_kwargs)<br>        self.transform_strategy = strategies[source_type]<br><br>    def run(self) -&gt; list[Order]:<br>        raw_records = self.extractor.extract()<br>        return [self.transform_strategy.transform(r) for r in raw_records]</pre><p>The pipeline itself never grows. It doesn’t know or care whether it’s talking to REST, SOAP or SFTP. It just asks the factory for an extractor and asks the registry for a strategy. All the source-specific knowledge lives in small, single-purpose classes that can be tested, replaced, or extended independently.</p><p>The patterns pay off when at least one of these is true,</p><ul><li>You genuinely expect the number of sources to grow (new integration partners, new vendors, new file formats)</li><li>The transformation logic is complex enough that you want to unit test it in isolation from I/O</li><li>Different teams own different sources and need to add one without risking the others</li></ul><h4>Why it is so cool</h4><blockquote><em>Factory and Strategy solve two different problems that tend to show up together in ETL work. Which object do I build and how do I transform what it gives me.</em></blockquote><blockquote><em>Naming them separately rather than letting both live in one sprawling conditional is what makes a pipeline easy to extend, easy to test and easy for the next engineer to reason about without reading the whole file.</em></blockquote><h4>Worth checking these out too!</h4><ul><li><a href="https://www.startdataengineering.com/post/code-patterns/">https://www.startdataengineering.com/post/code-patterns/</a></li><li><a href="https://refactoring.guru/design-patterns">https://refactoring.guru/design-patterns</a></li><li>Feel free to grill Gemini or any other LLM with questions until you’ve totally cleared up these design patterns.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53fdb06c22d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget PostGIS! Building a Modern Geospatial Stack with DuckDB and Streamlit]]></title>
            <link>https://kaushikshamantha.medium.com/forget-postgis-building-a-modern-geospatial-stack-with-duckdb-and-streamlit-d881e07694c8?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d881e07694c8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 09:15:21 GMT</pubDate>
            <atom:updated>2026-04-21T09:15:21.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbiHjfgHIxjxC_r6Tajfmw.png" /></figure><h3>Introduction</h3><p>For a long time, if you wanted to do serious geospatial analysis, you had to manage bulky PostGIS database and struggle with complex GIS software. But the landscape has shifted.</p><blockquote>I’m at the “xyz”; which pharmacies can I drive to in under 10 minutes?</blockquote><p>In this article, I’ll walk you through a pipeline I built for a recent geospatial project. We will move from raw OpenStreetMap data to a fully interactive web application using a modern “Lightweight” stack.</p><ul><li><strong>OSMNX</strong> provides the raw data (the <em>where</em>).</li><li><strong>OpenRouteService</strong> provides the constraints (the <em>how long</em>).</li><li><strong>DuckDB</strong> provides the lightning-fast analysis (the <em>who</em>).</li></ul><h4>The “Brain” of the Routing: OpenRouteService (ORS)</h4><p>Calculating the area reachable from a point within a certain time or distance. This is the core of “10-minute reachability” logic.</p><p><strong>Why use ORS instead of Google Maps API?</strong></p><p>For a developer or an urban planner, ORS has several major advantages:</p><ul><li>Cost: It is completely free if you host it yourself (which you are doing via Docker on localhost:8080).</li><li>Customization: You can tell ORS to prioritize different modes of transport, such as driving-car, cycling-regular, or foot-walking.</li><li>Open Data: Because it is built on OpenStreetMap, you can see exactly why it chose a certain route, making your analysis transparent for a Medium article.</li></ul><h4>Feature Extraction (Finding the “Points”): <strong>OSMNX</strong></h4><p>OSMNX searches the entire database for anything tagged as a hospital and returns it to you as a GeoPandas GeoDataFrame.</p><h3>How to set it up</h3><h4>Setting up the OpenRouteService (ORS) Engine</h4><p>If you have Docker installed, you can get a local instance running by following the <a href="https://giscience.github.io/openrouteservice/run-instance/running-with-docker">Official ORS Docker Guide</a>.</p><p><strong>Default Configuration:</strong> My project is pre-configured for <strong>Heidelberg, Germany</strong>. If you want to follow along exactly, you should download the heidelberg.osm.pbf (or the broader baden-wuerttemberg region) from <a href="https://download.geofabrik.de/">Geofabrik</a>.</p><p><strong>Customizing Your Area:</strong> You can analyze <em>any</em> city in the world by simply:</p><ul><li>Downloading the corresponding .osm.pbf file for that region.</li><li>Place it in the /docker/data folder of your ORS setup.</li><li>Updating the City input in the Streamlit UI.</li></ul><p>Heidelberg is a classic choice for GIS tutorials (and the home of the <a href="https://www.google.com/search?q=https://www.geog.uni-heidelberg.de/gis/index_en.html">GIScience Research Group</a> that created ORS!).</p><h4>Getting the Code</h4><p>The full source code for this project, including the SpatialEngine, the Router wrapper, and the Streamlit dashboard, is available on GitHub.</p><p><a href="https://github.com/kaushik0911/jubilant-guide">kaushik0911/jubilant-guide</a></p><ol><li><strong>Clone the repo:</strong> git clone <a href="https://github.com/kaushik0911/jubilant-guide.git">https://github.com/kaushik0911/jubilant-guide.git</a></li><li><strong>Install dependencies:</strong> pip install -r requirements.txt</li><li><strong>Start OpenRouteService:</strong> Ensure your Docker container is running (as described in the setup section).</li><li><strong>Launch the App:</strong> Run streamlit run app.py</li></ol><h3>The Code</h3><p><strong>Fetch all specific locations (like all hospitals in Heidelberg) from the real world.</strong></p><p>It uses <em>ox.features_from_place</em> to query the OpenStreetMap (OSM) database. It filters the entire city for a specific “tag” (e.g., amenity: hospital).</p><pre># data_processor.py<br><br>def get_pois(self, city_name, amenity=&quot;hospital&quot;):<br><br>    gdf = ox.features_from_place(city_name, tags={&quot;amenity&quot;: amenity})<br><br>    gdf = gdf.reset_index()<br>    gdf = gdf[gdf.geom_type == &quot;Point&quot;][[&quot;name&quot;, &quot;geometry&quot;]].copy()<br>    gdf[&quot;geometry&quot;] = gdf[&quot;geometry&quot;].to_wkb()<br><br>    self.con.register(&quot;raw_pois&quot;, gdf)<br><br>    return gdf</pre><p><strong>Generate the “Travel Blob” (the area reachable within X minutes).</strong></p><p>This function sends a POST request to your local OpenRouteService (ORS) instance.</p><pre># routing.py<br><br>import requests<br><br><br>class Router:<br>    def __init__(self):<br>        self.base_url = &quot;http://localhost:8080/ors/v2/isochrones/driving-car&quot;<br><br>    def get_isochrone(self, lat, lon, time_limit=10):<br>        time_seconds = [time_limit * 60]<br><br>        headers = {<br>            &quot;Accept&quot;: &quot;application/geo+json;charset=UTF-8&quot;,<br>            &quot;Content-Type&quot;: &quot;application/json; charset=utf-8&quot;,<br>        }<br><br>        body = {<br>            &quot;locations&quot;: [[lon, lat]],  # ORS = [Longitude, Latitude]<br>            &quot;range&quot;: time_seconds,<br>            &quot;range_type&quot;: &quot;time&quot;,<br>        }<br><br>        try:<br>            response = requests.post(self.base_url, json=body, headers=headers)<br><br>            if response.status_code != 200:<br>                print(f&quot;Full Error Response: {response.text}&quot;)<br><br>            response.raise_for_status()<br>            return response.json()<br>        except Exception as e:<br>            raise Exception(f&quot;Local ORS request failed: {e}&quot;)</pre><p><strong>The “Cookie Cutter”, keeping only the points that are inside the travel blob.</strong></p><p>This is where the DuckDB Spatial magic happens. It uses a SQL query to perform a spatial join.</p><pre>--- data_processor.py<br><br>SELECT name, ST_AsText(ST_GeomFromWKB(geometry)) as wkt_geom<br>FROM raw_pois<br>WHERE ST_Intersects(<br>    ST_GeomFromWKB(geometry),<br>    ST_GeomFromGeoJSON(?)<br>)</pre><ul><li><strong>ST_GeomFromWKB(geometry):</strong> Converts the raw binary data into a geometric object.</li><li><strong>ST_GeomFromGeoJSON(?):</strong> Converts the “Travel Blob” (Isochrone) into a geometric object.</li><li><strong>ST_Intersects(…): </strong>This is the logic gate. It returns TRUE only if the Point is inside the Polygon.</li><li><strong>ST_AsText(…): </strong>Converts the geometry back into readable text.</li></ul><h3>Why this is “Article Worthy”</h3><p>Most beginner mapping apps just show markers on a map. This project is unique because it is a <strong>self-contained microservice stack</strong>. By hosting your own routing engine (ORS) and using a vectorized database (DuckDB), you have a system that:</p><ul><li><strong>Works Offline/Local:</strong> Once data is downloaded, no external APIs are needed.</li><li><strong>Scales:</strong> It can handle thousands of points across entire regions without crashing.</li><li><strong>Answers “Real” Questions:</strong> It doesn’t tell you what is “near”; it tells you what is <strong>accessible</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d881e07694c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Callable in Python Decorators]]></title>
            <link>https://kaushikshamantha.medium.com/understanding-callable-in-python-decorators-b0cef700a8cf?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0cef700a8cf</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 18:35:07 GMT</pubDate>
            <atom:updated>2025-12-16T18:35:22.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwbtcMuHQZFre3ov0t1F7g.jpeg" /></figure><p>Python decorators can look <strong>magical</strong> at first. Add Callable into the mix and it can feel even more confusing.</p><h3><strong>What does callable mean?</strong></h3><p>In Python, something is callable if you can call it using parentheses.</p><pre>something()</pre><p>If that works, then something is callable.</p><p>Common callable objects are,</p><ul><li>Functions = add()</li><li>Methods = obj.save()</li><li>Classes = User()</li><li>Object with __call__ = obj()</li></ul><p>Callable = anything you can execute like a function.</p><h3>What is a decorator?</h3><p>A decorator is a function that,</p><ul><li>Takes another function.</li><li>Adds extra behavior.</li><li>Returns a new function.</li></ul><p>Without changing the original function’s code.</p><h3>Practical example from everyday life</h3><p>Imagine a coffee machine,</p><ul><li>Coffee = original function</li><li>Milk / Sugar / Foam = extra behavior</li><li>Decorator = adds extras without changing the coffee itself</li></ul><pre>@decorator<br>def my_function():<br>  pass</pre><p>It is just a shortcut for,</p><pre>my_function = decorator(my_function)</pre><h3>Why Callable is used in decorators</h3><p>When writing decorators, we usually accept any function.</p><p>Instead of saying, <strong>“This parameter is a function”.</strong></p><p>We say, <strong>“This parameter is callable.”</strong></p><p>That is more flexible and more correct.</p><pre>from collections.abc import Callable<br><br>def decorator(func: Callable):<br>  pass</pre><p>This means,</p><ul><li><strong>func</strong> can be any callable object, not just a normal function.</li></ul><p>This is especially useful for,</p><ul><li>decorators.</li><li>callbacks.</li><li>hooks.</li><li>middleware.</li></ul><h4>Here is my example,</h4><pre>import random<br>import time<br>from collections.abc import Callable<br><br>def retry(retry: int=3, delay: float=1.0):<br>    def decorator(func: Callable):<br>        def wrapper(*args, **kwargs):<br>            for attempt in range(1, retry+1):<br>                try:<br>                    return func()<br>                except Exception as ex:<br>                    print(f&quot;Attempt: {attempt}, Exception: {ex}&quot;)<br>                    time.sleep(delay)<br>        return wrapper<br>    return decorator<br><br><br>@retry(retry=3, delay=2.0)<br>def fetch_data() -&gt; None:<br>    if random.random() &lt; 0.5:<br>        raise RuntimeError(&quot;temporary error&quot;)<br>    print(&quot;fetch data successfully&quot;)<br><br><br>fetch_data()</pre><p>Lets break it down,</p><h4><strong>retry() = decorator factory</strong></h4><pre>def retry(retry: int = 3, delay: float = 1.0):</pre><p>This is not the decorator yet.</p><p>It’s a decorator factory, a function that creates decorators.</p><p>Why? Because you want configuration,</p><ul><li>Number of retries.</li><li>Delay between retries.</li></ul><h4><strong>decorator (func: Callable)</strong></h4><pre>def decorator(func: Callable):</pre><p>Here,</p><ul><li>func is the function being decorated (fetch_data).</li><li>Callable tells readers and type checkers, <strong>“func must be something we can call”</strong>.</li></ul><h4><strong>wrapper(*args, **kwargs)</strong></h4><pre>def wrapper(*args, **kwargs):</pre><p>The wrapper,</p><ul><li>Replaces the original function.</li><li>Runs before and after it.</li><li>Controls retry behavior.</li><li>*args and **kwargs allow it to wrap any function signature.</li></ul><h4><strong>Retry logic</strong></h4><pre>for attempt in range(1, retry + 1):<br>  try:<br>    return func()</pre><ul><li>Call the function.</li><li>If it succeeds, then return immediately.</li><li>If it fails, then retry.</li></ul><pre>except Exception as ex:<br>  print(f&quot;Attempt: {attempt}, Exception: {ex}&quot;)<br>  time.sleep(delay)</pre><p>This is where the retry behavior lives.</p><h3>Why Callable matters</h3><p>Callable helps you,</p><ul><li>Write flexible decorators.</li><li>Improve readability.</li><li>Enable static type checking (mypy, Pyright).</li><li>Document intent clearly.</li></ul><blockquote>Callable tells Python and humans, “This thing is meant to be called.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0cef700a8cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before You Spark! Lessons in Pandas Optimization]]></title>
            <link>https://kaushikshamantha.medium.com/before-you-spark-lessons-in-pandas-optimization-78e2ea188687?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/78e2ea188687</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 21:17:17 GMT</pubDate>
            <atom:updated>2025-10-05T21:17:17.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CvLrXL2fCYPPLhRwbf31g.png" /></figure><p>This article explores how to optimize large scale data workflows using Pandas before migrating to Spark. It covers memory saving techniques, efficient computation strategies, and best practices for handling complex storage formats, helping you push Pandas to its limits before adopting a new toolset.</p><h4>Load only what you need</h4><p>When working with large datasets, loading everything into memory is a recipe for slow performance and high resource usage.</p><pre>import pandas as pd<br><br>file_name = &#39;data/diabetes_dataset.csv&#39; <br>df = pd.read_csv(file_name)<br><br>mb = 1_000_000<br>print(&quot;Full Data Memory (MB):&quot;, df.memory_usage(deep=True).sum() / mb)<br><br>print(&quot;Median BMI by Gender:&quot;)<br>print(df.groupby(&#39;gender&#39;)[&#39;bmi&#39;].median())<br><br>columns = [&#39;gender&#39;, &#39;bmi&#39;]<br>df_subset = pd.read_csv(file_name, usecols=columns)<br><br>print(&quot;Subset Data Memory (MB):&quot;, df_subset.memory_usage(deep=True).sum() / mb)<br><br>print(&quot;Median BMI by Gender (subset):&quot;)<br>print(df_subset.groupby(&#39;gender&#39;)[&#39;bmi&#39;].median())</pre><p>Output,</p><pre>Full Data Memory (MB): 58.521915<br>Median BMI by Gender:<br>gender<br>Female    25.6<br>Male      25.6<br>Other     25.4<br>Name: bmi, dtype: float64<br>Subset Data Memory (MB): 6.202577<br>Median BMI by Gender (subset):<br>gender<br>Female    25.6<br>Male      25.6<br>Other     25.4<br>Name: bmi, dtype: float64</pre><h4>Optimize Column Types</h4><p>Large datasets often use default types like float64 or object, which consume more memory than necessary. By analyzing value ranges and converting to efficient types like float32, int8, or category, you can significantly reduce memory usage without losing precision.</p><pre>import pandas as pd<br>import numpy as np<br><br>file_name = &#39;data/diabetes_dataset.csv&#39;<br>df = pd.read_csv(file_name)<br><br>print(&quot;BMI Range:&quot;)<br>print(df[&#39;bmi&#39;].describe())<br><br>mb = 1_000_000<br>print(&quot;BMI Memory (float64):&quot;, df[&#39;bmi&#39;].memory_usage(deep=True) / mb, &quot;MB&quot;)<br><br>bmi_optimized = df[&#39;bmi&#39;].astype(np.float32)<br>print(&quot;BMI Memory (float32):&quot;, bmi_optimized.memory_usage(deep=True) / mb, &quot;MB&quot;)<br><br>print(&quot;Gender Memory:&quot;, df[&#39;gender&#39;].memory_usage(deep=True) / mb, &quot;MB&quot;)<br><br>gender_optimized = df[&#39;gender&#39;].astype(&#39;category&#39;)<br>print(&quot;Gender Memory (Categorical):&quot;, gender_optimized.memory_usage(deep=True) / mb, &quot;MB&quot;)</pre><p>Output,</p><pre>BMI Range:<br>count    100000.000000<br>mean         25.612653<br>std           3.586705<br>min          15.000000<br>25%          23.200000<br>50%          25.600000<br>75%          28.000000<br>max          39.200000<br>Name: bmi, dtype: float64<br>BMI Memory (float64): 0.800132 MB<br>BMI Memory (float32): 0.400132 MB<br>Gender Memory: 5.402577 MB<br>Gender Memory (Categorical): 0.100402 MB</pre><h4>Use PyArrow Backend for Efficient Strings</h4><p>Pandas now supports the PyArrow backend, which stores strings more compactly and enables faster operations.</p><pre>import pandas as pd<br><br>file_name = &#39;data/diabetes_dataset.csv&#39;<br>df = pd.read_csv(file_name)<br><br>mb = 1_000_000<br>print(&quot;Memory (default backend):&quot;, df.memory_usage(deep=True).sum() / mb, &quot;MB&quot;)<br><br>df_arrow = pd.read_csv(file_name, dtype_backend=&#39;pyarrow&#39;)<br>print(&quot;Memory (PyArrow backend):&quot;, df_arrow.memory_usage(deep=True).sum() / mb, &quot;MB&quot;)<br><br>income_map = {<br>    &#39;Lower-Middle&#39;: &#39;Low&#39;,<br>    &#39;Middle&#39;: &#39;Medium&#39;,<br>    &#39;Upper-Middle&#39;: &#39;High&#39;,<br>    &#39;High&#39;: &#39;High&#39;<br>}<br>df_arrow[&#39;income_group&#39;] = df_arrow[&#39;income_level&#39;].map(income_map)<br>print(&quot;Memory (mapped income_group):&quot;, df_arrow[&#39;income_group&#39;].memory_usage(deep=True) / mb, &quot;MB&quot;)<br><br>df_arrow[&#39;income_group&#39;] = df_arrow[&#39;income_group&#39;].astype(&#39;string[pyarrow]&#39;)<br>print(&quot;Memory (PyArrow string):&quot;, df_arrow[&#39;income_group&#39;].memory_usage(deep=True) / mb, &quot;MB&quot;)</pre><p>Output,</p><pre>Memory (default backend): 58.521915 MB<br>Memory (PyArrow backend): 27.021915 MB<br>Memory (mapped income_group): 5.033856 MB<br>Memory (PyArrow string): 1.198466 MB</pre><h4>Numba Acceleration</h4><p>This chapter shows how to do that efficiently first with Pandas .apply(), then with blazing fast Numba vectorization.</p><pre>import pandas as pd<br>import numba<br>import time<br><br>file_name = &#39;data/diabetes_dataset.csv&#39;<br>df = pd.read_csv(file_name)<br><br>bmi_median = df[&#39;bmi&#39;].median()<br>print(&quot;Median BMI:&quot;, bmi_median)<br><br>def norm_bmi(value):<br>    if value &lt;= 0 or value &gt; 60:<br>        return bmi_median<br>    return value<br><br>start = time.time()<br>df[&#39;bmi&#39;].apply(norm_bmi)<br>end = time.time()<br><br>print(&quot;Elapsed time:&quot;, end - start, &quot;seconds&quot;)<br><br>@numba.vectorize<br>def norm_bmi_numba(value):<br>    if value &lt;= 0 or value &gt; 60:<br>        return bmi_median<br>    return value<br><br>start = time.time()<br>values = df[&#39;bmi&#39;].to_numpy()<br>end = time.time()<br><br>print(&quot;Elapsed time:&quot;, end - start, &quot;seconds&quot;)</pre><p>Output,</p><pre>Median BMI: 25.6<br>Elapsed time: 0.013846874237060547 seconds<br>Elapsed time: 3.0994415283203125e-05 seconds</pre><h4>Polars vs Pandas for Speed and Memory</h4><p>As datasets grow, performance bottlenecks in Pandas become more noticeable. Polars, a fast DataFrame library built in Rust, offers blazing speed and lower memory usage.</p><pre>import polars as pl<br>import pandas as pd<br><br>file_name = &#39;data/diabetes_dataset.csv&#39;<br><br>df_pl = pl.read_csv(file_name)<br>print(&quot;Polars Estimated Size (MB):&quot;, df_pl.estimated_size(unit=&#39;mb&#39;))<br><br>df_pd = pd.read_csv(file_name)<br>print(&quot;Pandas Memory Usage (MB):&quot;, df_pd.memory_usage(deep=True).sum() / 1_000_000)<br><br>import time<br><br>start = time.time()<br>df_pl.group_by(&#39;gender&#39;).agg(<br>    pl.sum(&#39;cholesterol_total&#39;)<br>).sort(&#39;gender&#39;)<br>end = time.time()<br>print(&quot;Polars Aggregation Time:&quot;, end - start, &quot;seconds&quot;)<br><br>start = time.time()<br>df_pd.groupby(&#39;gender&#39;)[&#39;cholesterol_total&#39;].sum().sort_values()<br>end = time.time()<br>print(&quot;Pandas Aggregation Time:&quot;, end - start, &quot;seconds&quot;)</pre><p>Before reaching for distributed systems like Spark, it’s worth asking how far you can push Pandas. With smart loading strategies, efficient data types, PyArrow-backed strings, and performance boosts from tools like Numba and Polars, you can handle surprisingly large datasets right on your laptop. These techniques not only save memory and time they build a deeper understanding of your data and prepare you for scaling with confidence. Optimize first, migrate second.</p><ul><li><a href="https://www.kaggle.com/datasets/mohankrishnathalla/diabetes-health-indicators-dataset">https://www.kaggle.com/datasets/mohankrishnathalla/diabetes-health-indicators-dataset</a></li><li><a href="https://www.sourceforsports.ca/blogs/bikes-bicycles/bike-tune-up?srsltid=AfmBOorQUUfbnp96sicb96YhoJ8PWnNO80AZ5pcxb0ztTNaf11Kj7yK-">https://www.sourceforsports.ca/blogs/bikes-bicycles/bike-tune-up?srsltid=AfmBOorQUUfbnp96sicb96YhoJ8PWnNO80AZ5pcxb0ztTNaf11Kj7yK-</a> (image)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e2ea188687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD: The Secret Ingredient to My Happiest Coding Days]]></title>
            <link>https://kaushikshamantha.medium.com/tdd-the-secret-ingredient-to-my-happiest-coding-days-fe804078d598?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe804078d598</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 22:09:48 GMT</pubDate>
            <atom:updated>2025-08-13T22:09:48.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2GHt9kHX2WshbX_rk2_-w.png" /></figure><p>When releasing new features, bug fixes, or hotfixes, most developers (my past self included 😁) rarely think about writing test cases first. The focus is almost always on the shiny new functionality or the urgent fix.</p><p>It feels faster, until it isn’t.</p><p>Because here’s the hard truth. Sometimes a tiny change, something as innocent as renaming a variable or tweaking a condition, can cause the entire application to crash in unexpected ways. Suddenly, the “quick” release becomes a multi-hour (or multi-day) debugging marathon.</p><p>I’ve been there. The Slack notifications piling up, logs scrolling endlessly on my screen, and the sinking feeling of “Where do I even start?” That’s when I realized something had to change, and that “something” was how I approached writing code in the first place.</p><p>That’s when Test-Driven Development (TDD) entered my life.</p><p>Let me walk you through a minimal Rails app I built and experimented with using TDD. It’s a tiny pet-tracking API app.</p><p><a href="https://github.com/kaushik0911/fantastic-fiesta">https://github.com/kaushik0911/fantastic-fiesta</a></p><p>What makes it special? It was built 100% with a <strong>test-first mindset</strong>. Every behavior is codified with Rails tests, RSpec, and API documentation is generated via Rswag, meaning the controller tests double as Swagger API specs, no drift between code and docs.</p><h4>Start with the Models + Model Tests.</h4><p>The model is your domain’s foundation, and it holds the business rules, validations, and associations.</p><ul><li>Write a failing Rails test/RSpec model test for a single rule (e.g. “a cat can have a lost tracker, but a dog cannot”).</li><li>Write the minimal model code to make it pass.</li><li>Refactor if needed.</li></ul><pre># test/models/pet_test.rb<br>class PetTest &lt; ActiveSupport::TestCase<br>  def setup<br>    @pet = pets(:my_pet)<br>  end<br>  <br>  test &quot;lost_tracker can only be true for cats&quot; do<br>    @pet.pet_type = :dog<br>    @pet.lost_tracker = true<br>    assert_not @pet.valid?<br>    assert_includes @pet.errors[:lost_tracker], I18n.t(&quot;activerecord.errors.models.pet.attributes.lost_tracker.can_only_be_true_for_cats&quot;)<br>  end<br>end</pre><h4>Move to API Controllers + Controller Tests.</h4><p>Once the model behavior is correct, you expose it via your endpoints.</p><ul><li>Write a failing controller/request spec for the endpoint (e.g. POST /pets returns 422 for invalid dogs).</li><li>Implement the controller action to satisfy the test.</li><li>Refactor, keeping tests green.</li></ul><pre># spec/requests/api/v1/pets_spec.rb<br>describe &quot;GET /api/v1/pets&quot; do<br>  path &quot;/api/v1/pets&quot; do<br>    get &quot;Retrieves a list of all pets&quot; do<br>      tags &quot;Pets&quot;<br>      consumes &#39;application/json&#39;<br>      produces &#39;application/json&#39;<br><br>      response &quot;200&quot;, &quot;successful&quot; do<br>        schema type: :array, items: { &#39;$ref&#39; =&gt; &#39;#/components/schemas/PET&#39; }<br>        run_test!<br>      end<br>    end<br>  end<br><br>  it &quot;gets a list of pets&quot; do<br>    get api_v1_pets_path, headers: auth_headers, as: :json<br><br>    expect(response).to have_http_status(:success)<br><br>    body = JSON.parse(response.body)<br><br>    expect(body).to be_a_kind_of(Array)<br>  end<br>end<br></pre><h4>Iterate Feature by Feature</h4><ul><li>Add next business rule or endpoint → write failing test → implement → refactor.</li><li>Keep tests small, focused, and running often.</li></ul><h4>Generate API Documentation from Tests</h4><ul><li>Using Rswag, your request specs can automatically produce Swagger docs.</li><li>No drift between docs and actual API behavior.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abrJfJm9L0yDcnbN1Yme9w.png" /></figure><p>You can clone it, run `rails test` &amp; `bundle exec rspec`, play with it, watch tests fail, make them pass, and even browse the docs locally with a simple `rake rswag:specs:swaggerize`. That tight feedback loop? Pure TDD joy.</p><p>That, to me, is why TDD isn’t just a process, it’s a path to a cleaner, more confident development experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe804078d598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dunders in Python — Part 2.]]></title>
            <link>https://kaushikshamantha.medium.com/dunders-in-python-part-2-64bb2e4b4055?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/64bb2e4b4055</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 21:08:28 GMT</pubDate>
            <atom:updated>2025-02-03T21:08:28.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1cIr1Jsfvr-OCcddRDnRQ.jpeg" /></figure><h3>Dunders in Python — Part 2.</h3><p>“Dunders” is an unofficial term referring to double underscores that appear at the beginning and end of a variable name known as “magic methods”. They are used to enable the customization of basic behavior in classes.</p><p>This is part 2 of this blog. If you haven&#39;t read chapter 1 click <a href="https://medium.com/@kaushikshamantha/dunders-in-python-part-1-568ed50895d0">this</a> link to visit the page. This article only focuses on “__doc__”.</p><h4>“__doc__“ : Stores a class or function’s documentation string, which is used to describe its purpose.</h4><p>The __doc__ attribute is a special built-in property in Python that stores the docstring (documentation string) of a module, class, function, or method.</p><p>Docstrings are declared using triple quotes (&quot;&quot;&quot;...&quot;&quot;&quot; or &#39;&#39;&#39;...&#39;&#39;&#39;) immediately after defining a module, class, function, or method.</p><p><strong>Use Cases for </strong><strong>__doc__</strong></p><ul><li>Docstrings at the top of a file describe the module’s purpose.</li></ul><pre>&quot;&quot;&quot;A module for basic mathematical operations.<br><br>This module provides functions for addition, subtraction, etc.<br>&quot;&quot;&quot;<br><br>def subtract(a, b):<br>    &quot;&quot;&quot;Subtract `b` from `a`.&quot;&quot;&quot;<br>    return a - b</pre><pre>import math_operations<br>print(math_operations.__doc__)  # Outputs the module-level docstring</pre><p>This will print only “A module for basic mathematical operations. This module provides functions for addition, subtraction, etc.”</p><ul><li>Docstrings in classes describe the class’s role, attributes, and methods.</li></ul><pre>class Rectangle:<br>    &quot;&quot;&quot;Represents a geometric rectangle.<br><br>    Attributes:<br>        length (float): Length of the rectangle.<br>        width (float): Width of the rectangle.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, length, width):<br>        self.length = length<br>        self.width = width<br><br>    def area(self):<br>        &quot;&quot;&quot;Calculate the area of the rectangle.&quot;&quot;&quot;<br>        return self.length * self.width</pre><pre>print(Rectangle.__doc__) # Outputs the class-level docstring<br>print(Rectangle.area.__doc__) # Outputs the method-level docstring</pre><p>First print the, “Represents a geometric rectangle. Attributes: length (float): Length of the rectangle. width (float): Width of the rectangle.” then method level docstring “Calculate the area of the rectangle.”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySVHZtltDYSzvMjh8wPEVw.png" /></figure><h4>Real-World Use Case</h4><p>In large projects, it __doc__ helps generate comprehensive documentation. For example, the numpy module uses docstrings extensively. This outputs detailed documentation about parameters, returns, and examples.</p><pre>import numpy as np<br><br># Access the docstring for numpy&#39;s `array` function<br>print(np.array.__doc__)</pre><h4>Advantages of “__doc__&quot;</h4><ol><li>Docstrings make code readable and maintainable without external documentation.</li><li>Tools like <strong>Sphinx</strong>, <strong>pydoc</strong>, and <strong>IDEs</strong> (e.g., PyCharm, VSCode) are used __doc__ to generate API documentation or provide autocomplete hints.</li><li>Docstrings can follow conventions like <strong>Google Style</strong>, <strong>NumPy Style</strong>, or <strong>reStructuredText (reST)</strong> for consistency. Example (Google Style).</li><li>Docstrings are available at runtime, enabling dynamic introspection.</li></ol><h4>Best Practices</h4><ul><li>Prioritize docstrings for modules, classes, and functions/methods exposed to users.</li><li>Use Linters, Tools like <strong>Flake8</strong> with <strong>flake8-docstrings</strong> enforce docstring conventions.</li><li>Avoid Redundancy, Focus on why and how rather than repeating the function name.</li><li>Use triple-double quotes. Keep one-liners concise. For multi-line docstrings, include a summary line, followed by a blank line, then details.</li><li>Always document public-facing code (APIs, libraries, shared modules).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64bb2e4b4055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kimball vs Inmon]]></title>
            <link>https://kaushikshamantha.medium.com/kimball-vs-inmon-0725c1952e1c?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0725c1952e1c</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 13:55:29 GMT</pubDate>
            <atom:updated>2025-01-27T13:55:29.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lew9CnuV4cCAO5s3JZo-FQ.jpeg" /></figure><p>In the early 1980s, businesses were more focused on transactional systems, OLTP (Online Transaction Processing). It optimized transaction speed and efficiency for daily operations like sales, inventory, etc.</p><p>Over time businesses need to analyze historical data to make decisions for the future. Decision Support Systems (DDS) were introduced. Still, such systems were not efficient because it dependent on OLTP-based operational databases which were not optimized for heavy querying large amounts of data.</p><p>At that time there were 3 main challenges to be solved.</p><ol><li>Handling large volumes of data.</li><li>Integrating data scattered across different places.</li><li>Querying integrated datasets for analysis.</li></ol><h4>Bill Inmon’s top-down approach</h4><p>Inmon introduced the concept of the data warehouse in the 1990s and was recognized as the Father of Data warehouse. In his approach, businesses store their normalized data in a central repository, for analysis. Also known as the Top-Down approach.</p><p>This approach ensures data consistency, and integrity before starting the analytical process. But this could get more complex when increase of the data and sources. Therefore it may take some time for the implementation.</p><p>But business needs faster data analysis to make discussions. Meantime Ralph Kimball introduced the dimensional approach.</p><h4>Kimball’s Bottom-Up Approach</h4><p>The main reason for introducing this method is to reduce the complexity of the implementation. It is more focused on faster business discussions. In this approach, the warehouse is denormalized.<br>A star schema, which organizes data in a way that is easier to understand and query. Simplified data access for end-users. Also known as the Botton-Up approach.</p><h4>Top-Down vs Bottom-Up</h4><p>Both are widely recognized methodologies when designing data warehouses. But there is a key difference when it comes to their approach and structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*MqqheijSoUcYQgS79sv2mg.png" /></figure><p><strong>Bill Inmon’s top-down approach</strong></p><ul><li>Data is Normalized (3rd normal form) in the central data repository.</li><li>No data redundancy.</li><li>Implementation cost is high because the central Data warehouse must be built first. Start from Data warehouse to Data marts.</li><li>However, its data is consistent and suitable for long-term growth.</li><li>Bit more complex to query because heavy tables join might needed.</li><li>OLAP cubes are applied to the Datamart after data load from the central Data warehouse.</li></ul><p><strong>Kimball’s Bottom-Up Approach</strong></p><ul><li>Data is Denormalized (star schema). Collection of Individual data marts.</li><li>Data redundancy is there.</li><li>Implementation is faster. Because it focused on data marts.</li><li>Individual data marts can be developed and deployed quickly.</li><li>User-friendly for end-users to perform analysis and generate reports.</li><li>OLAP cubes can directly integrate into Datamart because it is already Denormalized.</li></ul><h4>What is more suitable?</h4><p>The choice depends on several things, such as the business goals, data complexity, organization structure, and long-term strategy.</p><ul><li><strong>Business Requirements</strong></li></ul><p>If you need quick, department-specific solutions, Kimball is better. If you need a centralized, enterprise-wide solution, Inmon is better.</p><ul><li><strong>Time and Resources</strong></li></ul><p>Kimball is faster and less resource-intensive initially. Inmon requires more time and resources but offers long-term benefits.</p><ul><li><strong>Data Complexity</strong></li></ul><p>Kimball works well for simpler, business-focused use cases. Inmon is better for complex, large-scale data environments.</p><ul><li><strong>End-User Needs</strong></li></ul><p>Kimball is more user-friendly for business analysts and decision-makers. Inmon may require additional layers (e.g., data marts) to make data accessible to end-users.</p><ul><li><strong>Governance and Consistency</strong></li></ul><p>Inmon provides stronger governance and consistency. Kimball requires careful management to avoid inconsistencies.</p><p>Ultimately, the choice depends on your organization’s priorities, resources, and long-term goals. In practice, many organizations use a <strong>hybrid approach</strong>, combining the strengths of both methodologies.</p><h4>Hybrid Approach</h4><p>Many organizations adopt a hybrid approach, combining the strengths of both methodologies.</p><ul><li>Use Inmon’s centralized EDW for enterprise-wide consistency.</li><li>Use Kimball’s dimensional modeling for specific data marts to meet business needs.</li></ul><h4>Example of Hybrid Approach</h4><p>The retail company wants to,</p><ul><li>Build a centralized data warehouse to serve as the single source of truth for all enterprise data.</li><li>Create departmental data marts (e.g., for sales, inventory, and customer analysis) that are easy for business users to query.</li></ul><p><strong>Build the Enterprise Data Warehouse (EDW) — Inmon Style</strong></p><ul><li>Design a <strong>normalized 3NF (Third Normal Form)</strong> data warehouse to serve as the central repository for all enterprise data.</li><li>Tables are designed to minimize redundancy and ensure data integrity.</li></ul><p><strong>Create Data Marts — Kimball Style</strong></p><ul><li>Use <strong>dimensional modeling</strong> (star or snowflake schema) to create data marts for specific business needs.</li><li>Data marts are derived from the centralized EDW.</li></ul><p><strong>Connect the EDW and Data Marts</strong></p><ul><li>The centralized EDW serves as the <strong>single source of truth</strong>.</li><li>Data is extracted from the EDW, transformed into dimensional models, and loaded into the data marts.</li><li>This ensures consistency across all data marts while maintaining business-friendly structures.</li></ul><p><strong>End-User Access</strong></p><ul><li>Business users access the data marts for their specific needs (e.g., the sales team uses the Sales Data Mart, and the inventory team uses the Inventory Data Mart).</li><li>The dimensional models in the data marts make it easy for users to query and analyze data.</li></ul><h4>When to Use the Hybrid Approach</h4><ul><li>Your organization needs a <strong>centralized, governed data warehouse</strong> but also wants <strong>business-friendly data marts</strong>.</li><li>You have the resources to build and maintain an EDW but want to deliver quick value to business users through data marts.</li><li>You want to balance <strong>long-term scalability</strong> with <strong>short-term business needs</strong>.</li></ul><p>This approach is widely used in modern data warehousing because it provides the best of both worlds, <strong>consistency and agility</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0725c1952e1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aggregate functions can act as window functions.]]></title>
            <link>https://kaushikshamantha.medium.com/aggregate-functions-can-act-as-window-functions-c286f2f6013d?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c286f2f6013d</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 06:27:39 GMT</pubDate>
            <atom:updated>2025-01-20T06:27:39.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJUJRruOPWvxFix_94Uhqg.jpeg" /></figure><p>Aggregate functions and window functions are <strong>distinct concepts</strong>, although <strong>aggregate functions can also be used as part of a window function</strong>. The main difference between <strong>aggregate functions</strong> and <strong>window functions</strong> lies in how they process rows and present results.</p><h3>Definition</h3><p>Aggregate functions operate on a set of rows and <strong>return</strong> <strong>a single value</strong> for the entire set or group of rows.</p><p>Window functions operate on a <strong>“window” or subset of rows</strong> and <strong>return</strong> <strong>a value for each row</strong>, based on calculations within the window.</p><blockquote><strong>Aggregate Function</strong> reduces rows by grouping and <strong>Window Function</strong> retains all original rows.</blockquote><h4>Example</h4><p>Consider the following sales table,</p><pre>| Product | Sales |<br>|:-------:|:-----:|<br>| Laptop  | 5000  |<br>| Laptop  | 7000  |<br>| Phone   | 3000  |<br>| Phone   | 4000  |</pre><p>Aggregate Function example,</p><pre>SELECT<br>    Product,<br>    SUM(Sales) AS TotalSales<br>FROM sales<br>GROUP BY Product;</pre><p>The SUM function aggregates rows into a single result for each Product.</p><pre>| Product | TotalSales |<br>|:-------:|:----------:|<br>| Laptop  | 12000      |<br>| Phone   | 7000       |</pre><p>Window Function example,</p><pre>SELECT<br>    Product,<br>    Sales,<br>    SUM(Sales) OVER (PARTITION BY Product) AS TotalSales<br>FROM sales;</pre><p>The SUM function here operates as a window function because of the OVER() clause, retaining all rows and calculating totals within the specified &quot;window&quot; ;PARTITION BY Product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*rVAOUtHGEEOgp9aTCqpgmA.png" /></figure><blockquote>Yes, <strong>aggregate functions can act as window functions. </strong>They are used with the OVER() clause. This enables aggregate functions to calculate values for a specific “window” or subset of rows while retaining all rows in the result set.</blockquote><h3>Behind the Scenes</h3><p>When an aggregate function is used as a <strong>window function</strong> (with the OVER() clause), the database performs several behind-the-scenes steps to compute the result.</p><pre>SELECT <br>    Product, <br>    Sales, <br>    SUM(Sales) OVER (PARTITION BY Product) AS TotalSales<br>FROM sales;</pre><p><strong>Step 1</strong>: Partition the dataset by Product</p><ul><li>Partition 1: Laptop rows</li><li>Partition 2: Phone rows</li></ul><p><strong>Step 2</strong>: For each row, calculate SUM(Sales) for its partition</p><ul><li>Partition 1: 5000 + 7000 = 12000</li><li>Partition 2: 3000 + 4000 = 7000</li></ul><p><strong>Step 3</strong>: Assign the result to each row within its partition</p><p>The calculated value is <strong>stored in a new column</strong> for each row in the result set. This step ensures that the result set retains all original rows and adds the computed value.</p><h4>Comparison to Regular Aggregate Functions</h4><p>For regular aggregate functions, there are <strong>no partitions or frames</strong>. The function works on the entire dataset or grouped subsets (defined by GROUP BY).</p><p>The number of output rows is <strong>reduced</strong> because results are returned per group.</p><p>For window functions, partitions and frames allow row-specific calculations. The number of output rows is <strong>preserved</strong>, with additional calculated columns.</p><h3>What is speed?</h3><p>The <strong>speed</strong> of a query depends on multiple factors, whether it involves <strong>window functions</strong> or <strong>aggregate functions</strong>, as both have different purposes and performance characteristics.</p><ul><li>Typically <strong>window functions are slower</strong> than aggregate functions because they must compute values for <strong>each row</strong> in the dataset.</li><li>Aggregate functions summarize data and reduce rows, meaning fewer computations.</li><li>Window functions maintain all rows in the result, increasing computation and output size compared to aggregates.</li></ul><p>Aggregate functions (e.g., SUM, AVG, COUNT, MAX, MIN) are designed to <strong>summarize data</strong> by collapsing rows into a smaller result set.</p><p>Window functions (e.g., SUM() OVER(), ROW_NUMBER() OVER()) <strong>preserve all rows</strong> in the result set while calculating a defined &quot;window&quot; of rows.</p><p>Aggregation functions are usually more efficient if speed is a concern, <strong>but window functions are indispensable when detailed row-level calculations are required</strong>. Use the one that fits your specific use case!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c286f2f6013d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy way to accelerate your pandas code]]></title>
            <link>https://kaushikshamantha.medium.com/lazy-way-to-accelerate-your-pandas-code-4905772e63be?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4905772e63be</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 15:05:58 GMT</pubDate>
            <atom:updated>2024-09-05T20:33:33.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*DW66wdZk_Mk-uH1k" /><figcaption><a href="https://zyliss.co.uk/cdn/shop/products/vyt8szwobzmdh6wipjzp_600x.jpg?v=1686048608">https://zyliss.co.uk/cdn/shop/products/vyt8szwobzmdh6wipjzp_600x.jpg?v=1686048608</a> (image)</figcaption></figure><p>Today everyone is using AI tools to accelerate their development lifecycle. Some developers are now too lazy to develop or optimize their code without using AI tools. What is <a href="https://fireducks-dev.github.io/">FireDucks</a>.</p><blockquote>Do you have a pandas-based program that is slow? FireDucks can speed-up your programs without any manual code changes. You can accelerate your data analysis without worrying about slow performance due to single-threaded execution in pandas. — FireDucks</blockquote><p><a href="https://fireducks-dev.github.io/">FireDucks</a> is a “<em>Compiler Accelerated DataFrame Library for Python with fully-compatible pandas API</em>”. But you can achieve this using with Line of Code. Great isn&#39;t it?</p><p>FireDucks is developed by members of <a href="https://www.nec.com/en/global/rd/index.html">NEC</a>’s R&amp;D department. So made in Japan. They love acceleration. Of course, <strong>FireDucks is still under research and development</strong>.</p><p><strong>It is currently available for Linux on the x86_64 architecture</strong>. Windows and MacOS versions are under development. But its working on <strong>WSL </strong>(Windows Subsystem for Linux). Supporting python version, <strong>3.8 ≤ Python ≤ 3.12.</strong></p><h4>Features</h4><ul><li>Multi-threaded</li><li>Fully compatible with pandas API — No additional learning is required to start with FireDucks / Zero learning cost</li><li>As is execution — Replace the import statement for pandas with the import statement for FireDucks</li><li>Lazy execution</li></ul><blockquote>We believe that acceleration has various values. In the age of cloud computing, the value is also increasing in the form of lower cloud costs and reduced CO2 emissions. Above all, it is a great feeling when a program you have written runs fast. — FireDucks</blockquote><h4>Usage</h4><p>Installing FireDuck,</p><pre>pip install fireducks</pre><p>Two ways to use FireDuck.</p><ol><li>Import Hook</li><li>Explicit Hook</li></ol><h4>Import Hook</h4><p>The import hook can be activated by Python interpreter’s -m option as follows,</p><pre>python3 -m fireducks.pandas my_script.py</pre><p>and Jupyter notebook.</p><pre>%load_ext fireducks.pandas<br>import pandas as pd</pre><h4>Explicit Import</h4><p>Replace the import statement as follows.</p><pre># import pandas as pd<br>import fireducks.pandas as pd</pre><h4>Example Code</h4><p>Following code is tested on Google Colabs environment.</p><pre>%load_ext fireducks.pandas<br>import time<br>import pandas as pd</pre><p>lets check whether its import correctly.</p><pre>print(f&quot;evaluation with {pd.__name__}&quot;)<br><br># output: evaluation with fireducks.pandas</pre><p>Download dataset.</p><pre>!wget https://data.rapids.ai/datasets/nyc_parking/nyc_parking_violations_2022.parquet</pre><p>Import dataset.</p><pre>df = pd.read_parquet(<br>    &quot;nyc_parking_violations_2022.parquet&quot;,<br>    columns=[&quot;Registration State&quot;, &quot;Violation Description&quot;,<br>             &quot;Vehicle Body Type&quot;, &quot;Issue Date&quot;, &quot;Summons Number&quot;]<br>)</pre><p>Query dataset and check for running time.</p><pre>t0 = time.time()<br>query = (df[[&quot;Registration State&quot;, &quot;Violation Description&quot;]]<br> .value_counts()<br> .groupby(&quot;Registration State&quot;)<br> .head(1)<br> .sort_index()<br> .reset_index()<br>)<br>time_diff = time.time() - t0<br>time_diff<br><br># output: 0.6491267681121826</pre><p>If you run the same code using pandas, it will query around 3 seconds<em>(I got 3.263641834259033).</em></p><h4>Benchmark Report</h4><p>If you want to research this more and more please refer <a href="https://fireducks-dev.github.io/db-benchmark/">https://fireducks-dev.github.io/db-benchmark/</a> report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j55YGTruq8xccguEbkpkew.png" /><figcaption><a href="https://fireducks-dev.github.io/db-benchmark/join/J1_1e9_NA_0_0_basic.png">https://fireducks-dev.github.io/db-benchmark/join/J1_1e9_NA_0_0_basic.png</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DS6LR86w44NLQ84RYIFdg.png" /><figcaption><a href="https://fireducks-dev.github.io/db-benchmark/join/J1_1e9_NA_0_0_basic.png">https://fireducks-dev.github.io/db-benchmark/join/J1_1e9_NA_0_0_basic.png</a></figcaption></figure><h4>Referance</h4><ul><li><a href="https://fireducks-dev.github.io/">https://fireducks-dev.github.io/</a></li><li><a href="https://fireducks-dev.github.io/db-benchmark/">https://fireducks-dev.github.io/db-benchmark/</a></li><li><a href="https://youtu.be/LJ-G0x1R1Zk?si=2eOz1W6QtaR_4bj4">https://youtu.be/LJ-G0x1R1Zk?si=2eOz1W6QtaR_4bj4</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4905772e63be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good graphs]]></title>
            <link>https://kaushikshamantha.medium.com/good-graphs-7308c7b6eacb?source=rss-702167d2cc2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7308c7b6eacb</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Kaushik Shamantha]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 15:04:53 GMT</pubDate>
            <atom:updated>2024-08-21T15:04:53.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u8h_2h5sC7w6u57m.jpg" /><figcaption>Image: SpaceX</figcaption></figure><blockquote>“When you tell a story with data, you need to find the right balance of storytelling and data analysis to make the message resonate with your audience.” — Cole Nussbaumer Knaflic</blockquote><h4>Visualization analytics</h4><p>Visualization analytics aims to help people make better decisions by transforming unprocessed data into visual presentations and using analytic tools to enable users to examine and understand information more efficiently.</p><p>What can we see on a line chart?</p><ul><li>Trend</li><li>Ups and downs</li><li>Recurrent patterns</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*Ri1MfxP_FTxSnyQO.jpg" /><figcaption><a href="https://people.duke.edu/~rnau/411outbd.htm">https://people.duke.edu/~rnau/411outbd.htm</a></figcaption></figure><h4>Understanding dimensions and measures</h4><p>Dimensions<strong> </strong>— categorical variables, which data can be segmented, filtered, or grouped. (eg. id, name, city, month)</p><p>Measures — continuous variables that represent numerical data. They are aggregated, calculated, or analyzed. (eg. number of people, total sales)</p><p>In visualizations, bar charts, or pivot tables, dimensions typically define the axes or categories, while measures define the values plotted against those dimensions.</p><h4>What is a good graph?</h4><blockquote><em>A graph with a simple design strives for a clean, uncluttered look. Simplicity in design does not mean simplicity in data however; well-designed graphs can represent rich data. — </em><a href="https://scc.ms.unimelb.edu.au/resources/data-visualisation-and-exploration/data-visualisation"><em>Gordon I &amp; Finch S. (2015)</em></a></blockquote><p>Let&#39;s go through some examples to understand the differences.</p><p>Try to answer the following questions by looking at the pivot table for a store&#39;s particular sales.</p><ol><li>Subcategories with the highest sales?</li><li>Subcategories with the least profit?</li><li>Subcategories having more losses in than two regions?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*45ofdOSGLALfjGmVQpDMWw.jpeg" /><figcaption><a href="https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t">https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t</a> (source)</figcaption></figure><p>Can you spot the answer in seconds? I assume it is a bit hard right?<br>Now look at the following chart and try to answer previous questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6skygPsR6kkChniXh4xdOw.png" /><figcaption><a href="https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t">https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t</a> (source)</figcaption></figure><p>Key points you should take from the above chart,</p><ul><li>Sort the data</li><li>Labels/orientation</li><li>If there is a data column never put it in the vertical line</li></ul><p>Now look at the next chart. Seems fine right? Analysts can see the trend, highest and lowest sales months, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgZUxRqeUZIbQpURYxBxeQ.png" /><figcaption><a href="https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t">https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t</a> (source)</figcaption></figure><p>But looking at the next chart using the same data users can easily compare data by year. You can answer many questions quickly and easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdJYIQCEw-99md4MjtHpIA.png" /><figcaption><a href="https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t">https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t</a> (source)</figcaption></figure><h4>Dashboard</h4><p>What is the first thing come to your mind when you heard the word dashboard. Vehicle dashboard isn&#39;t it? Dashnoard is a summary of data as collection of charts.</p><blockquote>A dashboard is a way of displaying various types of visual data in one place. Usually, a dashboard is intended to convey different, but related information in an easy-to-digest form. And oftentimes, this includes things like key performance indicators (KPI)s or other important business metrics that stakeholders need to see and understand at a glance. — <a href="https://www.tableau.com/learn/articles/dashboards/what-is">Tableau Software</a></blockquote><p>Mainly there are 3 points that should be followed to create a good dashboard. They are,</p><ul><li>Relevant content</li><li>Layout</li><li>Interactivity</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uy8cXHLR_r5tyOPtgVDX5w.png" /><figcaption><a href="https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesProfitDashboard">https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesProfitDashboard</a> (source)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*0yZRby123C-L27u1" /><figcaption><a href="https://community.dynamics.com/blogs/post/?postid=f2a77122-4a11-45cf-87a1-dc26927c7467">https://community.dynamics.com/blogs/post/?postid=f2a77122-4a11-45cf-87a1-dc26927c7467</a> (image)</figcaption></figure><h4>What is an interactive dashboard?</h4><p>An interactive dashboard is a dynamic, user-friendly interface that allows analysts to engage with and explore data in real time.</p><p>Static dashboards that simply display information and interactive dashboards enable users to manipulate the data, customize views, and drill down into specific details, making them powerful tools for data analysis and decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nvNIFrglArYngZZSpqdkSw.gif" /><figcaption><a href="https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesProfitDashboard">https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesProfitDashboard</a> (source)</figcaption></figure><p><strong>Storyboards </strong>is especially useful for presenting a data-driven story where each step or insight builds upon the previous one, leading the audience to a conclusion or key takeaway.</p><p>Each page is a specific dashboard that you want to highlight within the story. It could be a chart, a dashboard, or a particular filter setting applied to a visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1PEI9jVg1rBHDGXatmrpxg.gif" /><figcaption><a href="https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesStoryBoard?publish=yes">https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesStoryBoard?publish=yes</a> (source)</figcaption></figure><h4>Tools for Visualization Analytics</h4><ul><li>Power BI</li><li>Tableau</li><li>Qlik Sense</li><li>Google Data Studio</li><li>Looker</li><li>D3.js</li><li>Python (with libraries like Matplotlib, Seaborn, Plotly)</li></ul><p>In summary, visualization analytics is a powerful tool that leverages the strengths of both visual communication and analytical rigor, making data insights more accessible and actionable across various domains.</p><h4>References</h4><ul><li><a href="https://people.duke.edu/~rnau/411outbd.htm">https://people.duke.edu/~rnau/411outbd.htm</a></li><li><a href="https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesStoryBoard?publish=yes">https://public.tableau.com/app/profile/kaushiknshamantha/viz/SalesDashboard_16312517357750/SalesStoryBoard?publish=yes</a></li><li><a href="https://community.dynamics.com/blogs/post/?postid=f2a77122-4a11-45cf-87a1-dc26927c7467">https://community.dynamics.com/blogs/post/?postid=f2a77122-4a11-45cf-87a1-dc26927c7467</a></li><li><a href="https://www.tableau.com/learn/articles/dashboards/what-is">https://www.tableau.com/learn/articles/dashboards/what-is</a></li><li><a href="https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t">https://youtu.be/6mBtTNggkUk?si=jj3LvWDc4mANYr7t</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7308c7b6eacb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>