In this post we’ll implement Reed-Solomon error-correcting codes and use them to play with codes. In our last post we defined Reed-Solomon codes rigorously, but in this post we’ll focus on intuition and code. As usual the code and data used in this post is available on this blog’s Github page.
The main intuition behind Reed-Solomon codes (and basically all the historically major codes) is
Error correction is about adding redundancy, and polynomials are a really efficient way to do that.
Here’s an example of what we’ll do in the post. Say you have a space probe flying past Mars taking photographs like this one
Courtesy of NASA’s Viking Orbiter.
Unfortunately you know that if you send the images back to Earth via radio waves, the signal will get corrupted by cosmic something-or-other and you’ll end up with an image like this.
How can you recover from errors like this? You could do something like repeat each pixel twice in the message so that if one is corrupted the other will get through. But still, every now and then both pixels in a row will be corrupted and it’s twice as inefficient.
The idea of error-correcting codes is to find a way to encode a message so that it adds a lot of redundancy without adding too much extra information to the message. The name of the game is to optimize the tradeoff between how much redundancy you get and how much longer the message needs to be, while still being able to efficiently decode the encoded message.
A solid technique turns out to be: use polynomials. Even though you’d think polynomials are too simple (we teach them starting in the 7th grade these days!) they turn out to have remarkable properties. The most important of which is:
if you give me a bunch of points in the plane with different coordinates, they uniquely define a polynomial of a certain degree.
This fact is called polynomial interpolation. We used it in a previous post to share secrets, if you’re interested.
What makes polynomials great for error correction is that you can take a fixed polynomial (think, the message) and “encode” it as a list of points on that polynomial. If you include enough, then you can get back the original polynomial from the points alone. And the best part, for each two additional points you include above the minimum, you get resilience to one additional error no matter where it happens in the message. Another way to say this is, even if some of the points in your encoded message are wrong (the numbers are modified by an adversary or random noise), as long as there aren’t too many errors there is an algorithm that can recover the errors.
That’s what makes polynomials so much better than the naive idea of repeating every pixel twice: once you allow for three errors you run the risk of losing a pixel, but you had to double your communication costs. With a polynomial-based approach you’d only need to store around six extra pixels worth of data to get resilience to three errors that can happen anywhere. What a bargain!
Here’s the official theorem about Reed-Solomon codes:
Theorem: There is an efficient algorithm which, when given points with distinct has the following property. If there is a polynomial of degree that passes through at least of the given points, then the algorithm will output the polynomial.
So let’s implement the encoder, decoder, and turn the theorem into code!
Implementing the encoder
The way you write a message of length as a polynomial is easy. Pick a large prime integer and from now on we’ll do all our arithmetic modulo . Then encode each character in the message as an integer between 0 and (this is why needs to be large enough), and the polynomial representing the message is
If the message has length then the polynomial will have degree .
Now to encode the message we just pick a bunch of values and plug them into the polynomial, and record the (input, output) pairs as the encoded message. If we want to make things simple we can just require that you always pick the values for some choice of .
A quick skippable side-note: we need to be prime so that our arithmetic happens in a field. Otherwise, we won’t necessarily get unique decoded messages.
Back when we discussed elliptic curve cryptography (ironically sharing an acronym with error correcting codes), we actually wrote a little library that lets us seamlessly represent polynomials with “modular arithmetic coefficients” in Python, which in math jargon is a “finite field.” Rather than reinvent the wheel we’ll just use that code as a black box (full source in the Github repo). Here are some examples of using it.
>>> from finitefield.finitefield import FiniteField
>>> F13 = FiniteField(p=13)
>>> a = F13(7)
3 (mod 13)
10 (mod 13)
2 (mod 13)
A programming aside: once you construct an instance of your finite field, all arithmetic operations involving instances of that type will automatically lift integers to the appropriate type. Now to make some polynomials:
>>> from finitefield.polynomial import polynomialsOver
>>> F = FiniteField(p=13)
>>> P = polynomialsOver(F)
>>> g = P([1,3,5])
1 + 3 t^1 + 5 t^2
1 + 6 t^1 + 6 t^2 + 4 t^3 + 12 t^4
4 (mod 13)
Now to fix an encoding/decoding scheme we’ll call the size of the unencoded message, the size of the encoded message, and the modulus, and we’ll fix these programmatically when the encoder and decoder are defined so we don’t have to keep carrying these data around.
def makeEncoderDecoder(n, k, p):
Fp = FiniteField(p)
Poly = polynomialsOver(Fp)
return encode, decode
Encode is the easier of the two.
thePoly = Poly(message)
return [(Fp(i), thePoly(Fp(i))) for i in range(n)]
Technically we could remove the leading
Fp(i) from each tuple, since the decoder algorithm can assume we’re using the first integers in order. But we’ll leave it in and define the decode function more generically.
After we define how the decoder should work in theory we’ll run through a simple example step by step. Now on to the decoder.
The decoding algorithm, Berlekamp-Welch
There are a lot of different decoding algorithms for various error correcting codes. The one we’ll implement is called the Berlekamp-Welch algorithm, but before we get to it we should mention a much simpler algorithm that will work when there are only a few errors.
To remind us of notation, call the length of the message, so that is the degree of the polynomial we used to encode it. And is the number of points we used in the encoding. Call the encoded message as it’s received (as a list of points, possibly with errors).
In the simple method what you do is just randomly pick points from , do polynomial interpolation on the chosen points to get some polynomial , and see if agrees with most of the points in . If there really are few errors, then there’s a good chance the randomly chosen points won’t have any errors in them and you’ll win. If you get unlucky and pick some points with errors, then the you get won’t agree with most of and you can throw it out and try again. If you get really unlucky and a bad does agree with most of , then you just run this procedure a few hundred times and take the you get most often. But again, this only works with a small number of errors and while it could be good enough for many applications, don’t bet your first-born child’s life on it working. Or even your favorite pencil, for that matter. We’re going to implement Berlekamp-Welch so you can win someone else’s favorite pencil. You’re welcome.
Exercise: Implement the simple decoding algorithm and test it on some data.
Suppose we are guaranteed that there are exactly errors in our received message . Call the polynomial that represents the original message . In other words, we have that for all but of the points in .
There are two key ingredients in the algorithm. The first is called the error locator polynomial. We’ll call this polynomial , and it’s just defined by being zero wherever the errors occurred. In symbols, whenever . If we knew where the errors occurred, we could write out explicitly as a product of terms like . And if we knew we’d also be done, because it would tell us where the errors were and we could do interpolation on all the non-error points in .
So we’re going to have to study indirectly and use it to get . One nice property of is the following
which is true for every pair . Indeed, by definition when then so both sides are zero. Now we can use a technique called linearization. It goes like this. The product , i.e. the right-hand-side of the above equation, is a polynomial, say , of larger degree (). We get the equation for all :
Now , , and are all unknown, but it turns out that we can actually find and efficiently. Or rather, we can’t guarantee we’ll find and exactly, instead we’ll find two polynomials that have the same quotient as . Here’s how that works.
Say we wrote out as a generic polynomial of degree and as a generic polynomial of degree . So their coefficients are unspecified variables. Now we can plug in all the points to the equations , and this will form a linear system of unknowns ( unknowns come from and come from ).
Now we know that this system has a good solution, because if we take the true error locator polynomial and with the true we win. The worry is that we’ll solve this system and get two different polynomials whose quotient will be something crazy and unrelated to . But as it turns out this will never happen, and any solution will give the quotient . Here’s a proof you can skip if you hate proofs.
Proof. Say you have two pairs of solutions to the system, and , and you want to show that . Well, they might not be divisible, but we can multiply the previous equation through to get . Now we show two polynomials are equal in the same way as always: subtract and show there are too many roots. Define . The claim is that has roots, one for every point . Indeed,
But the degree of is which is less than by the assumption that . So has too many roots and must be the zero polynomial, and the two quotients are equal.
So the core python routine is just two steps: solve the linear equation, and then divide two polynomials. However, it turns out that no python module has any decent support for solving linear systems of equations over finite fields. Luckily, I wrote a linear solver way back when and so we’ll adapt it to our purposes. I’ll leave out the gory details of the solver itself, but you can see them in the source for this post. Here is the code that sets up the system
for e in range(maxE, 0, -1):
ENumVars = e+1
QNumVars = e+k
def row(i, a, b):
return ([b * a**j for j in range(ENumVars)] +
[-1 * a**j for j in range(QNumVars)] +
) # the "extended" part of the linear system
system = ([row(i, a, b) for (i, (a,b)) in enumerate(encodedMessage)] +
[ * (ENumVars-1) +  +  * (QNumVars) + ])
# ensure coefficient of x^e in E(x) is 1
solution = someSolution(system, freeVariableValue=1)
E = Poly([solution[j] for j in range(e + 1)])
Q = Poly([solution[j] for j in range(e + 1, len(solution))])
P, remainder = Q.__divmod__(E)
if remainder == 0:
return Q, E
raise Exception("found no divisors!")
Q,E = solveSystem(encodedMessage)
P, remainder = Q.__divmod__(E)
if remainder != 0:
raise Exception("Q is not divisibly by E!")
A simple example
Now let’s go through an extended example with small numbers. Let’s work modulo 7 and say that our message is
2, 3, 2 (mod 7)
In particular, is the length of the message. We’ll encode it as a polynomial in the way we described:
If we pick , then we will encode the message as a sequence of five points on , namely through .
[[0, 2], [1, 0], [2, 2], [3, 1], [4, 4]] (mod 7)
Now let’s add a single error. First remember that our theoretical guarantee says that we can correct any number of errors up to , which in this case is , so we can definitely correct one error. We’ll add 1 to the third point, giving the received corrupted message as
[[0, 2], [1, 0], [2, 3], [3, 1], [4, 4]] (mod 7)
Now we set up the system of equations for all above. Rewriting the equations as , and adding as the last equation the constraint that the coefficient of is , so that we get a “generic” error locator polynomial of the right degree. The columns represent the variables, with the last column being the right-hand-side of the equality as is the standard for Gaussian elimination.
# e0 e1 q0 q1 q2 q3
[2, 0, 6, 0, 0, 0, 0],
[0, 0, 6, 6, 6, 6, 0],
[3, 6, 6, 5, 3, 6, 0],
[1, 3, 6, 4, 5, 1, 0],
[4, 2, 6, 3, 5, 6, 0],
[0, 1, 0, 0, 0, 0, 1],
Then we do row-reduction to get
[1, 0, 0, 0, 0, 0, 5],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 3],
[0, 0, 0, 1, 0, 0, 3],
[0, 0, 0, 0, 1, 0, 6],
[0, 0, 0, 0, 0, 1, 2]
And reading off the solution gives and . Note in particular that the given in this solution is the true error locator polynomial, but it is not guaranteed to be so! Either way, the quotient of the two polynomials is exactly which gives back the original message.
There is one catch here: how does one determine the value of to use in setting up the system of linear equations? It turns out that an upper bound on will work just fine, so long as the upper bound you use agrees with the theoretical maximum number of errors allowed (see the Singleton bound from last time). The effect of doing this is that the linear system ends up with some number of free variables that you can set to arbitrary values, and these will correspond to additional shared roots of and that cancel out upon dividing.
A larger example
Now it’s time for a sad fact. I tried running Welch-Berlekamp on an encoded version of the following tiny image:
And it didn’t finish after running all night.
Berlekamp-Welch is a slow algorithm for decoding Reed-Solomon codes because it requires one to solve a large system of equations. There’s at least one equation for each pixel in a black and white image! To get around this one typically encodes blocks of pixels together into one message character (since is larger than there is lots of space), and apparently one can balance it to minimize the number of equations. And finally, a nontrivial inefficiency comes from our implementation of everything in Python without optimizations. If we rewrote everything in C++ or Go and fixed the prime modulus, we would likely see reasonable running times. There are also asymptotically much faster methods based on the fast Fourier transform, and in the future we’ll try implementing some of these. For the dedicated reader, these are all good follow-up projects.
For now we’ll just demonstrate that it works by running it on a larger sample of text, the introductory paragraphs of To Kill a Mockingbird:
message = '''When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow. When it healed, and Jem's fears of never being able to play football were assuaged, he was seldom self-conscious about his injury. His left arm was somewhat shorter than his right; when he stood or walked, the back of his hand was at right angles to his body, his thumb parallel to his thigh. He couldn't have cared less, so long as he could pass and punt.'''
k = len(message)
n = len(message) * 2
p = 2087
integerMessage = [ord(x) for x in message]
enc, dec, solveSystem = makeEncoderDecoder(n, k, p)
encoded = enc(integerMessage)
e = int(k/2)
corrupted = corrupt(encoded[:], e, 0, p)
Q,E = solveSystem(corrupted)
P, remainder = (Q.__divmod__(E))
recovered = ''.join([chr(x) for x in P.coefficients])
Running this with unix
time produces the following:
When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow. When it healed, and Jem's fears of never being able to play football were assuaged, he was seldom self-conscious about his injury. His left arm was somewhat shorter than his right; when he stood or walked, the back of his hand was at right angles to his body, his thumb parallel to his thigh. He couldn't have cared less, so long as he could pass and punt.
So it finishes in “only” an hour or so.
In any case, the decoding algorithm is an interesting one. In future posts we’ll explore more efficient algorithms and faster implementations.
Posts in this series: