<?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 Scott Syms on Medium]]></title>
        <description><![CDATA[Stories by Scott Syms on Medium]]></description>
        <link>https://medium.com/@scottsyms?source=rss-2390bfa352d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZqLj1GJzDxOIJsdeJfIWLQ.jpeg</url>
            <title>Stories by Scott Syms on Medium</title>
            <link>https://medium.com/@scottsyms?source=rss-2390bfa352d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:39:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scottsyms/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[Collect: A Rust Tool for Ingesting Streaming Data into Parquet]]></title>
            <link>https://scottsyms.medium.com/collect-a-rust-tool-for-ingesting-streaming-data-into-parquet-73bf2ebf0607?source=rss-2390bfa352d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/73bf2ebf0607</guid>
            <dc:creator><![CDATA[Scott Syms]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 23:11:18 GMT</pubDate>
            <atom:updated>2026-05-21T20:01:51.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1HkjcO6Kn0ye9H93ezjJQ.png" /><figcaption>A crab with a zero and one …. on a parquet floor.</figcaption></figure><p>Collecting data from a socket and saving it somewhere is a common enough pattern and should be simple.</p><p>That’s the motivation behind collect, a small Rust application I built to ingest data from a TCP socket or a file and write it to Hive-partitioned Parquet files, with optional background upload to S3-compatible object storage.</p><h3>The storage question</h3><p>Before writing any code, I spent time thinking about where data should actually land. The obvious answers are a database or a flat file on disk. Databases are powerful, but they introduce schema requirements, running services, and operational overhead that is disproportionate for a simple collection process. A flat file is low-maintenance, but it doesn’t give you a ready to query result.</p><p>Hive-partitioned Parquet turned out to be a reasonable answer to both problems. The storage layout is just a directory tree:</p><pre>data/<br>└── source=norway-tcp/<br>    └── year=2025/<br>        └── month=01/<br>            └── day=15/<br>                └── hour=14/<br>                    └── minute=31/<br>                        └── 20250115_143155_001.parquet</pre><p>This is simple enough that there’s nothing to administer. But because the partition keys are encoded in the directory structure, query engines like DuckDB, Spark, and Polars can read it natively and prune entire branches of the tree based on filter predicates. A query that asks for a specific source and date range doesn’t scan the full archive — it skips directly to the relevant directories. There’s no ETL step, no import, no duplication of data into a secondary system. The files are the queryable store.</p><p>Parquet itself is a columnar format with good compression characteristics. collect uses Zstd, which gives a reasonable balance of compression ratio and speed. The files are readable by virtually every modern data tool without conversion.</p><h3>Why S3?</h3><p>Persisting to a local directory and persisting to S3 are conceptually the same operation — you’re writing structured files to a location. The difference is the availability of the collected data.</p><p>S3-compatible storage is well-suited to parallel reads. HTTP is a known, optimized, well-secured protocol, and S3 implementations are available across a wide range of hosting options: managed cloud services, self-hosted MinIO, or low-cost third-party providers.</p><p>When data lands in S3 as Hive-partitioned Parquet, it can be registered directly in a catalog like Apache Iceberg with minimal effort. That opens the door to the kind of downstream architecture I had in mind when building this: a medallion-style pipeline where the arrival of a new Parquet file in S3 triggers an event, which in turn calls a service that processes and promotes the data to a refined bucket. The collection process stays simple and stateless; the processing logic lives elsewhere.</p><p>collect handles S3 upload asynchronously. Files are written locally first, then queued for background upload without blocking the ingest loop. If an upload fails, the local file is preserved. On shutdown, the application drains the upload queue before exiting. This means a network interruption doesn&#39;t interrupt collection — it just means local files accumulate until connectivity is restored.</p><p>The S3 integration works with AWS, MinIO, Backblaze B2 and any other S3-compatible endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_p53OGjJfsYHJ9MZ14gtYA.png" /><figcaption>Uploaded files in an S3 store</figcaption></figure><h3>The data model</h3><p>One design decision I wanted to preserve was generality. collect doesn&#39;t assume anything about the content of what it&#39;s ingesting. As long as records can be stored as a single text column, the tool will handle them. The source label you assign becomes a partition key, so you can run multiple instances collecting from different feeds and the output stays cleanly separated.</p><p>This makes it suitable for arbitrary line-oriented data: AIS feeds, log streams, sensor telemetry, or anything else that arrives over a TCP socket or from a file. The structure of the records themselves is a concern for the downstream processing layer, not the collector.</p><h3>Rust and the resource question</h3><p>Rust was the right language for this because the requirements map directly to what Rust is good at: low and predictable memory usage, no garbage collection pauses, and efficient async I/O. collect uses Tokio for async processing, which handles the concurrent ingest, file-writing, and upload coordination without threads blocking each other.</p><p>TLS is handled by rustls — a pure Rust implementation with no OpenSSL dependency. For anyone deploying in environments with strict dependency requirements or constrained build toolchains, this simplifies things.</p><p>The processor usage concern I started with turned out to be well addressed. Running against a the Norway public AIS feed, collect sits between 0.1% and 0.5% CPU on my MacBook M1 Max and holds steady at around 3 MB of resident memory. A Rust async runtime doing sequential I/O work is not a demanding process, and those numbers reflect it. It runs comfortably alongside other workloads without competing for resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4ZnDr3bswuznLjNFizVoQ.png" /><figcaption>HTOP showing resource usage. MacOS performance monitoring could be its own article.</figcaption></figure><h3>Configuration and the TUI</h3><p>collect is configured through command-line arguments or environment variables, with CLI arguments taking precedence. This makes it straightforward to deploy in Docker, Helm, or Kubernetes: base configuration lives in environment variables set by the orchestrator, with specific overrides passed as arguments where needed.</p><p>For interactive use, the binary also includes a terminal user interface, launched with collect --tui. The TUI provides a tab-based interface covering input source, output directory, S3 settings, and a configuration management tab where you can save and reload named configurations as JSON files. It&#39;s a practical convenience for local use — it walks through the parameters, validates the configuration before running, and shows the full command line it will execute so there are no surprises. Pre-populating it from environment variables is supported, so a configuration established in one session can be committed to a file and reused in the next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4PjK5s4vc33lfgoe-Bx7g.png" /><figcaption>Some options in the tui.</figcaption></figure><h3>Querying the output</h3><p>Once data is in Hive-partitioned Parquet, querying it is direct. DuckDB, for example, handles the partition tree natively:</p><pre>SELECT * FROM read_parquet(&#39;data/**/*.parquet&#39;, hive_partitioning=true);</pre><p>No schema registration, no running service, no intermediate import. The directory structure is the index. The worked example below shows this against a live public data source.</p><h3>A worked example: live AIS data from Norway</h3><p>A useful source for testing collect is the open AIS feed maintained by the Norwegian Coastal Administration (Kystverket). It streams real vessel position reports over a public TCP endpoint and requires no registration. The data is raw NMEA sentences — exactly the kind of line-oriented, high-volume feed that collect is designed for.</p><p>To try it yourself, start by cloning the repository and building the binary. You’ll need Rust installed; if you don’t have it, the standard installer from <a href="https://rustup.rs/">rustup.rs</a> takes a couple of minutes.</p><pre>git clone https://github.com/ScottSyms/collect.git<br>cd collect<br>cargo build --release</pre><p>The release build applies full optimizations. Once it completes, run collect pointed at the Norwegian feed:</p><pre>./target/release/collect --tcp-host 153.44.253.27 --tcp-port 5631 --out-dir ./data</pre><p>The --source label is optional here; if omitted it defaults to the host address. The program will connect, begin receiving NMEA sentences, and write them into Hive-partitioned Parquet files under ./data. You&#39;ll see output as files are flushed.</p><p>Let it run for a minute or two, then stop it with Ctrl+C. The upload queue drains cleanly on exit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dkZk1OXyF_weI_rszURKw.png" /><figcaption>Collect running and uploading content to an S3 bucket.</figcaption></figure><h3>Querying what you collected</h3><p>With data on disk, DuckDB can query it directly from the command line or its interactive shell. Install DuckDB if you don’t have it — it’s a single binary available at <a href="https://duckdb.org/">duckdb.org</a>.</p><p>To see how many records landed and inspect the raw NMEA content:</p><pre>SELECT count(*) FROM read_parquet(&#39;./data/**/*.parquet&#39;, hive_partitioning=true);</pre><p>To look at actual records and the partition columns alongside them:</p><pre>SELECT * FROM read_parquet(&#39;./data/**/*.parquet&#39;, hive_partitioning=true) LIMIT 20;</pre><p>The partition columns — source, year, month, day, hour, minute — appear automatically alongside the data column. You can filter on any of them without touching the Parquet file internals; DuckDB resolves them from the directory path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDM9LNJNwwNf05mtaTFSxQ.png" /><figcaption>Duckdb listing of synthetic data stored in hive-partitioned parquet.</figcaption></figure><p>From here, the next step would typically be a parsing layer that extracts the structured fields from each NMEA sentence — MMSI, position, heading, speed — and writes the result to a refined Parquet store. That processing step is separate from collection, which is the point: collect does one thing and leaves the data in a form that&#39;s ready for whatever comes next.</p><h3>A note on how it was built</h3><p>collect was developed using AI-assisted coding — working iteratively with a language model rather than writing every line by hand. I’m becoming a huge fan of using AI to quickly test ideas that normally would take much longer.</p><h3>Where this fits &amp; what’s next</h3><p>collect is a focused tool for a focused problem: durably capturing line-oriented streaming data with minimal resource use and maximum compatibility with the broader data ecosystem. It&#39;s suited to edge collection nodes, operational data feeds, research data capture, or any context where you want the data in a form that&#39;s immediately queryable without additional infrastructure.</p><p>My plan is to create a bundle of small single task tools that collect from source types — websocket, message bus- and render the data into the same hive-partitioned parquet format.</p><p>The code is available at <a href="https://github.com/ScottSyms/collect">github.com/ScottSyms/collect</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73bf2ebf0607" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding: Optimising Old Rust Code]]></title>
            <link>https://scottsyms.medium.com/vibe-coding-optimising-old-rust-code-963986a3a6a1?source=rss-2390bfa352d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/963986a3a6a1</guid>
            <category><![CDATA[code-optimization]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Scott Syms]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 13:24:34 GMT</pubDate>
            <atom:updated>2026-03-01T13:24:34.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEnO47gjz62OlxNSZ1xDVw.png" /></figure><p>Recently, I decided to test vibe coding by revisiting a project I originally put together for a Statistics Canada presentation. The project involved building a system to convert a multi-year archive of global ship positional data (AIS) into JSON — the kind of work where the volume and velocity of data are constant enemies.</p><p>I used the <strong>Copilot CLI</strong> and <strong>Anthropic’s Sonnet</strong> models to see if a prompt-led approach could help me — a “fair to middling” programmer — push a functional piece of code into the realm of high performance.</p><p>The task was to take a Rust-based AIS (Automatic Identification System) parser and make it as fast as possible. All timings were performed on a MacBook Air M1 Max processing a file of 9.7 million AIS sentences.</p><h3>Round 1: Breaking the Bottlenecks</h3><blockquote><strong><em>Prompt:</em></strong><em> </em>“Review the code and make changes so that it’s faster. Maximize throughput (lines/second) — all improvements welcome.”</blockquote><p>The AI identified that the multiline message assembly was suffering from high <strong>mutex contention</strong>. Every worker thread was fighting over the same shared HashMaps.</p><ul><li><strong>Structural Change:</strong> Collapsed the multiline assembly into a single dedicated thread with local HashMaps — eliminating all locking overhead.</li><li><strong>Dependency Swap:</strong> Removed the bitvec and regex crates. Replaced them with manual bit-shifting and str::find logic to avoid heap allocations and regex engine overhead.</li><li><strong>The Result:</strong> Processing time dropped by nearly <strong>40%</strong>.</li></ul><h3>Round 2: Aggressive Refactoring</h3><blockquote><strong><em>Prompt:</em></strong><em> </em>“These changes have allowed the test set to be processed in 66% of the time. I’d like you to make more aggressive speed optimisations — change the way files are written, or how status is echoed on the screen. Feel free to make major structural changes or swap libraries.”</blockquote><p>We moved from optimizing individual functions to optimizing the entire data pipeline.</p><ul><li><strong>Mmap I/O:</strong> Switched from BufReader to memmap2. By memory-mapping the input file, we could scan for relevant VDM lines at the byte level before even allocating a String.</li><li><strong>Batched Writing:</strong> Changed the output channel to send batches of 512 lines at once. This reduced channel messaging overhead by <strong>99.8%</strong>.</li><li><strong>Manual JSON:</strong> Dropped serde_json in favor of a manual string-building function. Since the AIS schema is fixed, a hand-rolled serializer avoided the heavy reflection and tree-walking of a general-purpose library.</li><li><strong>The Result:</strong> Down to <strong>15 seconds</strong> (a further 35% speedup).</li></ul><h3>Round 3: Zero-Allocation Mastery</h3><blockquote><strong><em>Prompt:</em></strong><em> </em>“Give it one more round of aggressive optimisations — rewrite whole swaths of the program if necessary.”</blockquote><p>This was the “final boss” of optimizations: moving to a <strong>zero-allocation hot path</strong>.</p><ul><li><strong>Rayon Integration:</strong> Replaced the manual threadpool with rayon. Using par_split, the program now divides the memory-mapped file into chunks and processes them in parallel without a central &quot;manager&quot; thread.</li><li><strong>Stack-Allocated Bit Extraction:</strong> Replaced the remaining Vec in the payload parser with a [u8; 128] stack array.</li><li><strong>Zero-Alloc JSON:</strong> The single-line path (90% of traffic) was rewritten to write numbers and strings directly into the batch buffer. This eliminated roughly <strong>100 million heap allocations</strong> across the 9.7M line dataset.</li><li><strong>The Final Result:</strong> <strong>4.5 seconds</strong>. An <strong>88% improvement</strong> over the baseline.</li></ul><h3>Performance Progression</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iXdzPU5jEoSYXe6qGwYMg.png" /></figure><p>The results were impressive: the code does the same work in 12% of the time. The optimisation was done over an hour with three prompts. There’s real value here for the developer and client.</p><p>There’s a real temptation here to extrapolate about the future role of the programmer, but the reality is that it’s still early days with AI assisted programming. The technology and the practice are still in flux.</p><p>My early take is that technical skill is still valuable- AI can still go off the rails when coding, but the programmer’s ability to understand the unique challenges presented by the client’s world may now be more vital whether the client is a warfighter, an industrial engineer or retail worker.</p><p>After all, someone has to prompt AI.</p><p>Code can be found at: <a href="https://github.com/ScottSyms/RustAISe">https://github.com/ScottSyms/RustAISe</a></p><p>Original article for the project can be found here: <a href="https://medium.com/p/f61ccb0b2f7f">https://medium.com/p/f61ccb0b2f7f</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963986a3a6a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering in Rust: Processing 50 Billion AIS Messages on a Laptop]]></title>
            <link>https://scottsyms.medium.com/data-engineering-in-rust-processing-50-billion-ais-messages-on-a-laptop-f61ccb0b2f7f?source=rss-2390bfa352d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61ccb0b2f7f</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[maritime]]></category>
            <dc:creator><![CDATA[Scott Syms]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 11:43:11 GMT</pubDate>
            <atom:updated>2026-03-01T11:43:11.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRHKSrkAS5HAiAk0MjlhxQ.jpeg" /></figure><p><strong>By: Scott Syms, Shared Services Canada</strong></p><p><em>This is a cleaned up repost of a paper I did for StatCan’s Data Science Network that is no longer available on their website. At the time, I was fascinated with what Rust could offer high volume/velocity data and was posting my work at different forums.</em></p><h3>Abstract</h3><p>Python is the undisputed king of data science, but when processing speed and hardware constraints become the primary bottlenecks, we need a different toolkit. In this article, I explore how to build a high-performance data conversion application in <strong>Rust</strong>. By leveraging Rust’s “fearless concurrency,” we can process a multi-year archive of global ship positional data on modest hardware — outperforming traditional Python approaches while maintaining memory safety.</p><h3>Introduction: The Python Paradox</h3><p>The Python ecosystem is invaluable. Tools like Jupyter Notebooks have become so ubiquitous that some suggest they replace the traditional scientific paper. However, Python’s strengths — dynamic typing and the Global Interpreter Lock (GIL) — become liabilities when processing massive datasets.</p><p>To scale Python, developers typically choose one of two paths:</p><ol><li><strong>Computational Accelerators:</strong> Using Numba or PyPy to boost single-machine speed.</li><li><strong>Distributed Computing:</strong> Using Dask or PySpark to spread the load across a cluster.</li></ol><p>But what if you don’t have a massive cloud environment? For AI at the edge or researchers with modest resources, efficiency must happen <em>in-place</em>. In 2020, <em>Nature</em> suggested a third path: writing scientific software in <strong>Rust</strong>.</p><p>Rust offers the performance of C++ with built-in memory safety. It compiles to native code or WebAssembly, making it an ideal candidate for heavy-duty data engineering.</p><h3>The Challenge: Automatic Identification System (AIS) Data</h3><p>Ocean-going vessels transmit voyage data via AIS. This data is collected by satellites and ground stations to build a global picture of maritime activity. The Canadian Space Agency (CSA) alone has collected over <strong>50 billion messages</strong> over the last decade.</p><p>AIS data is transmitted in the NMEA standard. A raw sample looks like this:</p><pre>1569890647\s:VENDOR,q:u,c:1569890555*5F!AIVDM,1,1,,A,13KG9?10031jQUNRI72jM5?40&gt;@&lt;,0*5C</pre><p>While some metadata is human-readable, the critical ship identity and movement data is packed into a <strong>six-bit ASCII payload</strong>. Decoding this requires bit-level manipulation — a task where Rust excels.</p><h3>Architecture: Fearless Concurrency</h3><p>The goal of our application, <strong>RustAISe</strong>, is to convert raw AIS archives into JSON for use in DataFrames or read-optimized formats like Apache Parquet.</p><p>To maximize throughput, we divide the workload into three concurrent pools:</p><ul><li><strong>The Reader:</strong> A single thread that ingests the source file.</li><li><strong>The Extraction Pool:</strong> A multi-threaded pool that parses single-line messages.</li><li><strong>The Multiline Pool:</strong> A pool that caches and reassembles fragmented messages.</li></ul><p>Because Rust enforces strict ownership, we can pass data between these threads via <strong>channels</strong> without risking data races.</p><h3>Implementation Highlights</h3><h3>Modern Dependency Management</h3><p>Rust’s build tool, Cargo, allows for strict version pinning, ensuring our data pipeline doesn&#39;t break when a library updates.</p><pre>[dependencies]<br>crossbeam-channel = &quot;0.5.2&quot;<br>serde = { version = &quot;1.0.136&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0.78&quot;<br>bitvec = &quot;1.0.0&quot;</pre><h3>The Power of Variable Scoping</h3><p>Rust’s memory safety is enforced through “Lifetimes.” While it can be strict, it allows us to write code where memory is reclaimed the moment it is no longer needed, without a garbage collector.</p><pre>let x: i8 = {<br>    if y == 1 { 67 } else { 0 }<br>}; // The result of the block is assigned to x</pre><h3>Shared State with Arc &amp; Mutex</h3><p>For multiline messages, we must share a cache across threads. We use an Arc (Atomic Reference Counter) and a Mutex to ensure only one thread modifies a specific fragment at a time.</p><pre>let payload_cache: Arc&lt;Mutex&lt;HashMap&lt;String, String&gt;&gt;&gt; = <br>    Arc::new(Mutex::new(HashMap::new()));</pre><h3>Results: Blazingly Fast</h3><p>I tested the application on a MacBook Pro (2.3 GHz 8-Core Intel i9). The results were staggering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*GjzG-ICf_A97TlA_i3ZFjA.png" /></figure><p>At this rate, a single laptop could process a <strong>50-billion-row archive in roughly 36 hours</strong>.</p><h3>Lessons Learned</h3><p>As a first-time Rust developer, the “juice is definitely worth the squeeze.” While the compiler is strict — often described as a “chatty” or “iron-fisted” assistant — it prevents the segfaults and memory leaks common in C++.</p><p><strong>My takeaways for fellow Data Engineers:</strong></p><ul><li><strong>Work with the compiler:</strong> Its error messages are actually helpful tutorials.</li><li><strong>Idiomatic Rust:</strong> My next step is refactoring to use custom Traits and better error handling.</li><li><strong>Hybrid Approaches:</strong> If you aren’t ready to leave Python, look into <strong>PyO3</strong> to write Rust extensions for your Python code.</li></ul><h3>Getting the Code</h3><p>The full project, including a sample dataset from the Government of Norway, is available on GitHub:</p><p>👉 <a href="https://github.com/ScottSyms/RustAISe"><strong>https://github.com/ScottSyms/RustAISe</strong></a></p><p><em>The views expressed in this article are those of the author and do not necessarily reflect the official policy or position of Shared Services Canada.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61ccb0b2f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic Identification System and Parquet]]></title>
            <link>https://medium.com/data-science/automatic-identification-system-and-parquet-365160852b3?source=rss-2390bfa352d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/365160852b3</guid>
            <category><![CDATA[making-sense-of-big-data]]></category>
            <dc:creator><![CDATA[Scott Syms]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 01:28:41 GMT</pubDate>
            <atom:updated>2021-02-15T17:14:19.824Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/making-sense-of-big-data">Making Sense of Big Data</a></h4><h4>If you store minimally parsed ship positional data in Parquet files, it’s faster and easier to query large volumes of data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cumZwHi-1HLT2NZQ5Bwqhw.jpeg" /><figcaption>Public domain image via Wikipedia</figcaption></figure><p>Just over a hundred years ago, <a href="https://en.wikipedia.org/wiki/Halifax_Explosion">two ships collided in Halifax Harbour </a>in Nova Scotia, Canada. The Mont Blanc was weighted down with explosives destined for the war in Europe, and when she collided with the Imo, the cargo ignited. It was the largest man-made explosion before the advent of nuclear weapons, flattening part of the city and killing more that 1,700 people in wartime Halifax.</p><p>Collisions are rarely this dramatic, but even <a href="https://en.wikipedia.org/wiki/USS_John_S._McCain_and_Alnic_MC_collision">as recently as 2017</a>, lives were lost to these accidents.</p><p>The <em>Automatic Identification System</em> was designed to prevent this. Ships outfitted with AIS transponders broadcast their position, course and identity as they move along the water.</p><p>Designed to be an aid to RADAR, these low power broadcasts are picked up by neighbouring vessels, shore receivers and even low altitude satellites. Collecting AIS data from a worldwide network of terrestrial and space sensors can provide a global picture of ship traffic.</p><p>The data has been used to gauge the impacts of ice-free summers on ship traffic in Canada&#39;s northern archipelago, estimate the noise impact of ships on whale habitats, and plan the development of rail and road services to port communities.</p><p>With this in mind, my goal is to structure AIS storage so that extracts on time, position, identity and destination can be created easily, but to do this, I need to pull some essential information from AIS’s cryptic encoding scheme.</p><p><strong>The Data</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15c602bd98cdd83b942bad958e8bcdd0/href">https://medium.com/media/15c602bd98cdd83b942bad958e8bcdd0/href</a></iframe><p>The data that streams out of an AIS receiver is only vaguely readable. AIS transmitters use a vocabulary of 27 messages. There’s more than ship movements being broadcast- AIS message can also transmit information on weather, crew, search and rescue activities and navigation hazards.</p><p>I use Eric Raymond’s <a href="https://gpsd.gitlab.io/gpsd/AIVDM.html#_introduction">AIVDM/AIVDO protocol decoding</a> guide to navigate the AIS sentence structure. Since I’m working with data that has already been stored in compressed files, my first step is to load each file into pandas and split each line on the exclamation mark into two columns- the <em>prefix</em> and <em>suffix</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f305a5d9ffc498b83e0d00b2732eb67/href">https://medium.com/media/4f305a5d9ffc498b83e0d00b2732eb67/href</a></iframe><p>The prefix contains metadata about the message in a series of <em>tagged blocks. </em>Regular expressions can extract these interesting bits. Satellite sourced AIS can be buffered in orbit, and some vendors provide both the time the sensor picked up the broadcast (<em>report_time</em>) and the time the data was received by the ground station (<em>received_time</em>). The download time is not found on every sentence, so this data is parsed when it exists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beb95efab8454400e441bae0fb1d0d7c/href">https://medium.com/media/beb95efab8454400e441bae0fb1d0d7c/href</a></iframe><p>Regular expressions can also be used to isolate values from the suffix- is the message split over more than one sentence? If so, is this the first or second sentence? What’s the fragment id that ties the two sentences together. Does the payload require padding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d6c118058413c5e4f023ce32e3521f2/href">https://medium.com/media/1d6c118058413c5e4f023ce32e3521f2/href</a></iframe><p>The most important part of the AIS message is found in the string of random-looking characters that makes up most of the second half of the message.</p><p>The AIS payload is encoded in six-bit ASCII. To make it readable, we have to convert this part of the message to binary, pull out the requisite bits of data and cast the data into the proper type- string, float, signed or unsigned int.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45964288eab7c3c2db0a4915bc1744ec/href">https://medium.com/media/45964288eab7c3c2db0a4915bc1744ec/href</a></iframe><p>The last step in constructing the payload involves appending the second fragment to the first for multipart sentences. I enlist a pandas “outer” merge for this job.</p><p>Now we have a string of 1’s and 0’s that we can carve up to find the ship’s identity and position.</p><p><strong>Carving up bits</strong></p><p>The first step is to tag each line with the sentence’s message type by pulling the first six bits of the message into an unsigned integer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa9f0c7b6855b063e7d2f9abd2080d31/href">https://medium.com/media/aa9f0c7b6855b063e7d2f9abd2080d31/href</a></iframe><p>With the message type, we can start extracting ships’ positions. Messages 1, 2, 3, 4 and 18 have latitude and longitude.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a8e5989fb378b68625466e95a8042f3/href">https://medium.com/media/5a8e5989fb378b68625466e95a8042f3/href</a></iframe><p>Each ship with an AIS transmitter is identified with a <em>Maritime Mobile Service Identity</em> (MMSI) carried in bits 8 to 37 of the payload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c118da9c8c1f4e7d6ffe7f144e38d35f/href">https://medium.com/media/c118da9c8c1f4e7d6ffe7f144e38d35f/href</a></iframe><p>Message type 5 holds the ships’ destination, if declared.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daca4debcad0e71765aee145ef2a46eb/href">https://medium.com/media/daca4debcad0e71765aee145ef2a46eb/href</a></iframe><p>Using the examples above and the detailed specifications from Raymond’s AIS guide, it’s straightforward to parse other attributes from payload. At this point, I have enough elements to meet my goal of creating extracts on time, position, identity and destination.</p><p><strong>How to store the data?</strong></p><p>I mostly see AIS data stored in CSV formats- I get it, CSV is ubiquitous, it’s understood by most tools, but data reads are slow. Since this archive will only be read, it’s ideal to store the data in a column store format like <a href="https://parquet.apache.org/">Apache Parquet</a>.</p><p>There’s lots of information on Parquet on the intertubes, so I won’t go into it here. I’d rather get a look at how this format compares as a reading format to CSV.</p><p>Writing our dataframe to Parquet is straightforward. To help with time based searches, I partition the table on year, month, day and hour.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a60bda1ada99b1a695730526d36da602/href">https://medium.com/media/a60bda1ada99b1a695730526d36da602/href</a></iframe><p>To test the impact of Parquet on search performance, I created a large repository of AIS data in both snappy compressed Parquet and uncompressed CSV formats, and ran some queries using <a href="https://drill.apache.org/">Apache Drill</a>. For each timing, I record the time value of the second run to give optimiser a chance to cache metadata.</p><p>A row count of around 334 million reports took 90 seconds to execute with CVS stored data. With Parquet, the count took 0.121 seconds. A group by and sorting query to find the top 100 referenced destinations took 87 seconds for CVS, 4.5 seconds for Parquet.</p><p>A frequency count of all unique MMSIs executed on CSV stored data in 89 seconds- with Parquet it took 19.1 seconds. And finally, a search for an individual MMSI took 82 seconds for CSV storage and 6.2 seconds for data</p><p>Code can be found <a href="https://github.com/ScottSyms/AISArchive">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=365160852b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/automatic-identification-system-and-parquet-365160852b3">Automatic Identification System and Parquet</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamically displaying millions of points on a web map with Python]]></title>
            <link>https://medium.com/data-science/dynamically-displaying-millions-of-points-on-a-web-map-with-python-ae2b39b2ebf?source=rss-2390bfa352d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2b39b2ebf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[editors-pick]]></category>
            <dc:creator><![CDATA[Scott Syms]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 00:35:58 GMT</pubDate>
            <atom:updated>2021-01-24T16:33:28.621Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generating tiled maps on the fly can save storage and time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKoLqCLcgDbg2oq47vCyrw.png" /><figcaption>25 million ships in American waters. Image by author.</figcaption></figure><p>Last year, <a href="http://tom-e-white.com/datavision/09-inaturalist-observations.html">Tom White demonstrated a web map drawn from millions of geo-coded wildlife observations</a>. The map behaves just as you’d expect, with each zoom level revealing the data in greater detail.</p><p>The digital magic in White’s solution is <a href="https://datashader.org/">Datashader</a>, an open-source library that creates imagery from millions of data points quickly. With Datashader, data can be pre-rendered at different zoom levels and locations, and served up by any web server. Add the proper client software and a browser, and you have a <em>tiled web map</em> or <em>slippy map</em>.</p><p>Slippy maps divide the earth up into tiles that reflect various levels. At zoom level 0, the world is presented as a single 256 by 256 pixel image. At zoom level 1, the earth is represented by four 256 square pixel tiles. Every zoom level calls up more granular tiles with additional detail. When rendered smoothly, the effect is like falling from stratospheric heights to street level.</p><p>By the time you get to zoom level 10 you’ve subdivided the earth into more than a million squares. At zoom level 15, you’re panning across a billion tiles, and a trillion tiles at zoom level 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWsSU7Lu4pVLi_AYZvGCXg.png" /><figcaption>Rome at zoom level 16 with St. Peter’s Square at the upper left and the Colosseum on the bottom right. Image from ArcGIS online tile imager.</figcaption></figure><p>Creating the tiles to feed a slippy masp is a computational challenge. If it takes 1ms to write a 300 byte tile on a single machine, you’ve created a gigabyte of data in half an hour. By zoom level 20, you’re three years in and shopping for terabyte drives.</p><p>But Datashader <em>is</em> fast- I wondered if it would be possible to generate the data on demand? This would drop the need to process and store a huge number of images. It would also allow for the data to be updated frequently- every half hour would give a reasonably accurate snapshot of global ship traffic.</p><p>To test this out, I used data from <a href="https://marinecadastre.gov/">Marine Cadastre</a>, a site operated by the US National Oceanic and Atmospheric Administration (NOAA) which makes public a decade of parsed ship positional data. From here I could get daily summaries of 6 to 8 million positions for vessels sailing in American waters.</p><h3>Preparing the data</h3><p>Each position record in the Marine Cadastre data contains more than just the ship’s current location. For our purposes we just need the latitude and longitude for the vessel, so the first step is to strip away the unnecessary data and convert the data from its native projection to web mercator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/048a81c234b28fe9804eb6c40e7bed3a/href">https://medium.com/media/048a81c234b28fe9804eb6c40e7bed3a/href</a></iframe><p>Retrieving the data is easily done with <em>curl</em> and <em>unzip. </em>GDAL’s <em>ogr2ogr</em> command line tool adjusted the coordinates to web mercator.</p><p>Although I really just wanted two columns reflecting each ship’s latitude and longitude, the <em>ogr2ogr</em> application wouldn’t limit the output to just the location data. An additional <em>awk</em> filter extracted just the columns required for visualisation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fcb5110e880f1c5553f9ae5f6a25283/href">https://medium.com/media/6fcb5110e880f1c5553f9ae5f6a25283/href</a></iframe><p>The result was a comma separated value (CSV) file with the latitude and longitude for each ship position in the required projection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35715b3d529c6c3cc00657bc83167bb3/href">https://medium.com/media/35715b3d529c6c3cc00657bc83167bb3/href</a></iframe><h3>Displaying the data</h3><p>The tile rendering part of the prototype loads positional data prepared in the previous step into a pandas DataFrame. When each web request arrives for a tile, the program converts the tile position into a bounding box of coordinates and uses this to query the DataFrame. The results are rendered with Datashader into a image which is passed back to the web client for display on an appropriate map client.</p><p>FastAPI provides routing of URLs to the rendering functions. At startup, an <em>indexhtml</em> variable is populated with a modified version of White’s original <a href="https://leafletjs.com/">Leaflet</a> application. This page can be used to show the rendered tiles on a base map. After a quick check to see if the file exists, the ship data gets loaded into a <a href="https://arrow.apache.org/docs/python/">PyArrow</a> object and then passed to a pandas DataFrame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830643d1760341f6ea19c3a6079f36a1/href">https://medium.com/media/830643d1760341f6ea19c3a6079f36a1/href</a></iframe><p>Two HTTP endpoints handle the static HTML and JavaScript needed by the web interface. Requests to the root of the web structure receive the contents of the indexhtml variable, while <em>app.mount</em> ensures that the clients get the page stylesheet, graphics and Javascript needed to present the web map.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca230417a6b81941293d980577ff80dc/href">https://medium.com/media/ca230417a6b81941293d980577ff80dc/href</a></iframe><p>A handler for the slippy map isolates the essential variables from tile requests: <em>zoom</em>, <em>x</em> and <em>y</em> get forwarded off to a tile generator with the results tagged as PNG files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6d818bb98b6f99e1c8554266a655966/href">https://medium.com/media/b6d818bb98b6f99e1c8554266a655966/href</a></iframe><p>The top-left and bottom-right co-ordinates are obtained for each tile by passing the x and y variables pulled from the request path to a translation function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dba0f2f4464594017960eeec3127074/href">https://medium.com/media/8dba0f2f4464594017960eeec3127074/href</a></iframe><p>Code borrowed from the OpenStreetmap wiki converts the tile path into a longitude and latitude. An added call to a Datashader helper function puts the tile co-ordinates into the web mercator’s metre-based format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a17c0f43cab2ec9db394148de42a10a5/href">https://medium.com/media/a17c0f43cab2ec9db394148de42a10a5/href</a></iframe><p>With the tile bounding box defined, the code carves out the location data from original parent DataFrame into a smaller dataset .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e44a0864309c759eca03dc650ad7f0c/href">https://medium.com/media/8e44a0864309c759eca03dc650ad7f0c/href</a></iframe><p>The canvas is 256 pixels square and it maps to a bounding box formed by the minimum and maximum extents of latitude and longitude covered by the tile being rendered. Next, the aggregation function processes the query data and the identifies latitude and longitude.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d45f746a3b9921571fbbc193fea5b2ac/href">https://medium.com/media/d45f746a3b9921571fbbc193fea5b2ac/href</a></iframe><p>Finally an image is created from the aggregate, assigned to a <em>bytesio</em> variable and passed back to the calling function to be delivered back to the browser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd05b782247a73a6cf5ce98661af2c9/href">https://medium.com/media/3cd05b782247a73a6cf5ce98661af2c9/href</a></iframe><h3>Final product</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*HulbORGvbAUGdl0MCUA7CA.gif" /><figcaption>Dynamic rendering in action. Image by author.</figcaption></figure><p>If you run the code I’ve placed <a href="https://github.com/ScottSyms/tileshade">on GitHub</a> and surf to <a href="http://localhost:8080,">http://localhost:8080,</a> you’ll see a styled global map. Clicking the icon on he upper right of the map will allow you to select the basemap and enable/disable the data layer.</p><p>The embedded animated gif gives a sense of how quickly the application renders tiles from a source file of 8 million position reports. Each tile renders in 30 to 40 ms, with detailed images requiring slightly more time to create. At high zoom levels, sparse data can be difficult to make out, but since Datashader gives control of the pixel size, it’s possible to create a dynamic algorithm to resize the pixels when zoom levels are high and data counts are low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8JQLvfl5ZHFySmIVY6cFQ.png" /><figcaption>Ship traffic draws tendrils of movement outside of Norfolk, Virginia. Image by author.</figcaption></figure><p>This rendering technique opens up a way to integrate Dataframe oriented analytics with standard web map presentations, Datashader could be replaced with any fast image generating function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2b39b2ebf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dynamically-displaying-millions-of-points-on-a-web-map-with-python-ae2b39b2ebf">Dynamically displaying millions of points on a web map with Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>