Weeknotes: 30th November 2026
Watching the boats (and occasional SAR plane)
I've been down with a cold that has reduced my reasoning ability, so for the last few days I switched to doing something that required low thought process and spent some time implementing AIS monitoring in OCaml as part of a little side project I have slowly bubbling away. I wrote last month about getting a dAISy AIS receiver, which is connected to an aerial on the roof of our house and setting it up with a raspberry Pi using OpenPlotter. This had been running a littlt too well: my plan was to just use OpenPlotter to check things worked, then get on to writing my own stack, but with other work demands I just ended up using OpenPlotter the last month. Fortunately for me, I clicked "update" on one of the components in OpenPlotter, and it totally hosed the stack, meaning I lost my nice little in-house webserver showing all the boat activity on a map, and thus it was time to write my own query code.
Thanks to a conversation with Adrian McEwan who has been doing similar AIS things (and was who inspired me to try this in the first place), I discovered that the dAISy hat hardware does all the RF decoding of the AIS data and spits the raw bits into one or more NMEA packets over the serial line to the raspberry pi. NMEA 0183 is to boats what CAN bus is to cars: it's a protocol designed to carry data from a bunch of independent sensors and let them all stream over one channel, so then interested parties can pick the bits they want. In my case the serial line from the dAISy looks like this:
!AIVDM,1,1,,B,402=aQ1vbw:WiOj00RNW7SOP25BL,0*54
!AIVDM,1,1,,A,13P=eW@000Oi4H`NPf>7bkUV05BL,0*41
!AIVDM,1,1,,B,402=acAuM8:Wmwi3FHNPPTW005BL,0*38
!AIVDM,1,1,,B,13P<<6@P01Oi4pPNP`7h0?w`08PO,0*4C
!AIVDM,1,1,,B,402=aeQuM8:WnwhRw6NPsG?005BL,0*5A
!AIVDM,2,1,1,A,53l3u802BIB4=7;WO>1=@Dhh61@PE8E<6222221@<pG::6uj0?1h`4km,0*20
!AIVDM,2,2,1,A,p88888888888880,2*6D
!AIVDM,1,1,,A,13P><k0000Oi4D2NPejdia;j00S?,0*39
!AIVDM,2,1,2,A,53P=eWD000038Q47B20q<j04AHDqAE8E:222220`1P7435IiD4SClm6C,0*7D
!AIVDM,2,2,2,A,cDQUicCClm6C`80,2*23
!AIVDM,2,1,3,B,53P9NkD00000lm@OH01LTp@<5B3<00000000000`0`:336q:03SClm6C,0*20
!AIVDM,2,2,3,B,cCR;CClm6Cg8880,2*46
!AIVDM,1,1,,A,402=ahQvbw:WsOj56nNUvPW000S:,0*73
!AIVDM,1,1,,A,402=aQ1vbw:WsOj00PNW7SgP20S:,0*05
!AIVDM,1,1,,B,13P=eW@000Oi4H`NPf>7bkT200S9,0*46
This is the NMEA frames, one per line. They all start with the same opening, as they're all AIS messages, but there are different prefix codes for different devices most notably GPS output for heading, location, etc. Until I install an AIS monitor on my motorbike, those are of less interest to me, so for now we're dealing with just the AIVDM messages. Beyond the opening, the rest of the frame is prefix specific, so what follows here pertains to the AIS container frames. The next three numbers (often just two numbers) are the sequence information. Most AIS messages fit into a single NMEA frame, but not all do, as you can see in the middle of that example set. So then we have a sequence length, position in sequence, and then a sequence set identifier (as you might have multiple messages of that type come in, and they might be interleaved so you need to be able to disentangle them. The A and B are the two different VHF frequencies assigned to AIS messages. Then you have the 6 bit armoured payload - which is effectively like base64 encoding for any old-school (or is that just old) nerds out there: it takes a binary string and encodes it as valid ASCII characters that excludes control codes, so you get just 6 bits of raw binary for every text character. Then finally there's the '0*4E' bit, which is 0 padding bits, and a checksum of 0x4E.
Thankfully the NMEA decoding bit I didn't need to write from scratch, as Davide Gessa had already made an OCaml module for decoding a lot of NMEA frames, just not the AIS ones. So after a little recalling how the Menhir parser generator for OCaml worked, I made a patch that allows it to recode the AIS frames. I didn't attempt to add AIS decoding on that patch, mostly because the fact that you need to allow for assembling multiple NMEA frames into a single AIS frame, and the current API for Davide's module is just doing per NMEA frame decoding. I feel when making a PR to someone else's code base for the first time it's best to tread lightly and demonstrate some competency before trying to mess too much with what they've set in place.
Still, with the NMEA in place, I then moved on to decoding the binary formats. This was quite fun to do, as it hit a very satisfying loop where I had raw NMEA messages scrolling by, and as I slowly added support they all gradually revealed their inner meaning to me, with more and more of the scrolling messages being replaced with their decoded counterparts. More of a simple puzzle game than actual tedious task (if your brain is wired like mine at least). It's very much like writing code dis-assemblers, converting raw binaries to the assembler instructions for a given architecture. The only oddity to do this in a language like OCaml is that it lacks bitfield access that you get in the languages I'd normally have done that in (e.g., C). Being under the weather and low on reasoning, I just wrote some naive brute force code to extract the bits on demand as I decode the 6-bit armoured text; crude, but sufficient for something as slow as this.
The actual AIS message format has been well documented on this page by Eric S. Raymond (yes, that Eric S. Raymond), and so I just plodded away through this. Thankfully the first type field is 6 bits long and so matches the number you see in the NMEA frame (so in the above we have a type 4 (base station update), followed by a type 1 message (position update), etc.), which makes working out which messages I needed to cover to get my local messages faster than it otherwise might have been. Eventually after a bunch of work I could convert the above to:
B: 🗼 2320772 - base station update: 53.496982 N 3.058318 W
A: ? 235105693 - position update: 53.322333 N 3.261833 W, Ais.Under_way_using_engine - 0.0 NM, 114˚
B: 🗼 2320813 - base station update: 53.316510 N 3.265367 W
B: ? 235080729 - position update: 53.319732 N 3.260133 W, Ais.Under_way_using_engine - 0.1 NM
B: 🗼 2320822 - base station update: 53.327940 N 3.375835 W
A: 🛢️ STELLA THERESA - related data: STELLA THERESA (Ais.Tanker_all) - GB SOW
A: ? 235113676 - position update: 53.322150 N 3.262078 W, Ais.Under_way_using_engine - 0.0 NM, 293˚
A: 🚤 NSL ADVENTURER - related data: NSL ADVENTURER (Ais.High_speed_craft_all) - MOSTYN-RFWF-MOSTYN
B: 🚤 WINDCAT 3 - related data: WINDCAT 3 (Ais.High_speed_craft_all) - MOSTYN-NH-MOSTYN<
A: 🗼 2320834 - base station update: 53.465817 N 3.040915 W
A: 🗼 2320772 - base station update: 53.496983 N 3.058320 W
B: 🚤 NSL ADVENTURER - position update: 53.322333 N 3.261833 W, Ais.Under_way_using_engine - 0.0 NM, 114˚
I learned a bunch of interesting details whilst implementing this. Firstly, you can see that the second message by 235105693 is actually the NSL ADVENTURER, but the main update package only contains the Mobile Marine Service Identifier (MMSI), and you get a periodic update package (which is one of those longer ones split over two messages) where you get metadata about a given boat like its name and ship type. Base stations never seem to send those, so in my viewer I've had to hard code all the local base station names, and it explains why after a reset OpenPlotter would lose the names for a lot of boats initially: position updates happen a lot more frequently than metadata updates.
The destination fields in the metadata updates are amusingly freeform. Here we can see that the NSL ADEVNTURER and WINDCAT 3 are both going to and from local windfarms (Rhyl Flats and North Hoyle respectively), but you'll often see just "GBLIV" or "LIVERPOOL", or "GBLIV <=> IEDUB". I feel there's definitely a paper analysing all the different ways people have tried to use this field, but perhaps that's the cold talking :)
The big surprise was that I occasionally see coast guard planes with AIS transponders, like this one that was going from Glasgow Prestwick to Newquey at the time when I spotted it over Angelsey. Now, if we look at this viewshed I made a few weeks ago that highlights the limits of where I should be able to reach with my AIS antenna you can see that Angelsey is not included, bu that's because I was thinking of boats that are on the planet's surface, and given the aircraft was over 4065 metres in the air (the range limit for the altitude field in the AIS SAR aircraft data record), then the line of sight required for AIS goes a lot further!
My eventual aim for all this is to put it on an eInk display in the house. We already have a beautiful tide-times poster, and a tidey tide height ambient display, and I want to build a local map that is static other than having the live boats data on it. I already have an Inky eInk display for this:

My plan is to drive this from OCaml using a port of my Claudius graphics library - Anil Madhavapeddy kindly provided me a with a Pi 4 for this purposes, as my Pi 3 is tied up with the dAISy, and the Pi Zero 2 that I was going to use doesn't have enough memory to build OCaml on it alas. Whilst the Claudius port for Inky is a task for another day (hopefully not another illness), I did a first quick pass just using Claudius on my desktop at taking my AIS data, mixing it with one of my 30 day map challenge attempts from earlier in the month, and starting to figure out what I want on the eink display:

The smaller 7.3" display is alas only 800x480 pixels, so I'm somewhat limited in space (when I ordered the display they were out of the larger 13" version, which I'll order if I have success with the 7.3" version), but this is enough to start experimenting with. The text layout obviously needs work, but I like the ability to have trails. The Inky displays have some buttons on them, so I think I'll add the ability to cycle through say the zoomed out view like this, and then zoom in on Liverpool, Mostyn, and the boat park between the two big wind farms.
The final point here, is that whilst people can nosey around my implementation if they know where to look, I've decided that I won't be making a PR to add this to the upstream NMEA as is. AIS data straddles this murky area between nerd data sperlunking and critical safety. I've bashed together something that seems to work, including unit tests, whilst under the weather. I do not want people running this anywhere that might be critical, and unlikely as it sounds that someone would take an obscure OCaml software thing and run it, the fact that cars run on GPL software these days shows that it's not entirely a stretch.
Harking back to the discussion with Anil's commentary on whether software was too complex for humans and my response in last week's notes, I think to have me happy for this code to be say in opam (the standard OCaml package repository) would require a lot more unit testing than the light positive test cases I've added so far, and a bunch of fuzzing (which I'd like to try in OCaml, as I've used it to good effect before in Python/Django). AIS is certainly not too complex for humans, and so it should be a relatively easy bar to hit, but I think it'd be irresponsible of me to push my current implementation out there given the context of the domain and it's possible safety implications.
Habitat map work
Mostly I tried to wrap up the Iceland work, but I found one last interesting point as I tried to focus back on more pertinent areas. Despite my best efforts the validation scores for my Iceland habitat maps have been somewhat poor. After sitting down and looking at occurrences where we were failing validation, it was because of the relatively high abundance of data where we see the observer being distinct from the habitat they are observing. Such as this example at Lónsfjörður:

And Vífilsstaðavatn, a wetland just outside of Garðabær:

In both these cases the GPS accuracy recorded with the data is better than 10m, which looks right given how well the points are located on the respective road/path, but the observations are all for water birds, clearly not at the point the observation is recorded. I discussed last week how I was filtering occurrences based on OSM/HydroLAKES datasets to remove water only species from land, and so these points don't go into my training data, but points like this are still in the validation data, and so correctly mark me down. This doesn't impact the habitat maps I'm comparing with which are at 100m resolution so badly, it's only because my map is at 10m per pixel that it hurts me more.
To allow for this I wanted to try usign validation with a broader net: what if instead of saying what's at this pixel, to allow for observer issues, can I say is there a pixel nearby that suits the observed species? And the answer was yes, though with a strong caveat that this is probably the wrong question:

Let's start with the raw performance, which is the top section of that diagram. In that graph the green line is the best of the other habitat maps I'm comparing with, and doing just by pixel alignment is the left most point on all lines, and you can see it performs considerably better than anything else, ourselves included (the blue/purple lines). But as we ask whether a matching pixel can be found in the nearby radius (going along the x axis), you can see our map starts to climb quickly in performance, leading from a 20m radius on. However, if we just had a noisy map where every pixel was a uniform probably to select any habitat, then as we make the radius bigger we'd be bound to do better, as at some point the radius would be enough to cover any pixel. So then are we better, or are we just noisy? That's what the bottom part of that graph is trying to show. In the upper graph the dashed lines are doing the same validation with with randomised habitat preferences for our occurrences, and the bottom graph is the difference between the two - as it gets better we're doing better than noise, as it goes down we are effectively just detecting noise. We can see that we peak around 30m - as we expand our validation radius up to 30m we add more certainty, but after that we're just detecting random noise in the map effectively.
Chatting with my colleague Aneesh Naik he pointed out to avoid the noise issue we should instead compare with a proportion of pixels within the radius: any single pixel is noise, but is there a significant patch within the radius is what we're interested in. I tried several variations, but for now have settled on 10% being a reasonable value. This pixel scaling also helps the other maps though, so it's not just something that helps us, but hopefully at least communicates the challenge we're facing here.

Ultimately this I think highlights the importance of the approach that Finley Stirk has been taking in his Part II Project, as suggested by Aneesh, looking at how to deal with GPS uncertainty using multiple-instance learning. The same approach that Finley is using here I'm fairly sure is the solution to dealing with the problem of observers not being where the observee is. I'm super keen to see how quickly I can take Finley's work and run it over Iceland to see how that does. My validation fixing approach I think is fair but somewhat of a bodge, where as using an inference approach that actually allows for the observation to not be quite where it claims is the real solution. No pressure Finley ;)
Tags: weeknotes