
Photo: Tech. Sgt. Lauren Gleason, U.S. Air Force, public domain.
What should we learn now?
The State of Things
Within the corporate world of coding, LLMs are, at least in my sphere, ubiquitous. In some ways, this is fantastic. To all those who complain about slop code and hallucinations, I can assure you that both of those things were happening in astonishing quantities even before LLMs arrived on the scene. So, to some degree, this is a welcome tooling improvement and possibly even an increase in median code quality inside a lot of companies.
But I’m worried. In the old world, you could not help but learn. When you had to go spelunking in some old legacy codebase, you probably picked up a few new tricks and maybe even learned about a build system against your will. We complained about it at the time, but that slow accretion of new ideas and skills was really meaningful. And that’s not even counting the occasional nerd sniping or the rabbit holes you’d go down while yak shaving, only to decide that YOU were the person who was going to fix this particular annoying
None of that happens anymore. We don’t run into the friction because the LLM smooths it out for us. We don’t see the different ways things are done because the harnesses don’t even show us the code as they work anymore.
Instead, we probably have three to five projects going at once and are just cycling through them as the agents come back for their next prompt. We really are all suffering from being promoted to managers, and our technical skills are atrophying.
What can we do, then?
$work is not going to want us coding at 2 mph when we could be doing 30 mph with agents. I think we have to take a page from other industries that have gone through the heavy shift from manual to automated technical work, specifically aviation, where manual flight hours are required in order to maintain qualifications, even though autopilot is capable of doing a large amount of the flying. In order to remain competent and have any hope of actually improving our skills, it’s going to take dedicated effort. And until $work figures this out, it’s going to have to happen on our own time.
What should that look like?
Do things by hand at home. Suffer through the friction of setting up a project on your own. Learn a new language. Go read Knuth. Basically, all the same advice from the before times applies. Possibly even more now than ever, having a broad base of knowledge is an advantage. Learn things one layer below the current level of abstraction at which you work.
Read, write, code, and avoid LLMs when off the clock. If you haven’t already, go write a coding harness BY HAND and see how it all works.
I would go so far as to say that those who avoid LLM usage the longest at $work will be at an advantage. These tools are trivially easy to pick up and don’t require any special skill to master. If you had missed out on the last year of the LLM explosion and just jumped in today, you would probably have a sharper set of technical skills, and you’d have fewer preconceived notions about what models can do. You’d also be less likely to underestimate what you can ask of the latest-generation models.
Closing
There are always exceptions. Some people have the discipline to work on one project at a time, never press the easy button, keep the LLM in check, read all the code, maintain the mental model, etc. But it is generally better not to assume you are the exception and to just put in the work instead.
AI Disclosure
An AI spellchecked this. The words and thoughts are my own.
A Collection of Programming-Adjacent Documentaries
Source: How one programmer’s pet project changed how we think about software
I saw this come out and realized there must be more like it, so I did a little hunting.
Links
- Hacker Interviews: Larry Wall
- Revolution OS (documentary about GNU/Linux)
- Netscape Mozilla Documentary 1998–2000
- Richard Feynman Computer Science Lecture - Hardware, Software and Heuristics
- Erlang: The Movie
- Rise of the personal computer:
April 25, 2026 note programming documentaries software history
FNV Hash Map
This article was partially written by Claude Sonnet 3.5. All of the below was an attempt by me to understanding how hashtables work better, and FNV was the function I chose since I use it often without understanding why it is fast.
:warning: I’m not a C programmer, I just want to get better at it. I found bugs in Claude’s implementation, and I’m sure there’s more I didn’t find. All code below includes my bugfixes, and what I found is cataloged at the end.
All of this is because of a build-it-from-scratch kick with C that I’ve been on, re-inventing a lot of wheels to see how they work. See the use case for this hashmap here.
The Code
(Which we will explain further on, this is just to get the big picture.)
hashmap.h
#ifndef HASHMAP_H
#define HASHMAP_H
// stdint pulls in exact width integers like uint64_t
#include <stdint.h>
// stdbool includes...bool
#include <stdbool.h>
// For size_t
#include <stddef.h>
// Opaque pointer to hide implementation details
typedef struct HashMap HashMap;
typedef void (*ValueCleanupFn)(void*);
// Create/destroy functions
HashMap* hm_create(size_t initial_capacity, ValueCleanupFn value_cleanup);
void hm_destroy(HashMap* map);
// Core operations
bool hm_put(HashMap* map, const char* key, void* value);
void* hm_get(HashMap* map, const char* key);
bool hm_remove(HashMap* map, const char* key);
// Utility functions
size_t hm_size(HashMap* map);
bool hm_is_empty(HashMap* map);
#endif // HASHMAP_H
hashmap.c
// includes stdint and stdbool
#include "hashmap.h"
// For malloc / calloc / free
#include <stdlib.h>
// For strcmp / strdup
#include <string.h>
// FNV-1a hash function constants
#define FNV_OFFSET 14695981039346656037UL
#define FNV_PRIME 1099511628211UL
// Initial load factor and growth settings
#define INITIAL_CAPACITY 16
#define LOAD_FACTOR_THRESHOLD 0.75
typedef struct Entry {
char* key;
void* value;
struct Entry* next;
} Entry;
// typedef in header
struct HashMap {
// A pointer to a pointer of type Entry,
// in this case this is an array of pointers of Entry.
// Each index in the array is a "bucket" and the
// Entries are a linked list.
Entry** buckets;
size_t capacity;
size_t size;
// A fn to call when we clean up values.
ValueCleanupFn value_cleanup;
};
// FNV-1a hash function - proven fast for string keys
static uint64_t hash_key(const char* key) {
uint64_t hash = FNV_OFFSET;
for (const char* p = key; *p; p++) {
hash ^= (uint64_t)(unsigned char)(*p);
hash *= FNV_PRIME;
}
return hash;
}
size_t round_to_power_of_2(size_t initial_capacity) {
// Ensure power of two capacity to ensure fast indexing
if (initial_capacity < INITIAL_CAPACITY) {
return INITIAL_CAPACITY;
}
initial_capacity--;
// Calculate the number of shifts needed based on the size of size_t
#if SIZE_MAX == 0xffffffffffffffffULL // 64-bit
initial_capacity |= initial_capacity >> 32;
#endif
initial_capacity |= initial_capacity >> 16;
initial_capacity |= initial_capacity >> 8;
initial_capacity |= initial_capacity >> 4;
initial_capacity |= initial_capacity >> 2;
initial_capacity |= initial_capacity >> 1;
// Check for overflow before incrementing
if (initial_capacity == SIZE_MAX) {
// We can't round up - we should handle this error
// Maybe return 0 to indicate error, or
// use errno, or return the largest power of 2
return SIZE_MAX >> 1; // Return largest power of 2 that fits
}
return initial_capacity + 1;
}
// Create a `HashMap`, returns NULL if a `HashMap` could not be created.
HashMap* hm_create(size_t initial_capacity, ValueCleanupFn value_cleanup) {
// Round up to the next power of 2
initial_capacity = round_to_power_of_2(initial_capacity);
HashMap* map = malloc(sizeof(HashMap));
if (!map) return NULL;
map->value_cleanup = value_cleanup;
// calloc initializes the memory when it creates it, and it does the
// multiplication of `sizeof(Entry*) * capapcity` and checks for overflows.
map->buckets = calloc(initial_capacity, sizeof(Entry*));
if (!map->buckets) {
free(map);
return NULL;
}
map->capacity = initial_capacity;
map->size = 0;
return map;
}
static void resize_if_needed(HashMap* map) {
if ((double)map->size / map->capacity > LOAD_FACTOR_THRESHOLD) {
// No resize needed
return;
}
size_t new_capacity = map->capacity * 2;
Entry** new_buckets = calloc(new_capacity, sizeof(Entry*));
if (!new_buckets) return; // Failed alloc
// Rehash all entries
for (size_t i = 0; i < map->capacity; i++) {
// since we calloc'd to zero this out, buckets with no pointer are NULL
Entry* entry = map->buckets[i];
while (entry) { // Traverse the linked list
Entry* next = entry->next;
size_t new_index = hash_key(entry->key) & (new_capacity - 1);
// Set the next for this entry to whatever is currently in the
// new_buckets list of pointers, then set the new_buckets pointer
// to this entry, extending the linked list.
entry->next = new_buckets[new_index];
new_buckets[new_index] = entry;
entry=next;
}
}
free(map->buckets);
map->buckets = new_buckets;
map->capacity = new_capacity;
}
// Returns true if the key was set, false if allocations failed and it was not set.
// If the key already exists, this will overwrite its value.
bool hm_put(HashMap* map, const char* key, void* value) {
resize_if_needed(map);
size_t index = hash_key(key) & (map->capacity - 1);
// Check for an existing key
for (Entry* entry = map->buckets[index]; entry; entry = entry->next) {
if (strcmp(entry->key, key) == 0) {
if (map->value_cleanup) map->value_cleanup(entry->value);
entry->value = value;
return true;
}
}
// Create a new entry
Entry* new_entry = malloc(sizeof(Entry));
if (!new_entry) return false;
new_entry->key = strdup(key);
if (!new_entry->key) {
free(new_entry);
return false;
}
new_entry->value = value;
new_entry->next = map->buckets[index];
map->buckets[index] = new_entry;
map->size++;
return true;
}
void* hm_get(HashMap* map, const char* key) {
size_t index = hash_key(key) & (map->capacity - 1);
for (Entry* entry = map->buckets[index]; entry; entry = entry->next) {
if (strcmp(entry->key, key) == 0) {
return entry->value;
}
}
return NULL;
}
// Returns true if the key was in the map and was deleted.
bool hm_remove(HashMap* map, const char* key) {
size_t index = hash_key(key) & (map->capacity - 1);
Entry** pp = &map->buckets[index];
while (*pp) {
Entry* entry = *pp;
if (strcmp(entry->key, key) == 0) {
// This is tricky.
// This is setting the pervious entries / buckets pointer
// to point the the next entry to skip this node in the linked list.
*pp = entry->next;
free(entry->key);
if (map->value_cleanup) map->value_cleanup(entry->value);
free(entry);
map->size--;
return true;
}
pp = &entry->next;
}
return false;
}
void hm_destroy(HashMap* map) {
if (!map) return;
for (size_t i = 0; i < map->capacity; i++) {
Entry* entry = map->buckets[i];
while (entry) {
Entry* next = entry->next;
free(entry->key);
if (map->value_cleanup) map->value_cleanup(entry->value);
free(entry);
entry=next;
}
}
free(map->buckets);
free(map);
}
// Get the current number of elements in the map
size_t hm_size(HashMap* map) {
return map->size;
}
// Check if the map is empty
bool hm_is_empty(HashMap* map) {
return map->size == 0;
}
Key Ideas
Power of two sizing (capacity)
Power of two sizing allows for very fast lookup with the hash key.
In our implementation, we use this simple but effective line:
size_t index = hash_key(key) & (map->capacity - 1);
Let’s break down why this works so well. Say our hashmap has a capacity of 16. In binary:
capacity = 16 = 00010000
capacity - 1 = 15 = 00001111
When we do a bitwise AND (&) with any number and (capacity-1), we’re essentially taking the remainder of that number when divided by capacity. But we’re doing it much faster than using the modulo operator (%).
Let’s walk through an example. Imagine our FNV hash function returns this value for a key:
hash = 12345678 = 00000000000000000000000010111100101100101001110
capacity - 1 = 15 = 00000000000000000000000000000000000000001111
When we do the bitwise AND:
hash = 00000000000000000000000010111100101100101001110
capacity - 1 = 00000000000000000000000000000000000000001111
result = 00000000000000000000000000000000000000001110 = 14
We get 14, which is a valid index for our array of size 16.
This is why we always make our capacity a power of 2 in the create function:
// Round up to next power of 2
initial_capacity--;
initial_capacity |= initial_capacity >> 1;
initial_capacity |= initial_capacity >> 2;
initial_capacity |= initial_capacity >> 4;
initial_capacity |= initial_capacity >> 8;
initial_capacity |= initial_capacity >> 16;
initial_capacity++;
The magic here is that powers of 2 minus 1 give us numbers that are all 1s in binary:
Capacity Binary (capacity) Binary (capacity - 1)
4 100 011
8 1000 0111
16 10000 1111
32 100000 11111
If we didn’t use a power of 2 for capacity, say 10:
capacity = 10 = 1010
capacity - 1 = 9 = 1001
This would lead to uneven distribution of indices because some bits in our mask would be 0, meaning those positions in our hash value wouldn’t contribute to the final index.
To make this even more concrete, let’s add some debug code to see this process:
void debug_hash_to_index(const char* key, size_t capacity) {
uint64_t hash = hash_key(key);
size_t index = hash & (capacity - 1);
printf("Key: %s\n", key);
printf("Hash: %lu\n", hash);
printf("Capacity: %zu\n", capacity);
printf("Capacity - 1 (mask): %zu\n", capacity - 1);
printf("Resulting index: %zu\n\n", index);
}
// Usage example:
debug_hash_to_index("hello", 16);
debug_hash_to_index("hello", 32);
This technique of using bitwise AND with (power_of_2 – 1) is so efficient that it’s used in many high-performance applications, including the Java HashMap implementation.
Fast hashing
The FNV (Fowler-Noll-Vo) hash function a fascinating algorithm that achieves excellent distribution while remaining surprisingly simple and fast.
Let’s look at the core implementation from our hashmap:
#define FNV_OFFSET 14695981039346656037UL // FNV offset basis for 64-bit
#define FNV_PRIME 1099511628211UL // FNV prime for 64-bit
static uint64_t hash_key(const char* key) {
uint64_t hash = FNV_OFFSET; // Start with the offset basis
for (const char* p = key; *p; p++) { // For each byte in the input
hash ^= (uint64_t)(unsigned char)(*p); // XOR the byte into the hash
hash *= FNV_PRIME; // Multiply by the prime number
}
return hash;
}
The FNV hash works through a carefully chosen combination of three elements:
An offset basis (FNV_OFFSET): This is a large, carefully selected number that starts the hash calculation. Think of it as providing a random-looking starting point for every hash computation.
A prime number (FNV_PRIME): This prime was specifically chosen because its multiplication properties help spread the bits of the input across the hash result. It’s similar to how multiplying by a prime number tends to distribute numbers evenly when taking remainders.
The mixing operation: For each byte of input, the algorithm:
- XORs the byte into the current hash value
- Multiplies the result by the prime number
Let’s walk through a simple example of hashing the string “cat”:
Starting with: hash = FNV_OFFSET
For 'c' (ASCII 99):
hash = hash XOR 99
hash = hash * FNV_PRIME
For 'a' (ASCII 97):
hash = hash XOR 97
hash = hash * FNV_PRIME
For 't' (ASCII 116):
hash = hash XOR 116
hash = hash * FNV_PRIME
The genius of FNV lies in how these operations interact:
- The XOR operation mixes in each byte’s bits in a reversible way
- The multiplication by a prime number diffuses these bits throughout the hash value
- Each subsequent byte affects all bits of the final hash
What makes FNV particularly good for hashmaps is:
- Speed: It uses simple CPU operations (XOR and multiply)
- Avalanche effect: Small input changes cause large hash value changes
- Good distribution: Output values spread evenly across the possible range
- Low collision rate: Different inputs rarely produce the same hash
We can actually visualize this distribution. Here’s a conceptual example:
// Demonstrating FNV's distribution
void visualize_distribution(void) {
char key[4] = "aaa";
int buckets[16] = {0}; // Count hashes in 16 buckets
// Try all possible 3-letter combinations
for(char c1 = 'a'; c1 <= 'z'; c1++) {
for(char c2 = 'a'; c2 <= 'z'; c2++) {
for(char c3 = 'a'; c3 <= 'z'; c3++) {
key[0] = c1; key[1] = c2; key[2] = c3;
uint64_t hash = hash_key(key);
buckets[hash % 16]++; // Count which bucket it falls into
}
}
}
// buckets[] would show relatively even distribution
}
When we need to optimize this function further, there are several variations:
- FNV-1a (what we used): XOR then multiply
- FNV-1: Multiply then XOR
- Different bit widths (32-bit, 64-bit, etc.)
The version we used (FNV-1a) is generally considered the best for most purposes because the XOR-then-multiply pattern provides slightly better avalanche behavior than the original FNV-1.
Quick Aside on the implementation from Claude in C
I am not a C programmer, really. And I’m not an expert in building hash maps. But the implementation from Claude had a lot of bugs that I caught along the way that would have been problems if I just copy pasted and ran with it:
- Claude didn’t free the memory of the values when calling
hm_putorhm_destroy. - Claude didn’t handle
size_tbeing 64 bits for initial_capacity- When prompted to handle this better, it then failed to handle the case of being passed
SIZE_MAX(max u64) (if someone asked for a hashmap of that size, things are arguably borked, but it should still handle it)
- When prompted to handle this better, it then failed to handle the case of being passed
- Claude truncated the comparison against LOAD_FACTOR_THRESHOLD to a float instead of a double
Other Interesting Tidbits
Null Terminated Strings
I’ve always wondered at the null terminated string choice in C. I still wonder about it, but this little loop at least shed a bit of light on how an ecosystem designed around it can work:
for (const char* p = key; *p; p++) {
hash ^= (uint64_t)(unsigned char)(*p);
hash *= FNV_PRIME;
}
That loops through the string, the stop condition is checking *p which will be false when it hits the null termination character.
The Cost or Resizing a HashMap
I knew that you had to re-allocate and copy, like when resizing a Vector/List, but I did not realize that re-sizing involved re-hashing all keys.
Linked Lists :vomit:
What if we just kept a dynamically sized array… or even fixed size for each bucket that held entries? That way when looking through a bucket we don’t have to fetch all over the heap. I’m betting that this is negligible with a good hash function that avoids collisions. But I don’t really have a sense of how often collisions happen. To be explored later.
Further Reading
- Article on the limitations of the Rust
Hashertrait. - Article on fixed size integer hashing (potential future exploration for encoded kmer hashing).
Comment
If you have any feedback, especially pointing out mistakes, please leave a comment!

Nim + Python + Poetry = :)
Sometimes you need a little more speed. Or you need to be able to justify writing some Nim. In either case there is an easy way to bundle your Nim code in with your Python code.
In this article we will do a quick overview of how to add Nim via Poetry. Before diving in here are the tools being used:
- Nim: A fast, pythonic, compiled language
- Nimpy: A Nim library for exporting functions to python
- Nimporter: A Python library for importing .nim files
- Poetry: A build tool for Python heavily influenced by Cargo
Install Things
You will need to install Nim, Poetry, and Nimpy. Nim and poetry include very good install instructions via the links above. For Nimpy, I recommend installing it via Nimble, which is bundled with Nim. Just run nimble install nimpy.
Not Doing
Both nimpy and nimporter have excellent docs. This guide is just walking through how to hook nimporter in with poetry, not the details of nimpy, nimporter, or poetry.
This is a Hack
But it kind of works… and Python packaging is basically all one giant gross hack, so maybe this isn’t so bd?
Begin Hack
Create a poetry project:
mkdir ponim
cd ponim
poetry init -n
This will create a pyproject.toml file in your current directory. Next up, lets make this a Python library!
mkdir ponim
cd ponim
touch __init__.py
touch subtractor.py
cd ../
We are just going to make a subtractor function in python:
# In subtractor.py
def subtractor(a: int, b: int) -> int:
return a - b
Now let’s make that available high up the import chain:
# In __init__.py
from .subtractor import subtractor
Cool, now let’s test that all that works so far and install our package into a venv managed by Poetry:
# back in your main project dir
poetry shell
poetry install
And now drop into the Python REPL and test it:
python
>>> import ponim
>>> ponim.subtractor(44, 2)
42
It works! So let’s add some Nim.
poetry add nimporter
poetry install
touch ponim/adder.nim
And then fill out the nim file:
# In adder.nim
import nimpy
proc add(a: int, b: int): int {.exportpy.} =
return a + b
And now for the magic bit, making this work seamlessly with subtractor.py. We’ll update the __init__.py to import the nim file and make it available in the package.
import nimporter # This must come first
from .subtractor import subtractor
from .adder import adder
And then rebuild the package and test it out
poetry install
python
>>> import ponim
>>> ponim.subtractor(44, 2)
42
>>> ponim.adder(40, 2)
42
And that’s it! You now have nim code bundled with your Python code! To create a wheel all you need to do is run poetry build and your .nim files will be included. The host system will still need to have nimpy + Nim installed, but that shouldn’t be too hard to work around / improve in the future.
There is the overhead of the nim code compiling on the first run. If you actually use this to bundle application code, you could work around that issue by running ‘python -c “import ponim”’ after installing the wheel. This will cache the compiled nim code in your __pycache__.
So why go through all this trouble? Nim is way nicer to work with than Cython, and offers the same or better performance. There are a few wrinkles yet to be smoothed out, but this setup could easily be used with docker to deploy a python + nim application. With all the exiting things going on in Nim, like optional move semantics for performance, and the concurrency work, having this easy of an interop is amazing.
Happy Hacking!
The source code for this can be found here: https://github.com/sstadick/ponim
Choosing a Language for Bioinformatics

But why?
Bioinformatics is an interesting field when it comes to language choices. On the one hand, you are writing a lot of cheap scripts to get your data from point A to point B in a unix like environment. On the other hand, you are likely sending a lot of data through those cheap scripts.
The time honored tradition has been to write your cheap scripts in a scripting language, usually Perl or Python, and then identify the places that are doing the heavy lifting, or tools that are ubiquitous / used repeatedly, and rewrite them in something faster, usually C or C++. This has worked well, and likely will continue to work well into the future. But sometimes…sometimes you really don’t want to write C/C++. It’s really fun for the first few hours…maybe even the first few days, but then reality sets in and the enormity of what you’ve undertaken weighs heavily upon you as you repeatedly find bugs in the hand rolled functions that are part of the standard lib of your daily driver language. You gnash your teeth. You decry the gods of programming. You despair.
But wait! We are in the 21st century, we have options! My personal criteria has evolved over time, but currently stands as:
- Scriptability - How easy is it write a quick and dirty script to act as a filter?
- Scalability - Can it grow from a script into a performance critical piece of software?
- IO - Is there something inherently slow about how the language deals with IO? How easy is it to perform IO tasks?
- String Ops - Are the builtins for doing string manipulations efficient, or do they just look pretty? How feature rich are the string ops?
- Lightweight Modeling - Can we cheaply model our problem via types, classes, or builtin data structures?
- Array and String allocations - Does the compiler / interpreter optimize allocations?
- (Not yet done) C binding - How easy is it to use a c library?
- (Not yet done) C interop - Is there a large cost to interacting with C libraries?
These features are not things that normally fall into other peoples benchmarks categories.
The programs used in most of these benchmarks come down to numeric problems at their core. Benchmarks that revolve around IO and string ops are always going to be dubious to some degree. What I have tried to do is write a short script in each language that demonstrates a common task that I perform every day: parsing a TSV.
Pragmatic but Dubious Benchmarks
I chose 4 languages based on the benchmarks listed above, as well as personal bias:
- Python
- Perl
- Nim
- D
In each language I wrote the same script, adjusting it to fit what would be ‘idiomatic’ for the language, but not optimizing outside of that. The Python script is as follows:
As you can see, this follows that pattern of read a line, process the line, save the result, do some calculations on the result. I am covering all of my above criteria, minus the C interop bits, and to some degree the question of scaling. You can check out how the input dataset was generated and the programs run/compiled here.
Without further ado, here are the results:
*In ugly form so that they update.
Nim is blazingly fast! I’d toyed with Nim in the past, but never took it too seriously. Nim compiles to C, and has the potential of being as fast as C depending on how low down you want to go. The beauty of it is that on the surface it is as high level as Python. I’m not going to give a whole intro to Nim because others have already done that better than I could.
What I love the most about Nim, outside of its speed, is the pragmatism of its community and core devs. As I’ve been digging through the Nim forum, Reddit, and their Github issues, I’ve been impressed by the focus on making sure that the language remains focused on enabling people to solve problems.
Overall I’ve been won over and will be using Nim as my daily driver for a while to learn it better. Specifically I want to toy with its interop with C/C++ libs, which looks very straightforward, and to see how low the language can go when trying to optimize as fast as possible. There already seems to be some momentum for Nim in the land of bioinformatics.
But wait…
But where are Rust and Go?
- Go has a high cost interop with C/C++, and too much work exists in C/C++ within bioinformatics to ignore that.
- Rust has too high a cognitive overhead, and too ornate of a syntax to work as an every day scripting language.
Your implementation of
- Feel free to submit a PR! But remember, I’m not optimizing for the fastest tab splitting field counter ever, I just want a pragmatic example of daily code.
Correct Me!
February 8, 2020 essay bioinformatics programming languages benchmarks
TRE: A Regex Engine with Approximate Matching

TRE is a regex engine that allows for approximate matching. It does this by using calculating the Levenshtein Distance (number of insertions, deletions, or substitutions it would take to make the strings equal), as it searchs for a match.
The re::engine::TRE is a Perl wrapper around the TRE engine. It swaps out the default Perl regex engine with the TRE engine within the lexical scope that it is used.
Before we dive into the nitty gritty, here are a few examples.
S=Substitution, I=Insertion, D=Deletion
Fuzzy matching:
0> use re::engine::TRE max_cost => 2
1> say $& if 'pesarl' =~ /perl/x # 2I
pesa
2> say $& if 'prjl' =~ /perl/x # 2S
prjl
Fuzzy captures:
0> use re::engine::TRE max_cost => 6
1> say "\$1 = $1, \$2 = $2" if 'Fussy wuzzy has a beer' =~ /(fuzzy) wuzzy was a (bear)/xi
$1 = Fussy, $2 = beer
Perl regex variables returned (this is so handy):
0> use re::engine::TRE max_cost => 2
1> say "$1 starts at $-[1] and ends at $+[1]" if 'GATACA' =~ /GA(TCC)A/x
TAC starts at 2 and ends at 5
Implementation details
So now that you’ve seen the basic flavor of what the TRE is, let’s clear up some of the details that I found really confusing when I started with it.
The ERE vs the BRE Syntax
They syntax that TRE uses can be switched to either use the POSIX Extended Regular Expression syntax, ERE, or the Basic Regular Expression syntax, BRE. The docs page, however, does not make this clear. The re::engine::TRE implementation looks for the /x flag in order to switch on ERE, which is almost certainly what you want.
The Approximate match specifier
TRE does mix in some of its own syntax as well though. The ‘Approximate Match Settings’ are the primary example of this. They allow you to set the number of mismatches, in total or specific type, for an atom. They also allow you to set the score of each type of mismatch for that atom.
EX:
0> use re::engine::TRE max_cost => 6
1> say "$1 starts at $-[1] and ends at $+[1]" if 'GATTACA' =~ /GA(TCC){ #1+1~2 }A/x
TTAC starts at 2 and ends at 6
2> say "$1 starts at $-[1] and ends at $+[1]" if 'GATGGGGA' =~ /GA(TACAC){ #1+1-1~2 }A/x
# No match
The last example says that my capture group can have only one insertion, 1 deletion, or 1 substitution, but that it can’t have more than 2 errors in total. This brings up one of the gotchas though. It is sometimes hard to ‘see’ the edits that lead to a match. For example, GATCCCCA would have matched and given ‘TCCC’ as my capture, which is one substitution, and 1 deletion in the capture group, and 1 insertion outside of it.
Pragmas
When importing re::engine::TRE, you can set various ‘global’ pragma, such as ‘max_cost’, which specify the overall settings for TRE to use. The defaults can be found in the re::engine::TRE docs. If you set the global max cost to 2, but have an atom allowing up the 3 errors, the global cost will overrull that and no match will be returned.
I should note that I don’t know the details of how Perl’s use statement works well enough to speak to what kind of overhead throwing use re::engine::TRE max_cost => 2 into a function result in. I think that use is a compile time thingy, and therefor you can put it in a function had have low to no overhead from the ‘import’ each time the function is called. But I could be totally wrong about that.
Other places TRE can be found
Other Fuzzy Matching Options
- Text::Fuzzy
- String::Approx
- Text::Levenshtein::XS
- Python’s alt regex module
- Python’s Fuzzywuzzy
Excellent Articles
- How to Write a Spelling Corrector by Peter Norvig
- SymSpell by Wolf Garbe
A Bunch of Example Test Cases
Some day I will hopefully PR more test cases into re::engine::TRE
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
plan tests => 66;
# Approx match a basic string
{
use re::engine::TRE max_cost => 1;
ok( 'pearl' =~ /perl/, 'Test Approx match with 1 insertion' );
ok( 'per' =~ /perl/, 'Test Approx match with 1 deletion' );
ok( 'perd' =~ /perl/, 'Test Approx match with 1 substitution' );
}
# Approx match a basic string
{
use re::engine::TRE max_cost => 2;
ok( 'pesarl' =~ /perl/, 'Test Approx match with 2 insertion' );
ok( 'er' =~ /perl/, 'Test Approx match with 2 deletion' );
ok( 'berd' =~ /perl/, 'Test Approx match with 2 substitution' );
ok( 'prjl' =~ /perl/, 'Test Approx match with 1I1D' );
ok( 'ped' =~ /perl/, 'Test Approx match with 1D1S' );
ok( 'derJl' =~ /perl/, 'Test Approx match with 1I1S' );
ok( 'terd' =~ /perl/, 'Test Approx match with 2S' );
}
# Perl magic regex vars
# Note that for clasical 'bounds' {} and 'capture groups' () must be escaped
# Note also that the local approx match {} also need escaping
# All esamples with capture groups are locally scoped to avoid $1 issues
# qr strings specifically seem to not work at the moment
{
use re::engine::TRE max_cost => 2;
{
ok( 'GATAAAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex normal match' );
is( $1, 'AAAA', 'Test capture group' );
is( $-[1], 3, 'Test @- capture group 1 index' );
is( $+[1], 7, 'Test @+ capture group 1 index' );
}
{
ok( 'GAAAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex normal match non-greedy match'
);
is( $1, 'AAAA', 'Test capture group - non-greedy' );
is( $-[1], 2, 'Test @- capture group 1 index - non-greedy' );
is( $+[1], 6, 'Test @+ capture group 1 index - non-greedy' );
}
# 1 Insertion/Deletion/Substitution
{
ok( 'GTATAAAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 1I' );
is( $1, 'TAAA', 'Test capture group mutated - 1I' );
is( $-[1], 3, 'Test @- capture group 1 index - 1I' );
is( $+[1], 7, 'Test @+ capture group 1 index - 1I' );
}
{
ok( 'GATAAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 1D'
);
is( $1, 'AAAA', 'Test capture group - 1D' );
is( $-[1], 3, 'Test @- capture group 1 index - 1D' );
is( $+[1], 7, 'Test @+ capture group 1 index - 1D' );
}
{
ok( 'GATAAGAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 1S' );
is( $1, 'AAGA', 'Test capture group - 1S' );
is( $-[1], 3, 'Test @- capture group 1 index - 1S' );
is( $+[1], 7, 'Test @+ capture group 1 index - 1S' );
}
# 2 Insertion/Deletion/Substitution
{
ok( 'GACTAAAAAT' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 2I' );
is( $1, 'AAAA', 'Test capture group - 2I' );
is( $-[1], 4, 'Test @- capture group 1 index - 2I' );
is( $+[1], 8, 'Test @+ capture group 1 index - 2I' );
}
{
ok( 'ATAAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 2D'
);
is( $1, 'AAAA', 'Test capture group - 2D' );
is( $-[1], 2, 'Test @- capture group 1 index - 2D' );
is( $+[1], 6, 'Test @+ capture group 1 index - 2D' );
}
{
ok( 'GATAAAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 2S' );
is( $1, 'AAAA', 'Test capture group - 2S' );
is( $-[1], 3, 'Test @- capture group 1 index - 2S' );
is( $+[1], 7, 'Test @+ capture group 1 index - 2S' );
}
{
ok( 'CATAATAAA' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 1I1S'
);
is( $1, 'AATA', 'Test capture group - 1I1S' );
is( $-[1], 3, 'Test @- capture group 1 index - 1I1S' );
is( $+[1], 7, 'Test @+ capture group 1 index - 1I1S' );
}
{
ok( 'GAAAAAAT' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 1I1D'
);
is( $1, 'AAAA', 'Test capture group - 1I1D' );
is( $-[1], 3, 'Test @- capture group 1 index - 1I1D' );
is( $+[1], 7, 'Test @+ capture group 1 index - 1I1D' );
}
{
ok( 'ATAAAAG' =~ /^G[AT]{2}?([GATC]{4})A/x,
'Test complex mutated match - 1D1S'
);
is( $1, 'AAAG', 'Test capture group - 1D1S' );
is( $-[1], 3, 'Test @- capture group 1 index - 1D1S' );
is( $+[1], 7, 'Test @+ capture group 1 index - 1D1S' );
}
}
# Use the local approximate match settings
# You can specify a max for a local subpattern, that counts toward global max
# local max total can't exceed global
{
use re::engine::TRE max_cost => 2;
# Show that everything is normal
{
ok( 'ATACTAC' =~ /^A(TACT)AC/x,
'Local approx match settings - exact' );
is( $1, 'TACT', 'Local approx match capture group 1 - exact' );
}
# Mutate 2 Bases in the capture group and still capture
{
ok( 'ATGTTAC' =~ /^A(TACT)AC/x,
'Local approx match settings - 2S, no local' );
is( $1, 'TGTT', 'Local approx match capture group 1 - 2S, no local' );
}
# Mutate 2 Bases in capture group, but set local max to 1 (no match)
{
ok( 'ATGTTAC' !~ /^A(TACT){~1}AC/x,
'Local approx match settings - 2S, local 1'
);
is( $1, undef, 'Local approx match capture group 1 - 2S, local 1' );
}
# Mutate only 1 base in the capture group and 1 outside it
{
ok( 'ATATTAG' =~ /^A(TACT){~1}AC/x,
'Local approx match settings - 1S global, local 1'
);
is( $1, 'TATT', 'Local approx match capture group 1 - 1S global, local 1' );
}
# Mutate only 1 base in the capture group and 2 outside it
{
ok( 'CTATTAG' !~ /^A(TACT){~1}AC/x,
'Local approx match settings - 2S global, local 1'
);
is( $1, undef, 'Local approx match capture group 1 - 2S global, local 1' );
}
# Mutate only 3 base in the capture group and 0 outside it to test global limit
{
ok( 'ATGTGAG' !~ /^A(TACT){~3}AC/x,
'Local approx match settings - 0S global, local 3'
);
is( $1, undef, 'Local approx match capture group 1 - 0 global, local 3' );
}
}