<?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 Milos Colic on Medium]]></title>
        <description><![CDATA[Stories by Milos Colic on Medium]]></description>
        <link>https://medium.com/@milos.colic?source=rss-16747f5bb100------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z-8EQzstP9FYhPns2boGNw.jpeg</url>
            <title>Stories by Milos Colic on Medium</title>
            <link>https://medium.com/@milos.colic?source=rss-16747f5bb100------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:09:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milos.colic/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[I Wrote an AI Paper in 2015. What Still Feels Right Is Context. And Why Emotion Still Matters.]]></title>
            <link>https://medium.com/@milos.colic/i-wrote-an-ai-paper-in-2015-what-still-feels-right-is-context-and-why-emotion-still-matters-e56a97036406?source=rss-16747f5bb100------2</link>
            <guid isPermaLink="false">https://medium.com/p/e56a97036406</guid>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Milos Colic]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 16:34:44 GMT</pubDate>
            <atom:updated>2026-04-09T16:34:44.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkOvieNBS5eLIX5w1byrng.png" /></figure><p>In 2015, while I was still in school, I wrote a paper with a gloriously overreaching title:</p><p><a href="https://github.com/milos-colic/super_AI_paper_2015/blob/main/SuperIntelligenceEssay.pdf"><em>Road to Super Artificial Intelligence: Is Artificial Intelligence Complete without Artificial Emotions</em></a></p><p>It was a student paper. It was not published. It was not a hidden breakthrough waiting for history to catch up.</p><p>But it was not nonsense either.</p><p>I reopened it recently because one part of it still feels alive. Modern agents keep failing exactly where that paper was trying, imperfectly, to look: at internal structure.</p><p>Not just what a system knows.</p><p>How it knows.</p><p>How it represents the world, itself, the human in front of it, what counts as evidence, what matters right now, and what should happen next.</p><p>That is the part that stayed with me.</p><h3>The Missing Distinction: AI Model Versus Logical Model</h3><p>To make the argument properly, one distinction has to be explicit from the start.</p><p>An AI model is the trained machine-learning system itself: a language model, reward model, classifier, retrieval model, planner, or some other learned component.</p><p>A logical model is something else. In Marvin Minsky’s 1965 essay <a href="https://philpapers.org/rec/MINMMA">“Matter, Mind and Models”</a>, a model is useful not because it reproduces the world in full fidelity, but because it helps answer questions about some target system. It is a usable internal representation. It is built for reasoning.</p><p>That matters because a powerful AI model can still fail if it is operating on a weak logical model.</p><p>It can have plenty of parameters and still carry the wrong constraint forward.</p><p>It can have a huge context window and still confuse related text for sufficient evidence.</p><p>It can retrieve a mountain of material and still fail to construct the relevant sub-world for the task at hand.</p><p>This is why I think context is the real bridge between that old paper and present-day agent design.</p><p>Context is not just tokens in a window.</p><p>Context is the task-relevant logical model a system constructs so it can act coherently.</p><h3>What The Old Paper Was Really Reaching For</h3><p>The paper argued that intelligence should not be reduced to cognition alone. It framed intelligence as requiring at least three things:</p><ol><li>cognitive intelligence</li><li>emotional intelligence</li><li>self-awareness</li></ol><p>That framing was bold. It was also incomplete in the way early frameworks often are: it was trying to compress too many important things into a few loaded words.</p><p>Still, the direction was not wrong.</p><p>What I was really reaching for was the idea that intelligence is architectural. It depends on multiple internal models interacting with one another. A system needs some logical model of the world, some logical model of itself, some interpretation of signals, some way of deciding salience, some mechanism for preserving what matters, and some way of updating behaviour when reality pushes back.</p><p>That is much closer to how modern agents actually behave than the older picture in which intelligence is treated like one flat scalar property.</p><h3>Why I Still Refuse To Discard Emotion</h3><p>This is where I differ from the safer mainstream reading.</p><p>I do not think the right correction is to say the paper was wrong because useful AI can exist without anything resembling emotion.</p><p>That is too easy.</p><p>A coding agent does not need heartbreak.</p><p>A SQL agent does not need shame.</p><p>That is true, and the line is worth keeping because it names an important boundary.</p><p>But it does not settle the real question.</p><p>The real question is incomplete for what.</p><p>If the task is sorting a linked list, emotions are irrelevant.</p><p>If the task is supporting a grieving patient, teaching a child, mediating a conflict, protecting a vulnerable user, or modelling what a frightened human actually means when they say they are fine, then emotion is not a decorative add-on. It is part of the logical model of the human world the system is operating in.</p><p>Even when an artificial system does not need to feel emotions in the biological human sense, it may still need mechanisms that play roles analogous to what emotions do in biological systems: compression of prior signals into fast behavioural guidance, salience assignment, reward shaping, prioritisation, and rapid shifts in action policy under changing conditions.</p><p>That is the stronger version of the old claim.</p><p>Not “AI must imitate human feelings.”</p><p>More like this:</p><p>Any system that aims to reason well about humans, or to regulate itself robustly in complex environments, will likely need explicit machinery for some of the effects that emotion serves in biological and social systems.</p><p>That machinery may be implemented very differently.</p><p>But it cannot be hand-waved away.</p><h3>The Better Modern Framing</h3><p>So if I were writing that paper today, I would not replace the emotion claim with a purely cold architectural claim.</p><p>I would make a union of the two.</p><p>I would say that intelligence depends on the quality of a system’s internal context architecture, and that architecture must often include:</p><ul><li>a logical model of the external world</li><li>a logical model of the system’s own state and capabilities</li><li>a logical model of the human user as a concrete entity, not an abstract average</li><li>a way to represent goals, constraints, and values</li><li>a way to structure reasoning rather than merely emit it</li><li>a way to distinguish evidence from related text</li><li>a way to compose multiple representations into one usable working context</li><li>a way to encode salience, urgency, and behavioural guidance, including some of the roles emotion plays in biological systems</li></ul><p>That feels much closer to the real problem.</p><h3>Four Design Questions For Modern Agents</h3><p>The architectural lesson becomes sharper when I break it into four questions.</p><h3>1. How Should The Relevant World Be Modeled?</h3><p>The important word there is relevant.</p><p>A useful logical model is not a copy of everything. It is a usable representation of the part of reality that matters for this task, for this user, at this time.</p><p>This is where modern context engineering starts to become serious. The problem is no longer just retrieval. The problem is deciding what belongs in the active sub-world now, what should remain latent, what deserves durable memory, what should be treated as uncertain, and what must never be forgotten. The distinction between relevant context and sufficient context matters here more than most agent chatter admits, and <a href="https://research.google/pubs/sufficient-context-a-new-lens-on-retrieval-augmented-generation-systems-2/">Google’s recent work</a> gives that distinction a useful name.</p><p>Projects like <a href="https://github.com/milla-jovovich/mempalace">mempalace</a> are interesting not because they prove some grand theory, but because they force a structural distinction: identity is not the same as critical facts, critical facts are not the same as recent recall, and recent recall is not the same as deep search.</p><p>That is the right instinct.</p><p>Context is not a pile.</p><p>At best, it is a hierarchy of different piles with very different jobs.</p><p>At its best, it is not a pile at all. It is an operating architecture for building the right logical model at the right time.</p><h3>2. How Should Reasoning Be Structured?</h3><p>Long-running agents fail because they do not just need intelligence. They need shape.</p><p>Sometimes reasoning should be linear. Sometimes it should branch. Sometimes it should pause for tool use. Sometimes it should recover from a bad intermediate step. Sometimes it should remember a procedure it has already learned rather than rediscovering it from scratch.</p><p>This is why recent work like <a href="https://arxiv.org/abs/2210.03629">ReAct</a>, <a href="https://arxiv.org/abs/2305.10601">Tree of Thoughts</a>, and workflow-memory approaches matters. They are all, in different ways, arguments against the fantasy that one giant monologue is the natural unit of intelligence.</p><p>Reasoning should be matched to task topology.</p><p>That sounds abstract, but it is not. <a href="https://research.google/blog/towards-a-science-of-scaling-agent-systems-when-and-why-agent-systems-work/">Google has shown this point very directly</a>: multi-agent designs can help on decomposable tasks and can hurt badly on sequential ones.</p><p>Architecture is not a garnish. It changes the result.</p><h3>3. How Should Evidence Be Structured?</h3><p>This is one of the weakest habits in current agent design.</p><p>Too many systems still behave as if retrieved text automatically becomes evidence.</p><p>It does not.</p><p>A strong system should be able to ask:</p><ul><li>what is the claim?</li><li>what supports it?</li><li>what only resembles support?</li><li>what would weaken it?</li><li>do we have relevant context, or actually sufficient context?</li></ul><p>That is why I find the bridge to argument structure and knowledge representation so interesting. The problem is not just memory quantity. It is evidence quality and evidence form. The <a href="https://openai.com/index/inside-our-in-house-data-agent/">OpenAI in-house data agent write-up</a> makes this point in production form, and the <a href="https://developers.openai.com/cookbook/examples/agents_sdk/session_memory">OpenAI session-memory cookbook</a> makes it in operational form.</p><p>Metadata, human annotations, procedural memory, retrieved passages, graph structure, runtime state, and model priors are not interchangeable. Treating them as interchangeable is one of the hidden reasons agents sound confident while being wrong.</p><h3>4. How Should These Models Be Composed?</h3><p>This might be the hardest question of all.</p><p>Different representational forms are good at different things.</p><p>Learned models are good at compression, fuzziness, pattern recognition, and generalisation.</p><p>Symbolic and graph structures are good at explicit relation, constraint handling, and inspectability.</p><p>Durable memory is good at persistence.</p><p>Runtime inspection is good at freshness.</p><p>User models are good at grounding behaviour in the actual person in front of the system rather than in some average imaginary user.</p><p>The design problem is not choosing one winner.</p><p>The design problem is deciding what each form should own, how they hand off to one another, and what truth conditions apply at each layer.</p><p>That is why I think context architecture matters more than context volume.</p><p>The number of tokens you can stuff into a window is not the main event.</p><p>The main event is how the system composes a usable logical model of the world from heterogeneous parts.</p><h3>Why Abundance Creates A New Failure Mode</h3><p>There is another parallel here that I do not think we talk about enough.</p><p>Systems evolved for scarcity often behave badly in abundance.</p><p>Humans in an abundant food environment discovered a new enemy: obesity. The instinct to ingest aggressively made sense under constraint and becomes maladaptive under abundance.</p><p>Agent systems show an analogous pathology with context.</p><p>Once you give them large windows, broad retrieval, tool access, memory stores, and endless documents, the primitive instinct is to ingest greedily. More text, more snippets, more history, more related material.</p><p>That is often the wrong instinct.</p><p>Abundant context without structure becomes cognitive obesity.</p><p>The system is full, but not sharp.</p><p>It has more material, but less discrimination.</p><p>This is one reason I think the real problem is not maximising context. It is metabolising it well.</p><h3>What I Believe Now</h3><p>I do not believe the road to better AI is to make machines perform human feelings on command.</p><p>I do believe the road to better agents runs through better context architecture.</p><p>And I also believe that once those agents are meant to serve humans seriously, that architecture must include a much better logical model of human emotion, value, intent, and vulnerability than the field often admits.</p><p>That does not mean forcing biology into code line by line.</p><p>It does mean taking seriously the functions that emotion serves in biological systems and the role emotion plays in the human worlds these agents must navigate.</p><p>So when I look back at that 2015 paper now, I do not see a solved theory of AI.</p><p>I see an ambitious early attempt to say that intelligence is not only calculation.</p><p>It is also internal structure.</p><p>It is model quality.</p><p>It is context design.</p><p>It is self-modeling.</p><p>It is human modeling.</p><p>And for a meaningful class of systems, it is impossible to think clearly about those things without thinking clearly about emotion as well.</p><p>That is the version of the claim I would defend today.</p><h3>References</h3><ul><li>Marvin Minsky, “Matter, Mind and Models” (1965): <a href="https://philpapers.org/rec/MINMMA">https://philpapers.org/rec/MINMMA</a></li><li>ReAct: <a href="https://arxiv.org/abs/2210.03629">https://arxiv.org/abs/2210.03629</a></li><li>Tree of Thoughts: <a href="https://arxiv.org/abs/2305.10601">https://arxiv.org/abs/2305.10601</a></li><li>CoALA: <a href="https://arxiv.org/abs/2309.02427">https://arxiv.org/abs/2309.02427</a></li><li>OpenAI, “Inside our in-house data agent” (January 29, 2026): <a href="https://openai.com/index/inside-our-in-house-data-agent/">https://openai.com/index/inside-our-in-house-data-agent/</a></li><li>OpenAI cookbook, “Context Engineering — Short-Term Memory Management with Sessions”: <a href="https://developers.openai.com/cookbook/examples/agents_sdk/session_memory">https://developers.openai.com/cookbook/examples/agents_sdk/session_memory</a></li><li>Google Research, “Sufficient Context: A New Lens on Retrieval Augmented Generation Systems” (ICLR 2025): <a href="https://research.google/pubs/sufficient-context-a-new-lens-on-retrieval-augmented-generation-systems-2/">https://research.google/pubs/sufficient-context-a-new-lens-on-retrieval-augmented-generation-systems-2/</a></li><li>Google Research, “Towards a science of scaling agent systems: When and why agent systems work” (January 28, 2026): <a href="https://research.google/blog/towards-a-science-of-scaling-agent-systems-when-and-why-agent-systems-work/">https://research.google/blog/towards-a-science-of-scaling-agent-systems-when-and-why-agent-systems-work/</a></li><li>Rosalind Picard, <em>Affective Computing</em> (1997): <a href="https://mitpress.mit.edu/9780262161701/affective-computing/">https://mitpress.mit.edu/9780262161701/affective-computing/</a></li><li>MIT News, “MIT team building social robot” (February 14, 2001): <a href="https://news.mit.edu/2001/kismet">https://news.mit.edu/2001/kismet</a></li><li>mempalace repository: <a href="https://github.com/milla-jovovich/mempalace">https://github.com/milla-jovovich/mempalace</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e56a97036406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hottest New Tool for Management Is Context Engineering]]></title>
            <link>https://medium.com/@milos.colic/the-hottest-new-tool-for-management-is-context-engineering-1951fbdd5741?source=rss-16747f5bb100------2</link>
            <guid isPermaLink="false">https://medium.com/p/1951fbdd5741</guid>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[management]]></category>
            <dc:creator><![CDATA[Milos Colic]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 12:34:00 GMT</pubDate>
            <atom:updated>2026-04-06T12:43:41.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYwz3mRSolxhCmt4NcdAmA.png" /></figure><h3>Why Enterprise AI Still Feels Hard</h3><p>Most enterprise <strong>AI</strong> discussion is still trapped in the wrong frame. It asks whether the models are smart enough, cheap enough, safe enough, or fast enough. And those questions do matter.</p><p>But for leaders trying to use AI inside a real organisation, they are no longer the whole story.</p><p><strong>The harder problem is operational: how do you give an AI system enough context to be useful without burying it in the very complexity you hoped it would tame?</strong></p><p><strong>This is why </strong><a href="https://www.linkedin.com/in/andrej-karpathy-9a650716/"><strong>Andrej Karpathy’s</strong></a><strong> recent </strong><a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f"><strong>gist</strong></a><strong> is worth reading, even for people who would never open a pseudo-blog on GitHub.</strong></p><p>What he is proposing is not just “chat with your files” dressed up in better language. <strong>It is a pattern</strong>. Keep raw sources immutable. Let the AI maintain an intermediate layer of summaries, entities, concepts, comparisons, and evolving synthesis. Give it explicit operating instructions. Give it an index so it can scan before it reads deeply. Give it a log so prior work does not disappear into chat history. <a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">[llm-wiki]</a></p><p>For most organisations, this is already <strong>a better mental model</strong> than the usual fantasy of one giant omniscient assistant hovering above a chaotic pile of documents. And, for the most part, Karpathy is pointing in the right direction. The useful extension is this: once you try to build such a system inside an organisation, the issue stops being model brilliance and becomes <strong>context discipline.</strong></p><p>At that point, context engineering stops sounding like an engineering detail and starts sounding like management. Because what is management, at some level, if not the design of who sees what, what counts as relevant, which rules govern decisions, where information lives, and how work gets handed from one actor to another?</p><p>An AI system has the same problem. Only faster. And more expensively.</p><h3>Why Context Becomes the Real Bottleneck</h3><p>Whilst building a similar system for personal and organisational support, I kept running into a blunt reality: tokens were being burnt like crazy. That sentence may sound technical. For leaders, it should be translated into business language.</p><p>It means rising operating cost. It means slower responses. It means inconsistent answers. It means repeated work. It means lower trust because the system keeps dragging in irrelevant material and missing the one thing that mattered. The very tool that was supposed to be an enabler turned into a bottleneck. [<a href="https://direct.mit.edu/tacl/article/doi/10.1162/tacl_a_00638/119630/Lost-in-the-Middle-How-Language-Models-Use-Long">Lost in the middle</a>]</p><p>An AI assistant that reads too much, searches too widely, and recomputes too often behaves like a bright but disorganised staffer. It is energetic, occasionally brilliant, and constantly at risk of wasting everyone’s time.</p><p>This is why the middle layer matters so much. [<a href="https://www.anthropic.com/research/contextual-retrieval">Introducing Contextual Retrieval</a>]</p><p>You can think of it as a lightweight organisational <strong>ontology</strong>, built quickly and imperfectly by the AI as it works. Not a pristine enterprise knowledge graph designed by committee over eighteen months. Something humbler. And, in many situations, something far more useful.</p><p>If the goal is an AI agent that helps a leader navigate the organisation’s information landscape as a virtual PA, then “poorly but quickly” is often good enough, provided the structure is legible, revisable and scoped down to the area of influence.</p><p>The assistant does not need a metaphysically complete model of the company. It needs a working map. It needs to know the important entities, recurring topics, current priorities, durable constraints, and where to look next. That is enough to make the system useful. And that is enough to compound.</p><h3>From Engineering Pattern to Management Tool</h3><p>This is where the simple mechanisms in Karpathy’s gist become surprisingly powerful for leadership. An INDEX.md is not just an engineering file. It is a map of the terrain. In leadership terms, it functions like a portfolio view, an operating dashboard, or a guide to where knowledge lives.</p><p>The instruction file is not just a prompt. It is role clarity and decision policy. It tells the assistant what kind of work it is doing, what rules it must follow, and how to behave when uncertainty appears.</p><p>The log is not just housekeeping. It is organisational memory and audit trail. It answers a question every leader eventually asks: what happened, when, and why?</p><p>The maintained summaries and working pages are not just notes. They are reusable decisions. They are standard work. They are the difference between insight that compounds and insight that vanishes into chat. [<a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">llm-wiki</a>]</p><p>This is why I like the phrase:</p><p><strong>The hottest new software problem is context engineering.</strong></p><p>But for leadership the more provocative version may be this:</p><p><strong>The hottest new management tool is context engineering.</strong></p><p>Because leaders are not only buying intelligence now. They are designing the context in which machine intelligence operates. <strong>That is a management act</strong>. It shapes speed, consistency, delegation quality, and organisational trust.</p><h3><strong>Where does AI acceleration Matters</strong></h3><p><strong>Executive briefing:</strong> Instead of manually stitching together updates from Slack, email, decks, CRM notes, and project trackers, an AI assistant can maintain an evolving operational view. But only if it has a disciplined index of what matters, clear source boundaries, and a way to distinguish live signals from stale synthesis.</p><p><strong>Onboarding:</strong> A new manager usually learns by pinging ten people, reading outdated docs, and slowly piecing together the unwritten rules. A well-structured AI assistant can accelerate that dramatically. But only if the system has working memory, explicit instructions, and a maintained map of people, processes, and priorities.</p><p><strong>Cross-functional execution:</strong> Many leadership failures are really information routing failures. Teams know fragments of the truth, but no one sees the whole picture in time. An AI assistant can help here as a connective layer. But only if it knows where truth lives and what should not be inferred from partial signals.</p><p><strong>Decision support:</strong> Leaders do not need an assistant that produces eloquent paragraphs on demand. They need one that can say, quickly and reliably, what changed, what matters, what conflicts with prior decisions, and where the evidence came from. [<a href="https://www.anthropic.com/engineering/building-effective-agents">Building effective agents</a>]</p><h3>Skills, Specialisation, and the New Coordination Cost</h3><p>Now we arrive at another important layer: skills.</p><p>A general model becomes much more useful in an enterprise when it can switch into specific modes of work. A board-prep skill. A weekly operating review skill. A customer-escalation skill. A diligence skill. A chief-of-staff skill. A compliance triage skill.</p><p>This is how AI starts to feel less like a clever chatbot and more like a usable staff function. [<a href="https://simonwillison.net/guides/agentic-engineering-patterns/how-coding-agents-work/">How coding agents work</a>]</p><p>Skills package instructions, expectations, and workflows into repeatable operating routines.</p><p>They tell the system not only what information matters, but what kind of job it is performing. <strong>That is powerful</strong>. It is also where many teams quietly reintroduce the same waste they thought they had removed.</p><p>Every skill carries context overhead. It brings instructions, conventions, expected artifacts, and often additional files into play. Nested skills can amplify that further. A high-level leadership workflow may call a briefing skill, which calls a sales-summary skill, which calls a customer-account skill, which calls retrieval across multiple knowledge stores.</p><p>Even when indexes and pruning are in place, the overhead can accumulate.</p><p>The underlying reason is simple. Specialised subagents or skills can preserve the main thread’s context by working in their own windows, which is useful, but the work still costs tokens somewhere. Anthropic’s subagent documentation makes both sides explicit: separate context windows can preserve the main conversation, and many detailed subagent results can still consume significant context when they return. The same logic applies to skill-heavy enterprise systems. You have not abolished the context problem. You have redistributed it. [<a href="https://code.claude.com/docs/en/sub-agents">Create custom subagents</a>]</p><p>This is very important.</p><p>If leaders are serious about AI assistants, they need to think about skill design the way they think about organisational design.</p><p>Which skills deserve to exist?</p><p>Which should be broad and which should be narrow?</p><p>When should one skill call another?</p><p>What information should be passed forward, and what should stay local?</p><p>What artifacts should persist after the skill completes? [<a href="https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents">Effective harnesses for long-running agents</a>]</p><p>When does specialisation create leverage, and when does it create bureaucracy in silicon?</p><p>These are not merely software design questions.</p><p>They are operating model questions.</p><p>What should the system know?</p><p>What should it defer?</p><p>What counts as source of truth?</p><p>How should judgment be distributed between humans and machines?</p><p>How do we audit the decisions that emerge? [<a href="https://modelcontextprotocol.io/docs/learn/architecture">Model Context Protocol, architecture overview</a>]</p><p>This is why I think the important leadership lesson from Karpathy’s gist is not that AI gives us a new way to talk to computers. It is that AI forces us to become more explicit about how our organisations think.</p><p>The companies that benefit most will not be the ones with the flashiest demos. They will be the ones that build the better ladders between raw information, working context, reusable judgment, and action.</p><p>They will be the ones that accept a fast, imperfect, continuously maintained map of the organisation instead of waiting for a perfect representation that never arrives.</p><p>They will be the ones that understand that context is now a managed asset.</p><p>And that managing it well is quickly becoming a leadership advantage.</p><p>[<a href="https://simonwillison.net/guides/agentic-engineering-patterns/how-coding-agents-work/">How coding agents work</a>]</p><p><strong>Note:</strong> This essay was written with the help of my AI assistant. That is not incidental. It is evidence of the point: these systems are already becoming practical tools for navigating information, shaping judgement, and supporting managerial work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1951fbdd5741" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unifying Raster and Vector data with Mosaic]]></title>
            <link>https://medium.com/@milos.colic/unifying-raster-and-vector-data-with-mosaic-76b00a4d2b96?source=rss-16747f5bb100------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b00a4d2b96</guid>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Milos Colic]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 17:59:22 GMT</pubDate>
            <atom:updated>2023-02-14T17:59:22.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3FwDfhyiIicqgbq.png" /></figure><p>We face a remarkably <a href="https://gisgeography.com/gis-formats/"><em>diverse and broad set of data formats</em></a> regarding geospatial data processing at scale. These data formats have been designed with particular use cases in mind and, within that context, are very efficient. However, combining data across these different data sources can prove to be a tough challenge. Frameworks like <a href="https://gdal.org/"><em>GDAL</em></a> have emerged aiming to abstract these complexities. In this blog, we will cover how <a href="https://databrickslabs.github.io/mosaic/"><em>Mosaic</em></a> integrates with GDAL, the abstractions Mosaic provides in spatial SQL and how that allows us to easily combine raster and vector data into a unified system.</p><h4>The value behind the raster “paywall”</h4><p>Rasters are a compelling set of data formats. Data assets describing climate data, weather data, satellite data, flood regions, soil data, harvest data, and many more are often supplied as raster data. The trouble is that most data scientists are not trained to handle raster formats. In most cases, barriers like obtaining requisite GIS expertise and complexities of advanced frameworks such as GDAL, create a “paywall” that hides available insights from those seeking to work with raster data. However, the value inside these assets can help us address use cases such as climate risk, flood risk, ESG, alternative energy site planning; the list goes on and on. How can we bring these data assets closer to data scientist and analyst communities and decouple from GIS expertise?</p><h4>GDAL as an enabler</h4><p>GDAL stands for “Geospatial Data Abstraction Library”, and as the name suggests, it provides an abstraction layer over raster and vector data formats. This is a robust approach toward simplifying and unifying the code required to process data. Indeed some formats are more complex than others (e.g. <a href="https://www.unidata.ucar.edu/software/netcdf/">NetCDF</a>) and require reasoning about subdatasets, but the abstractions provided allow us to overcome these complexities easily.</p><pre>import org.gdal.gdal.gdal;<br>import org.gdal.gdal.Band;<br>import org.gdal.gdal.Dataset;</pre><pre>...<br>Dataset dataset = gdal.Open(filename);<br>Band band = dataset.GetRasterBand(1);</pre><p>The code above illustrates how we can read a band of raster data using GDAL and a filename. It is important to note that we aren’t explicitly providing the format, and we expect GDAL to infer this from the file extension. This can be a massive enabler that simplifies and unifies the code needed to produce a piece of analysis.</p><p>Finally, GDAL is compiled using system native code and provides a very performant framework. Unfortunately, this comes with a cost when considering specific applications of this powerful tool. Being a platform-specific framework means there is a higher risk of encountering challenges when installing GDAL. Furthermore, using java bindings for GDAL comes with additional complexities. It is not an overstatement to say that there are expectations of skill levels for GDAL users. So how can we leverage this framework to democratise geospatial data?</p><h4>Easy GDAL for Databricks with Mosaic</h4><p>Since version <a href="https://pypi.org/project/databricks-mosaic/0.3.7/"><em>0.3.7</em></a>, Mosaic integrates with GDAL and provides a set of abstractions that make raster data more accessible to individuals that would not classify themselves as GIS experts.</p><p>Firstly, Mosaic introduces an <a href="https://databrickslabs.github.io/mosaic/usage/install-gdal.html"><em>easy install of GDAL for Databricks</em></a>. This involves the generation of an init.sh script and providing necessary shared object files (without this, GDAL won’t work in java based languages nor java based frameworks like Apache Spark™).</p><pre># Once per cluster/workspace, the generated init script can be reused<br>import mosaic as mos<br>mos.enable_mosaic(spark, dbutils)<br>mos.setup_gdal(spark)</pre><pre># Configure the init script on a fresh cluster<br>import mosaic as mos<br>mos.enable_mosaic(spark, dbutils)<br>mos.enable_gdal(spark)</pre><p>The benefit of this approach is that the packaged scripts are version-controlled and unit tested for the version of Mosaic. This way, we ensure consistency between installed GDAL as a dependency and the exposed functionality.</p><h4>RST_ APIs in Mosaic</h4><p>Mosaic brings <a href="https://databrickslabs.github.io/mosaic/api/raster-functions.html">30+ raster functions/expressions</a>. All the raster functions that you can use in Mosaic are prefixed by RST_. RST_ stands for “raster” or “raster spatiotemporal” functions.</p><pre>import mosaic as mos<br>mos.enable_mosaic(spark, dbutils)<br>mos.enable_gdal(spark)</pre><pre>df = spark.read \<br>  .format(&quot;binaryFile&quot;).option(&quot;pathGlobFilter&quot;, &quot;*.nc&quot;) \<br>  .load(&quot;dbfs:/sample_raster_data/binary/netcdf-coral&quot;)</pre><pre>df.select(mos.rst_georeference(&quot;path&quot;)).limit(1).display()</pre><p>All the APIs provided by Mosaic are available in Python, SQL, R and Scala/Java; please refer to the documentation page for examples of function usage.</p><p>RST_ expressions including metadata inspection, re-tiling of rasters and conversion of rasters into grid index system representation. Grid index systems such as <a href="https://h3geo.org/">H3</a> and <a href="https://en.wikipedia.org/wiki/Ordnance_Survey_National_Grid">BNG</a> are core to the way Mosaic represents vector data.</p><pre>df = spark.read \<br>  .format(&quot;binaryFile&quot;).option(&quot;pathGlobFilter&quot;, &quot;*.nc&quot;) \<br>  .load(&quot;dbfs:/sample_raster_data/binary/netcdf-coral&quot;)</pre><pre>df.select(mos.rst_rastertogridavg(&#39;path&#39;, F.lit(3)).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lsHRlDrBAnF4xVLz.png" /><figcaption>RST_RasterToGridAvg example of NetCDF data</figcaption></figure><p>Using RST_RasterToGrid* set of operations, Mosaic users can easily convert raster data into grid-based data that can be accessed from notebooks or Databricks SQL. This is a significant simplification of data access for individuals that aren’t GIS experts and have no knowledge of underlying data formats and/or of GDAL’s existence.</p><h4>Combining vector and raster</h4><p>We have followed the same philosophy for raster data as we did for vector data. Through this shared approach, we can ensure both vector and raster data are represented in a unified way that allows for easy combinatorics between data assets.</p><p>In Mosaic, users can use ST_GridTesselate* set of operations to represent vector data in grid index systems as a set of piecewise geometries (chips) contained within a single index cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ONBib4-LGEVACfqb.png" /><figcaption>Tessellation of a polygon in H3(8)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CM-gLU-_rYHHeDQE.png" /><figcaption>Tessellation of a polygon in BNG(4)</figcaption></figure><p>Now that both vector and raster data are represented in the same domain, we can easily combine data assets between vector and raster domains and produce insights. Combining data is as easy as doing a simple SQL join based on grid index cell ids.</p><pre>vector_df = spark.read.load(&quot;dbfs:/sample_vector_data/regions&quot;)<br>raster_df = spark.read \<br>  .format(&quot;binaryFile&quot;).option(&quot;pathGlobFilter&quot;, &quot;*.nc&quot;) \<br>  .load(&quot;dbfs:/sample_raster_data/binary/netcdf-coral&quot;)</pre><pre>vector_df = vector_df.select(grid_tessellateexplode(&#39;wkt&#39;, lit(3)))<br>raster_df = raster_df.rst_rastertogridavg(&#39;path&#39;, lit(3))</pre><pre># RST_RasterToGrid* functions return a set of grid index cells<br># for each band of the raster, so we need to flatten the dataframe<br># Please note that we need to explode the dataframe twice</pre><pre>raster_df = raster_df \<br>    .withColumn(&quot;grid_values&quot;, <br>                mos.rst_rastertogridavg(&quot;path&quot;, lit(3))) \<br>    # explode bands<br>    .withColumn(&quot;grid_values&quot;, explode(&quot;grid_values&quot;)) \<br>    # explode (cell, measure) pairs<br>    .withColumn(&quot;grid_values&quot;, explode(&quot;grid_values&quot;)) \<br>    .withColumn(&quot;index_id&quot;, col(&quot;cellID&quot;))</pre><pre>result_df = vector_df.join(raster_df, on=&quot;index_id&quot;)</pre><p>Mosaic support all <a href="https://gdal.org/drivers/raster/index.html">raster drivers</a> supported by GDAL, including TIF, COG, GRIBB, NetCDF and many more formats. Currently, Mosaic doesn’t expose OGR vector drivers from GDAL; this will come with future releases.</p><h4>Future releases</h4><p>In future releases, Mosaic will focus on expanding both the vector and raster set of APIs to simplify more use cases. In addition, we will bring custom grid index system support and user-defined functions (UDFs) for easy integration of custom shapely, rasterio and GDAL code. Finally, Mosaic will support automatic query optimization rules that can reorder your queries automatically to automatically use grid index systems if the operation can benefit from them.</p><p>This blog has covered the unification of raster and vector data under grid index systems as a unification framework. We have covered the pain points of handling frameworks like GDAL and their value and provided an approach of easy access to such valuable tools within Databricks lakehouse platform. Finally, we have provided a summary of what next is coming into Mosaic framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b00a4d2b96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Spatial Nearest Neighbours with Mosaic]]></title>
            <link>https://medium.com/@milos.colic/scalable-spatial-nearest-neighbours-with-mosaic-336ce37edbae?source=rss-16747f5bb100------2</link>
            <guid isPermaLink="false">https://medium.com/p/336ce37edbae</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[h3]]></category>
            <category><![CDATA[knn]]></category>
            <dc:creator><![CDATA[Milos Colic]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 17:44:14 GMT</pubDate>
            <atom:updated>2022-12-07T17:48:22.338Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Proximity_analysis">Proximity analysis</a> has many applications across multiple industries. Whether your use case is to perform property searches, fraud analytics, customer segmentation, demographic analytics, ect., it can benefit from proximity analysis techniques. Proximity analysis includes many techniques such as spatial autocorrelation, gravity models, spatial nearest neighbours and many more. In this blog we will focus on spatial nearest neighbours algorithm, or more precisely, an efficient implementation of spatial nearest neighbours algorithm that scales with big data and is available in <a href="https://databrickslabs.github.io/mosaic/">Mosaic</a> v0.3.5 by <a href="https://www.databricks.com/">Databricks.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*0BZ2YIycvCZ17t5a" /><figcaption>Figure 1: Spatial nearest neighbours (<a href="https://labs.mapbox.com/education/proximity-analysis/">source</a>)</figcaption></figure><h3><strong>So close yet so far</strong></h3><p>Usually when asserting the notion of nearest neighbours we bound that notion to the K neighbours, if left unbound the answers produced by the analysis are basically orderings of the whole data assets based on the proximity/distance and the computational costs to produce such outputs can be very prohibitive since they would result in comparing all features across all data assets. For the rest of this blog we will assume that we are discussing only Spatial K nearest neighbours (Spatial KNN) as the only pragmatic problem to solve for big data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DEuwg-aDj_maPVX0" /><figcaption>Figure 2: Flowchart Naive Spatial KNN (left) vs Mosaic Spatial KNN (right)</figcaption></figure><p>Spatial nearest neighbours is a difficult problem to solve, for several reasons all of which are particularly hard when applied in big data context and when distributed compute engines (like <a href="https://spark.apache.org/">Apache Spark</a>) are used:</p><p><em>1. Curse of Dimensionality</em>: This refers to the fact that as the number of features or dimensions increases, the amount of data required to make effective predictions grows exponentially. As a result, the performance of nearest neighbour algorithms may suffer when applied to high-dimensional datasets.</p><p>In our context, we are limiting the distance function to be the spatial distance between 2 geometrical features in two different data assets. This way we can avoid very costly cartesian product searches in order to produce the more complex comparisons amongst observations. Once spatial KNN results are returned one can further prune results based on a secondary distance function that includes other dimensions in the dataset.</p><p><em>2. Computational Complexity: </em>Nearest neighbour algorithms can be computationally intensive, as they require a large amount of memory and time to process. This can become a major problem when dealing with large datasets.</p><p>By using Apache Spark, we ensure to have a computation engine that can scale with our data. With the introduction of a new iterative approach that mimics the nature of ball trees we ensure independence between different data partitions and ensure high levels of parallelism. Our approach scales with millions of rows in either data assets.</p><p><em>3. Outliers: </em>Outliers can have a major impact on nearest neighbour algorithms, as they can significantly distort the distances between data points. As a result, it is important to identify and remove any outliers before using a nearest neighbour algorithm.</p><p>In our implementation, we do not need to prune outliers. The iterative nature of the algorithm is self-regulating when it comes to handling outliers. Our approach does not require building the indexes or index trees and as such it avoids costly collection of whole data sets or sampling strategies required when solving for big data use cases.</p><h3><strong>Keep the ball rolling</strong></h3><p>The first step in implementing Spatial KNN is to define the distance metric that is to be used to measure the similarity between objects. The most commonly used metrics for spatial data are Euclidean distance, Manhattan distance, and cosine similarity. Once the metric has been chosen, the objects must be mapped into a spatial coordinate system so that the distances between them can be calculated.</p><p><strong>​​</strong>Next, the number of nearest neighbours to consider is determined. This is usually done by setting the K parameter. One extension can be introduced at this point, the algorithm can apply a distance threshold for considering a pair of geometries neighbours. If the distance is larger than the threshold then the pair of geometries are not considered neighbours.</p><p>The algorithm then iterates through all objects in the data set. For each object, it calculates the distances to all of its neighbours and stores the information in a list. The list is then sorted and the k nearest neighbours are selected.</p><p>This is the naive approach and simply won’t scale with very large data sets. The description above is equivalent to a Cartesian product between data sets followed by a sort based on distance between two geometries and finally a window over K rows with minimal value for distance for each row in the left hand side data set.</p><p>Efficient implementations for spatial KNN (K-Nearest Neighbour) involve making use of spatial data structures and algorithms, as well as taking advantage of certain characteristics of the data to speed up the search process. When dealing with spatial data, it is important to make use of spatial data structures, such as <a href="https://en.wikipedia.org/wiki/Quadtree#:~:text=A%20quadtree%20is%20a%20tree,into%20four%20quadrants%20or%20regions.">quadtrees</a>, <a href="https://en.wikipedia.org/wiki/K-d_tree">k-d trees</a>, <a href="https://en.wikipedia.org/wiki/Ball_tree">ball trees</a>, etc. These data structures store the data points in an organised fashion, making it easier to search for the nearest neighbours. In addition, they can be used to quickly prune away points that are not close enough to the given point, which reduces the amount of time needed to search for the k-nearest neighbours.</p><p>In big data context it is not desirable to build centralised views over the dataset since iterating over all rows in the dataset can be too costly. The build trees can occupy too much memory themselves and crash the execution by causing Out of Memory Errors. And many other problems can occur if these techniques are applied in the same way they were intended for single node compute environments (single server/your laptop).</p><p>Another way to speed up the search process is to make use of spatial indexes (<a href="https://h3geo.org/">H3</a>, <a href="https://en.wikipedia.org/wiki/Ordnance_Survey_National_Grid">BNG</a>, <a href="https://s2geometry.io/">S2</a>, etc). These indexes organise the data points in a fashion that makes it easier and faster to find the nearest neighbours. For example, a grid index organises the data points in a grid-like manner, making it easy to find the points that are closest to the given point. Similarly, a radius index (ball tree) stores the points in a circular structure, allowing the algorithm to quickly identify the points that are within a certain radius of the given point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HtJ7fWeVsWj57VbP" /><figcaption>Figure 3: H3 grid index</figcaption></figure><p>Mosaic comes with several functionalities that will allow us to leverage the principles outlined both in grid index systems and radius index systems. Mosaic implements both H3 and BNG index systems out of the box and provides functionalities like <a href="https://databrickslabs.github.io/mosaic/api/spatial-indexing.html#grid-tessellate">grid_tesselate</a> or <a href="http://grid_cellkring/">grid_kring</a> (<a href="https://databrickslabs.github.io/mosaic/api/spatial-indexing.html">see more</a>).</p><p>If we combine radius index approaches with grid index approaches we can quickly understand that the concept of kring is the key concept for achieving an iterative spatial k nearest neighbours implementation that scales with your data. It is worth noting that the K in kring and the K in KNN aren’t the same Ks. K in kring indicates the grid radius of the kring — for kring(1) returns all cells that are 1 cell away from the specified cell, kring(2) returns all cells that are 2 cells away and so on. K in KNN indicates the number of neighbours we have requested to be identified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C29PUP5TuQDyqeaC" /><figcaption>Figure 4: H3 kring(2) in Mosaic.</figcaption></figure><p>Using the kring concept we can define areas of interest around each point of interest and within those areas of interest we can identify the neighbours as the answer to the spatial nearest neighbours problem.</p><h3><strong>Landmarks of interest</strong></h3><p>On top of the kring concept, Mosaic introduces concepts of geometry-aware krings; these rings grow in a concentric way around the supplied geometry. They can help us address the skew that would be introduced if we performed our search based only on centroids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v5ItUV8dyVCsaSuX" /><figcaption>Figure 5: BNG geometry aware kring(2)</figcaption></figure><p>Finally, Mosaic introduces the concept of a kloop. In essence, kloop(N) is a set difference between kring(N) and kring(N-1). It produces a set of cells that are exactly N cells away from the provided cell (for cell variant) or from the provided geometry (for the geometry aware variant).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oTKhOp_ryHhOHiTZ" /><figcaption>Figure 6: H3 geometry aware kloop(2)</figcaption></figure><p>With the introduction of geometry aware functionality we have solved for an interesting extension to the definition of spatial nearest neighbours. We can define the problem as an iterative join relationship. We can define 2 data sets that we are interested in. The left hand dataset would represent all the landmarks we are interested in finding the neighbours for. The right hand dataset would represent all the candidate neighbours.</p><p>Using this definition naturally extends the application of the algorithm to arbitrary spatial proximity analytics. The landmarks dataset can be any geometry dataset, residential building, schools, supermarkets, while the candidates dataset can be roads, rivers, lakes, parks, other residential buildings, demographics statistics, mobility data, etc. If one wants to find the neighbourhoods within the same dataset that is as simple as passing the same dataset as both landmarks and candidates.</p><p>The fact that we are not restricted to points only, but can use landmarks, means that we do not need to pre process geometries in order to force point-wise representation. Geometries are provided as-is, whether they are MultiPolygons, Polygons or MultiLines, focusing on what they represent rather than how they are stored. This maximises analytical value since any unnecessary simplifications are avoided.</p><h3><strong>The answer for proximity</strong></h3><p>Putting all of these concepts together, Mosaic implements an iterative algorithm that iterates through N kloop calls around every geometry and identifies the incremental set of neighbours. Given the fact that each iteration returns only a partial result, Mosaic maintains a checkpoint result set that grows until K neighbours are identified for the specified geometry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OJ7vCyhv9R-_qElY" /><figcaption>Figure 7: Iterative Spatial KNN in Mosaic</figcaption></figure><p>Mosaic ensures that in every iteration only the minimal required number of comparisons are made, hence avoiding the curse of the Cartesian product. Mosaic can compare datasets with millions of complex shapes within minutes.</p><p>The set of K neighbours is produced as a union of neighbours found in kloop(1), kloop(2) all up to kloop(max_iterations). The process is additive since kloops are non-overlapping. This ensures that individual iterations are independent of each other.</p><p>One thing worth noting is that the result at the final iteration is an approximation of the actual result. This is due to spatial skew that can be introduced by grid index cell distortions and due to kloop spatial distortion (kloop is only an approximate loop around the geometry). We can stabilise these results by identifying the Kth neighbour. Kth identified neighbour is at least the Kth neighbour of the landmark, however this neighbour can be further and there may be a closer neighbour available in the data and was missed due the distortions outlined above. At this point we can identify the distance between the landmark geometry and the Kth neighbour. Based on this distance we can construct a buffered geometry around the landmark and capture all neighbours in this area. This set contains at least K neighbours and contains the real KNN set, we can order these neighbours and return K of them. Mosaic allows end users to choose between the approximate (faster) and exact (slower) implementations of the algorithm.</p><p>This algorithm implements <a href="https://spark.apache.org/docs/latest/ml-guide.html">spark-ml</a> APIs and in effect integrates with frameworks like <a href="https://mlflow.org/">mlflow</a>. This can ensure reproducible results and easy collection of metadata.</p><pre>import mosaic as mos<br>mos.enable_mosaic(spark, dbutils)<br><br>buildings_df = spark.read.table(&quot;buildings&quot;)<br>buildings_df = buildings_df.withColumn(&quot;left_id&quot;, monotonically_increasing_id())<br>roads_df = spark.read.table(&quot;roads&quot;)<br>roads_df = roads_df.withColumn(&quot;right_id&quot;, monotonically_increasing_id())<br><br>from mosaic.models import SpatialKnn<br>import mlflow<br><br>with mlflow.start_run():<br>  knn = SpatialKNN(roads_df)<br>  knn.setLeftGeometryColumn(&quot;geometry&quot;)<br>  knn.setRightGeometryColumn(&quot;geometry&quot;)<br>  knn.setLeftIdColumn(&quot;left_id&quot;)<br>  knn.setRightIdColumn(&quot;right_id&quot;)<br>  knn.setK(5)<br>  knn.setMaxIterations(10)<br>  knn.setDistanceThreshold(1.0)<br>  knn.setUseTableCheckpoint(True)<br>  knn.setCheckpointTablePrefix(&quot;checkpoint_table_knn&quot;)<br>  knn.setIndexResolution(10)<br><br>  neighbours = knn.transform(buildings_df)<br><br>  mlflow.log_params(knn.getParams())<br>  mlflow.log_metrics(knn.getMetrics())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*ol6Ous2plS9oEWn6" /><figcaption>Figure 8: Spatial KNN parameters in mlflow</figcaption></figure><p>In the mlflow output, we can identify all the parameters we can set for the algorithm. The full documentation for the spatial KNN algorithm can be found <a href="https://databrickslabs.github.io/mosaic/models/spatial-knn.html">here</a>.</p><h3><strong>How far is too far</strong></h3><p>In order to handle extreme points and outliers we have added the support for distance thresholds. The idea behind distance threshold is to regulate for meaningless results. The nature of the KNN approach dictates that the user provides the K number before (in many cases) knowing if K is globally appropriate. Adding the support for distance thresholds allows us to relax the K value, if the K is set to too large a value we can still prune unnecessary results by the notion of being too far.</p><p>One thing to note is that if K is set to a very large value, the algorithm will iterate over a larger number of candidates and may do more computation and may require more time to converge.</p><p>Another level we have to control the overall convergence of the algorithm is that of maximum number of iterations and early stopping. Through the maximum number of iterations we can control how far the algorithm will go to find the neighbours, this concept is very similar to that of the max distance threshold. The difference is that max iterations parameter expresses distance in the number of iterations (number of grid cells) the algorithm will traverse and it is an indirect distance threshold.</p><p>Finally, the early stopping helps us stop the iterations if no new neighbours were identified for the specified number of iterations. This ensures that the algorithm doesn’t keep on running without producing any useful results.</p><h3><strong>So many questions left to ask</strong></h3><p>When we talk about <a href="https://databrickslabs.github.io/mosaic/models/spatial-knn.html">spatial nearest neighbours (SNN) algorithm</a> we are not trying to solve a clustering problem — there are many efficient implementations that address this problem. In this blog we focused on grouping different geospatial features based on a proximity/distance where these features may come from the same or a different data asset. The ability to combine different spatial data assets based on the notion of proximity/distance can be a very powerful tool to solve for many business applications.</p><p>1. <a href="https://en.wikipedia.org/wiki/Location-based_advertising">Location Based Advertising</a>: Location-based advertising is a marketing technique that uses location data to deliver targeted advertisements to consumers. This type of advertising is based on the idea that people are more likely to respond to advertisements that are relevant to their location, such as ads for products or services available in their immediate area. Location-based advertising can be used to target potential customers who are in a specific geographic location, or to deliver personalised messages to customers based on their past purchase history, preferences, or other data. It can also be used to reach out to customers who are in a specific area, such as a shopping mall or a restaurant. This type of advertising is enabled by the use of location data gathered from mobile devices, such as smartphones and tablets, as well as from other sources, such as GPS signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*gtYK9SHHqh1UwuQY" /><figcaption>Figure 9: Location based Advertising (<a href="https://www.digitaljournal.com/pr/location-based-advertising-lba-market-2022-industry-insight-drivers-top-trends-global-analysis-and-forecast-by-2027">source</a>)</figcaption></figure><p>Spatial nearest neighbours can be used to identify customers who are in the vicinity of a specific store, restaurant, or other venue, and to deliver targeted advertisements to those customers.</p><p>Identifying such customers can be achieved with following steps:</p><pre>1) Set landmarks dataset to be location data of the users (last mobile<br>ping, last payment transaction, etc). We are inverting the landmark <br>notation here since we want to return K nearest stores to each consumer<br>- consumers are our logical landmarks.<br><br>2) Set candidates dataset to be your points of interest (store location,<br>restaurant, etc.), this can be the centroid of the building or the <br>actual shape of the building. Shapes can be very important for malls <br>and/or shopping centres.<br><br>3) Run mosaic KNN with K set to appropriate value (eg. 5/10/20).<br><br>4) Return results for the selected users.</pre><p>By using spatial nearest neighbours, businesses can better understand their customers’ preferences and interests, and deliver customised advertisements that are more likely to be successful. Additionally, spatial nearest neighbours can help businesses to target customers in a specific geographic location, such as a shopping mall or a restaurant, and to track the effectiveness of their advertising campaigns.</p><p>2. <a href="https://carto.com/blog/new-approach-customer-segmentation-location-data/">Customer Segmentation</a>: Spatial customer segmentation is a data analysis technique used to identify areas of a geographic region where customers with similar characteristics are located. The technique is used to identify market opportunities and target potential customers by analysing their geographic locations. It is often used in marketing and sales to identify potential customers and target them with tailored campaigns and services. By analysing a customer’s location, businesses can make decisions about their marketing strategies and focus their efforts on specific locations. Spatial customer segmentation can help businesses better understand the needs of their customers, identify new market opportunities, and optimise their marketing efforts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TdBryYS8792m5HzX" /><figcaption>Figure 10: Customer Segmentation using Location (<a href="https://carto.com/blog/new-approach-customer-segmentation-location-data/">source</a>)</figcaption></figure><p>Spatial nearest neighbours can be used to divide customers into segments based on their geographical locations.</p><p>There are several approaches to segmenting customers based on their location, we could generate H3 index values for their addresses and produce cell level segments. Another approach is to group users by proximity to a specific store or brand or multiple stores. This approach can be achieved as follows:</p><pre>1) Set landmarks dataset to location of stores. If shapes are <br>available we should use them for more robust outputs.<br><br>2) Set candidates dataset to the location of customers.<br><br>3) Run mosaic KNN with K set to appropriate value (eg. 1000s).<br><br>4) Extract customer segment definition for each store by using <br>appropriate operation (ie. mean age, median salary, modal postcode).<br><br>5) Return customer segmentation per store or per brand (rollup <br>from stores).</pre><p>This approach can be used to identify groups of customers who are geographically close to each other and who share similar characteristics. This can be used to create more targeted marketing campaigns and increase sales by targeting specific customer segments. Additionally, it can be used to identify areas of opportunity and help optimise the placement of stores and other businesses.</p><p>3. <a href="https://www.mckinsey.com/industries/retail/our-insights/supercharging-retail-sales-through-geospatial-analytics">Retail Store Optimisation</a>: Retail store location optimisation is a process used by companies to determine the optimal locations for their physical retail stores. Companies use a variety of data sources to determine the best locations for their stores, including demographic information, local competition, foot traffic, customer preferences, and more. The goal is to maximise the potential of each store location based on the specific characteristics of that location. Companies may also use optimisation techniques to identify potential locations for new stores or to evaluate existing stores for potential relocation. By optimising their retail store locations, companies are able to maximise their return on investment, improve customer service, and increase their overall sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*HS5euu5Jthr79YJ4" /><figcaption>Figure 11: Store location optimisation (<a href="https://www.ezrankings.com/blog/optimize-multi-location-online-store/">source</a>)</figcaption></figure><p>Spatial nearest neighbours can be used to identify the best locations for a retail store based on the proximity of potential customers. This can help businesses maximise their profits by ensuring that they are located in areas where there is a large customer base.</p><p>One can leverage Mosaic implementation of Spatial KNN in the following way:</p><pre>1) Set landmarks dataset to H3 cells representing the location<br>of a potential store (postcode shape could be another alternative, <br>depending on the size of the postcode area may be skewing results).<br><br>2) Set candidates dataset to customers locations.<br><br>3) Run mosaic KNN with K set to appropriate value (eg. 1000s).<br><br>4)Extract statistics for each potential location by grouping by <br>all matches.<br><br>5) Retrieve results and filter as per business criterias.<br><br>6) Set landmarks dataset to retrieved results - we will run 2 <br>instances of KNN for this use case.<br><br>7) Set candidates dataset to already existing stores.<br><br>8) Run mosaic KNN with K set to appropriate value (eg. 5/10/50).<br><br>9) Define catchment areas (eg. use Mosaic tessellation approach, <br>read more).<br><br>10) Identify stores that overlap the least catchment areas with <br>the same brand stores and maximise overalls with competition <br>(eg. use Mosaic tessellated joins to scale with 1000s/10.000s of <br>stores, read more).</pre><p>This approach can scale over very large areas and demonstrates how easy it is to link the spatial KNN stages. One can think of Spatial KNN as a linking step in a pipeline and it can be used to easily chain otherwise disjoint spatial data assets.</p><p>4. <a href="https://www.feasibility.pro/site-analysis-for-real-estate-developments/">Real Estate Analysis</a>: Real Estate Analysis is the process of examining real estate data to identify trends, patterns, and opportunities in the market. This data can include historical sales prices, local economic indicators such as unemployment rates, population trends, and rental rates. By analysing this data, investors and real estate professionals can gain insights into market trends and make better informed decisions about when to buy and sell. The analysis can also be used to identify areas that may have potential for future price appreciation or which have a higher potential for investment. Additionally, Real Estate Analysis can be used to identify potential risks, such as areas that may be overvalued or in decline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JP4q7W6_SSzjpl4g" /><figcaption>Figure 12: Real estate site analysis (<a href="https://www.feasibility.pro/site-analysis-for-real-estate-developments/">source</a>)</figcaption></figure><p>Spatial nearest neighbours can also be used to help with property searches. By using data from surrounding properties, it can help identify properties that may be similar in terms of characteristics such as location and size. This can be useful for buyers who are looking for a specific type of property in a particular area, as it can help narrow down their search and identify properties that may be a good fit by overlaying proximity/distance to other properties, schools, hospitals, transport, etc. All of these factors can have implications when it comes to evaluation of a property and thus important questions to answer within real estate analysis.</p><p>One can implement this use case using Spatial KNN chaining multiple stages of proximity analysis:</p><pre>1) Set landmarks dataset to properties locations/shapes.<br><br>2) Set candidates dataset to school locations/shapes.<br><br>3) Run mosaic KNN with K set to appropriate value (eg. 5).<br><br>4) Extract statistics for each potential property by grouping <br>by all matches.<br><br>5) Retrieve results and filter as per provided criteria.<br><br>6) Set landmarks dataset to retrieved results - we will run <br>multiple instances of KNN for this use case.<br><br>7) Set candidates dataset to hospitals.<br><br>8) Run mosaic KNN with K set to appropriate value (eg. 3).<br><br>9) Retrieve results and filter as per provided criteria.<br><br>10) Set landmarks dataset to retrieved results - we will run <br>multiple instances of KNN for this use case.<br><br>11) Continue linking data assets while available.<br><br>12) Retrieve results.</pre><p>5. <a href="https://desktop.arcgis.com/en/analytics/case-studies/analyzing-crashes-1-overview.htm">Traffic Analysis</a>: Traffic analysis is the process of collecting and analysing data about the movement of vehicles on a road network. This data can be used to assess the performance of a road network, identify areas of congestion, identify traffic patterns, and plan for future improvements. Traffic analysis typically involves measuring and analysing the volume and speed of traffic, the number of vehicles and their types, the number of vehicles turning at intersections, and the duration of trips. Traffic analysis can also include analysis of pedestrian and bicycle traffic. This data can be collected through manual observation or via technology such as sensors, video cameras, and radars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bABKvT39-0u58ZSH" /><figcaption>Figure 13: Routes associated with taxi rides in New York City</figcaption></figure><p>Spatial analysis is an analytical approach used to understand and analyse the spatial relationships between objects and locations. In the context of traffic, spatial analysis — spatial nearest neighbours to be specific — can be used to understand the spatial relationships between roads, intersections, and other elements of a road network. It can also be used to analyse the patterns of traffic flow, the distribution of traffic volume, and the relationship between traffic conditions and geographic features. Spatial analysis can provide insights into how traffic patterns can be improved, what factors are influencing traffic flow, and how to better plan for future traffic.</p><p>One interesting application of Spatial KNN could be to identify roads closest to highest number of incidents:</p><pre>1) Set landmarks dataset to road shapes. Setting a centroid <br>is not advisable for road analysis, due to the way line <br>features behave with respect to distance functions.<br><br>2) Set candidates dataset to incident locations. These are <br>not required to intersect the road features, meaning that we <br>can avoid unnecessary point to linear feature snapping logic <br>that can be very costly.<br><br>3) Run mosaic KNN with K set to appropriate value (eg. 50/100).<br><br>4) Extract statistics for each road.<br><br>5) Retrieve results and display highest risk roads.</pre><p>Spatial nearest neighbours works by grouping similar points together based on their spatial location. For example, it can be used to identify areas with the highest levels of traffic congestion, or areas that will likely experience an influx of traffic in the near future. Additionally, it can be used to identify the most efficient routes through a city or region, helping to alleviate overall traffic congestion. Spatial KNN can be used to identify potential hazards on the road. By analysing the spatial relationships between points of interest, the algorithm can detect areas where collisions are more likely to occur, such as intersections with high levels of traffic. By identifying these areas, policymakers can take steps to reduce the risk of accidents and improve overall safety.</p><p>For full documentation please visit: <a href="https://databrickslabs.github.io/mosaic/models/spatial-knn.html">https://databrickslabs.github.io/mosaic/models/spatial-knn.html</a></p><p>For other geospatial examples please visit: <a href="https://github.com/databrickslabs/mosaic/tree/main/notebooks/examples">https://github.com/databrickslabs/mosaic/tree/main/notebooks/examples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=336ce37edbae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Native Support for British National Grid with Mosaic on Databricks — The Performance Catalyst]]></title>
            <link>https://medium.com/@milos.colic/native-support-for-british-national-grid-with-mosaic-on-databricks-the-performance-catalyst-50ce3e4de870?source=rss-16747f5bb100------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ce3e4de870</guid>
            <category><![CDATA[public-sector]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[geospatial-analytics]]></category>
            <category><![CDATA[gis]]></category>
            <dc:creator><![CDATA[Milos Colic]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 14:53:33 GMT</pubDate>
            <atom:updated>2022-10-26T09:08:37.769Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Native Support for British National Grid with Mosaic on Databricks — The Performance Catalyst</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqpnRubLhHQpaRo4D2zcoA.png" /></figure><h4><strong>British National Grid — BNG shaped keys to the kingdom</strong></h4><p>With the version 0.3.2 update to <a href="https://github.com/databrickslabs/mosaic">Mosaic</a> framework we have introduced <a href="https://en.wikipedia.org/wiki/Ordnance_Survey_National_Grid">British National Grid (BNG)</a> as a first class citizen. We continue to work on making geospatial data processing more scalable and simpler. And in this particular case our focus was on the UK Public Sector and UK based organisations that consume geospatial data from Public Sector data providers like Ordnance Survey, DEFRA, Met Office, and others.</p><p>BNG is a geospatial indexing system that overlays a grid of squares across all of Great Britain. Each square is subdivided into 4 smaller ones, with each sub-square being continually divided. This provides a set of squares that cover GB ranging from 1000km2 down to 1m2. BNG is a central concept for bringing the geospatial data together in the context of the UK Public Sector. Many departments are using geospatial data at the centre of their data analytics, insights production and statistical work; but there is a lack of standardisation in tooling across teams, and many organisations are struggling to scale their workloads to the Big Data world of today. With the addition of BNG support, Mosaic now provides an easy to use, scalable, and open source toolkit for working with British geospatial data. This allows geospatial experts to work on big data problems that were previously intractable by providing standard transformations in <a href="https://spark.apache.org/">Apache Spark</a> on <a href="https://www.databricks.com/">Databricks</a>, without requiring prior expertise in Big Data processing.</p><p>National data strategy (<a href="https://www.gov.uk/government/publications/uk-national-data-strategy/national-data-strategy">NDS</a>) clearly outlines the need for driving the better quality of data, more standardisation and interoperability of the data to drive economic growth and to enable public good outcomes. These concepts all come into play when one is required to establish a standard way to store geospatial data that simultaneously ensures best performance and interoperability both internally and externally.</p><p>By using BNG one can make sure that they are standardising to the representation many UK Public Sector organisations have adopted. This means you can preempt many challenges that naturally arise with geospatial data processing at scale. Integration and combination with external data sources will be much simpler, since both the external data and your internal data will adhere to the same indexing standard. This is paving the way towards a geospatial data marketplace within the UK Government.</p><h4><strong>A hard byte to chew on</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*SsBjxsHwkDsRRBpo" /><figcaption>Source: <a href="https://www.tablespoon.com/recipes/earth-cake-with-rock-candy-core/14cd99a8-3759-4484-bccf-c1efb6b8e48d">https://www.tablespoon.com/recipes/earth-cake-with-rock-candy-core/</a></figcaption></figure><p>There are many layers — when it comes to geospatial data one can expect many joins and joins tend to bring the most time consumption in large scale computing.</p><p>Some slices are larger than others — most of the data sources have hotspots, i.e. data is clustered around specific areas. This makes partitioning hard, parts of the distributed joins will run much slower than other parts — known as the join skew.</p><p>Some bites have more custard — different rows in the data can represent very different things. In the vector sources complex shapes tend to be very diverse: in the same data source one row can describe a river (a LineString with a few dozens of vertices) and a lake with a few small islands (a Polygon with multiple holes that is represented by hundreds of vertices).</p><p>Some layers don’t stick together — Combining vector and raster data isn’t an obvious task due to different storage formats and different indexing patterns.</p><p>The approach that addresses all of the above problems is centred around grid index systems such as <a href="https://h3geo.org/">H3</a>, <a href="https://s2geometry.io/">S2</a>, <a href="https://en.wikipedia.org/wiki/Geohash">geohash</a> and, of course, <a href="https://medium.com/r?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FOrdnance_Survey_National_Grid">British National Grid (BNG)</a>. The Mosaic framework was originally inspired by a joint project from Ordnance Survey, Microsoft and Databricks (<a href="https://www.databricks.com/blog/2021/10/11/efficient-point-in-polygon-joins-via-pyspark-and-bng-geospatial-indexing.html">link</a>) and it continues to be inspired by examples such as the great work of Thasos (<a href="https://www.databricks.com/blog/2022/10/12/how-thasos-optimized-and-scaled-geospatial-workloads-mosaic-databricks.html">link</a>) who are processing petabyte scale of geospatial data using Mosaic on Databricks.</p><h4><strong>Why Local Grid</strong></h4><p>Up until now Mosaic was supporting the H3 grid index system as a universal indexing system. H3 as a grid system brings a lot of value to the the framework:</p><ul><li>Databricks has native implementation for many H3 expressions in <a href="https://www.databricks.com/product/photon">Photon</a> that brings unrivalled performance for grid indexing capabilities.</li><li>Mosaic uses these capabilities on enabled workspaces in Databricks.</li><li>H3 forms an envelope around the globe, i.e. we can use it for any locality.</li><li>H3 is hierarchical systems, which means we can index our data at different resolutions. This helps us address data skew differently in different circumstances.</li><li>There are many 3rd party solutions (e.g. <a href="https://carto.com/blog/databricks-h3-big-data/">Carto</a>, <a href="https://www.safe.com/integrate/h3/">Safe Software</a>, etc.) that have already adopted H3 as an indexing system and centering around H3 makes integrations much easier.</li></ul><p>However, there can be disadvantages to consider when working in a local context. Global grid index systems such as H3 are focused towards a global grid which can introduce unnecessary complications to generating non-global geospatial data products. Organisations like Ordnance Survey have been producing geospatial and cartographical data for centuries now with a clear focus towards national geospatial data needs. The disadvantage is that the data needs to be provided in <a href="https://epsg.io/4326">EPSG:4326</a> coordinate reference system. If we take Great Britain, most of the geospatial data will be provided in <a href="https://epsg.io/27700">EPSG:27700 (OSGB36)</a> coordinate reference system. So in order to use H3 we would need to perform coordinate reference system conversions that are costly and can introduce computational errors into the data.</p><p>Another very important consideration is that of catering for already existing data consumers and the delivery of data in the expected formats. Using a global index system would introduce changes into the data supply chain that other than standardising to another system brings little to no value. Taking all of these things into account, the natural choice is to keep BNG as the indexing standard and focus on delivering a stable and performant implementation of BNG.</p><h4><strong>British National Grid &amp; Mosaic</strong></h4><p>We have implemented BNG natively as a part of Mosaic offering. This means that all of the Databricks users in the UK can easily access BNG implementation that is robust and scalable. This applies to organisations both in the Public and Private sector enabling a much wider adoption for the standard and easier integration of both open and commercial data assets.</p><p>Mosaic brings all the necessary abstractions needed to use BNG on spark with little to no additional effort to the end users while introducing several optimisation at the same time. Mosaic implements BNG natively within Apache Spark by extending the Catalyst Expressions. This means no user defined functions are needed (UDFs). One can use these expressions in python, SQL, R and Scala which provides unification of the geospatial tooling across different user groups that may have preference towards certain programming languages.</p><figure><img alt="British National Grid (BNG)" src="https://cdn-images-1.medium.com/max/500/0*L87tOURFWwZibxDp" /><figcaption>British National Grid (BNG)</figcaption></figure><figure><img alt="Irish Grid Reference" src="https://cdn-images-1.medium.com/max/440/0*znPuIbbkBmjHciH_" /><figcaption>Irish Grid Reference (IGR)</figcaption></figure><p>The availability of BNG is paving the way to implement other coordinate reference systems based on planar concepts similar to northings and eastings. The next planned extensions to the supported grid index systems will include Irish Grid Reference (<a href="https://en.wikipedia.org/wiki/Irish_grid_reference_system">IGR</a>) to ensure complete United Kingdom coverage.</p><p>Mosaic is introducing some optimisations to the way BNG can be used. The traditional way of using BNG is referencing string typed cell IDs — TQ2323 resolutions in base 10 metres and TQ2323SW for resolutions in base 5 metres. Mosaic brings a way to encode these strings as long type identifiers. Long type identifiers are more optimal for operations like joins and <a href="https://docs.delta.io/2.0.0/optimizations-oss.html#z-ordering-multi-dimensional-clustering">ZORDER</a> of your geospatial delta tables to ensure best performance.</p><p>While Mosaic implements the opinionated long based approach, the traditional approach of encoding BNG cell IDs as strings is supported natively. One can easily switch between the two approaches by a configuration on the Mosaic execution context.</p><p>Finally, Mosaic supports easy plotting of BNG cells in <a href="https://kepler.gl/">KeplerGL</a> using mosaic plotting magics in Databricks notebooks. This brings an interactive development experience to the end user.</p><p>For a full set of capabilities please visit our documentation page (<a href="https://databrickslabs.github.io/mosaic/usage/grid-indexes-bng.html">link</a>).</p><p><a href="https://databrickslabs.github.io/mosaic/usage/grid-indexes-bng.html">BNG - British National Grid - Mosaic</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XJxVHnXdro5adILh" /><figcaption>Tessellated geometry using BNG on Mosaic</figcaption></figure><p>We provide a full walkthrough notebooks (<a href="https://github.com/databrickslabs/mosaic/blob/main/notebooks/examples/python/BritishNationalGrid.py">link</a>) that demonstrate how to configure Mosaic for BNG and how to perform your first optimised massive scale geospatial joins based on BNG.</p><p>Special thanks to:</p><p><a href="https://github.com/steve-kingston">Steven Kingston (Ordnance Survey)</a> for inspiration for long type encoding and constructive feedback during the implementation</p><p><a href="https://www.linkedin.com/in/lindacmg/">Dr Linda Sheard (Microsoft)</a> for being an amazing Mosaic champion</p><p><a href="https://www.linkedin.com/in/edward-fawcett-taylor-a5a675b5/">Ed Fawcett-Taylor</a> and <a href="https://www.linkedin.com/in/lewisdj/">Dan Lewis</a> (DEFRA) for many hours discussing BNG and how it can be applied to both vector and raster data</p><p><a href="https://www.linkedin.com/in/ernidurdevic/">Erni Durdevic</a>, <a href="https://www.linkedin.com/in/robert-whiffin-16b39a65/">Robert Whiffin</a>, <a href="https://www.linkedin.com/in/michaeljohns2/">Michael Johns</a> (Databricks) for all the work they put in helping BNG capability being built and tested</p><h4><strong>For the curious — Space filling in BNG using long cell IDs</strong></h4><p>Space filling curves are a very important concept when it comes to optimising storage of your data for big data use cases. <a href="https://delta.io/">Delta</a> implements this concept as a part of <a href="https://docs.delta.io/2.0.0/optimizations-oss.html#z-ordering-multi-dimensional-clustering">ZORDER</a> operation. ZORDER is defined as a multidimensional clustering that ensures similar data is collocated in the same set of files in the storage location. Given that geospatial data represents spatially correlated rows of data and most of the geospatial queries rely on the vicinity of geospatial features ZORDER-ing a table based on spatial grid index can significantly improve the performance of queries.</p><p>The way BNG is set up naturally brings the idea of space filling. The cell IDs are defined as a zig zag pattern between 2 coordinates. The first letter is computed based on the northings coordinate, the second letter is computed based on the eastings coordinate. The numerical bins follow the same pattern, the first N digits are based on the northings value and the second N digits are based on the eastings value. The number of digits N is determined by the resolution at which we are indexing our data.</p><p>This approach means we are drawing a specific space filling curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*mtijizOogYEq2FX6" /><figcaption>Space filling with base 10 resolutions in BNG</figcaption></figure><p>This concept applies in the case of base 5 metres indexing resolutions as well. In this case we are adding a quadrant encoding as a letter pair (SW, NW, NE, SE). We have added an encoding number in our integer packing to address this need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*roA0tTdWJwKyRPbM" /><figcaption>Space filling with base 5 resolutions in BNG</figcaption></figure><p>Finally putting everything together we get the space filling curve for the long type cell IDs encoding in 1(NL)(EL)(NB)(EL)(Q) format where:</p><ul><li>NL are 2 digits encoding the northings letter</li><li>EL are 2 digits encoding the eastings letter</li><li>NB are N digits encoding the northings bin (N is determined based on the selected resolution)</li><li>EB are N digits encoding the eastings bin</li><li>Q is 1 digit encoding the quadrant</li></ul><p>Using either of the two available encodings for BNG can combine well with ZORDER operation in delta. The long typed encoding is slightly more performant due to more optimised data type and better space filling, while the string typed encoding is more widely used and it is more interoperable. Depending on the application one can convert between the two formats easily using Mosaic functionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ce3e4de870" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>