Algorithmadvanced
Common lines method
Also called angular reconstitution.
Find the relative orientations of projection images from the lines along which pairs of their 2D Fourier transforms agree, as the slice theorem requires.
- Time
- O(m a n^2 + m^2 a^2 d + m^4) totalO(a^2 d) per_iteration
- Space
- O(a n^2 + m a d + m^2) extra
- Where
- a = the number of angles in the sinogram of one image; d = the number of bins in one line projection; m = the number of images; n = the side of an n x n image
- Model
- Real RAM
- Properties
- deterministicexact on exact linesnot handedness resolvednot in placenot iterativeneeds three imagesiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Marin van Heel, 1987
The common lines method finds the orientations of 2D projection images of one 3D object when the orientations are not known. It is a basic step of single-particle reconstruction in cryo-electron microscopy. By the Fourier slice theorem, the 2D Fourier transform of each image is a central plane of the 3D Fourier transform of the object. Two central planes meet in a line through the origin, so any two images share one line of Fourier values, their common line. In real space the same fact says that two images have one pair of equal line projections. The method finds the common line of each pair of images by a search in their sinograms. From the common lines of three images it computes their relative rotations exactly, and from these it places the other images one by one. The data fix the rotations only up to a global rotation and up to a reflection: the mirror image of the object gives the same images, so the handedness stays open.
In plain words
A microscope takes flat shadow pictures of many copies of one molecule. Each copy lies in an unknown direction. To build the 3D shape, you first need to know how each picture is turned.
Any two shadow pictures of one object have one thing in common. If you squash each picture onto a line at the right angle, the two squashed profiles are the same, because both show the object squashed onto one direction in space. The method searches each pair of pictures for this matching pair of angles.
The matching angles of three pictures fix how the three are turned against each other, like three hinged plates. Each further picture is then placed from two pictures that are already placed. One question stays open: a mirror copy of the molecule gives exactly the same pictures, so the pictures alone cannot tell left from right.
The problem
There is a density on and there are unknown rotations . The input is the images
sampled on grids. The columns of are the image axes and the beam direction , written in the frame of the object. An image covers , with the pixel centers and ; the images must be centered, so that the origin of the object projects to the center of every image. The output is rotations with for all pairs, or the same with every replaced by , where .
Common lines. For a unit vector in the image plane, let be the line projection of image in the direction , one line of its sinogram. If , the unit vector along lies in both central planes. In the coordinates of image it is the direction , and in image it is . Then
because both sides are the integral of over the plane , that is the 3D Radon transform of at (a theorem, proved in the correctness proof). In Fourier space, with , the 1D transform of this line projection is on the line through the origin in the direction . A line in the direction is the line in the direction read in reverse, so a search over the angles must also try each line of the second image reversed.
The algorithm
is the rotation with the columns , the unit vector along the part of orthogonal to , and the cross product of these two. A 2D direction is used as the 3D vector . The angle is the direction .
COMMON-LINES(P_1..P_m, a)- 1
S_i ← the line projections of P_i at the angles πl/a, l = 0..a-1, for each i - 2
for each pair i < j, find the line α of S_i and the line β of S_j, forward or reversed, with the smallest distance, refined by a parabola - 3
c_ij ← ω(α); c_ji ← ω(β), or -ω(β) for a reversed match - 4
pick the triple (r, b, d) whose smallest |sin| between the two common lines in any of its three images is largest - 5
q_rb ← c_rb; q_rd ← c_rd ▷ R_r = I - 6
q_bd ← the unit vector with q_bd·q_rb = c_br·c_bd, q_bd·q_rd = c_dr·c_db and third coordinate ≥ 0 - 7
R_b ← FRAME(q_rb, q_bd) FRAME(c_br, c_bd)^T; R_d ← FRAME(q_rd, q_bd) FRAME(c_dr, c_db)^T - 8
while some image has no rotation, pick an unplaced k and placed u, v with the largest |sin| between c_ku and c_kv - 9
R_k ← FRAME(R_u c_uk, R_v c_vk) FRAME(c_ku, c_kv)^T - 10
return R_1..R_m
Line L6 is the triangle step. In the frame of image , the common directions and lie in the plane , and the unknown has known dot products with both, because the angle between two common lines inside image is the angle between the corresponding directions in space. Two linear equations give the first two coordinates of , and its length 1 gives the third up to the sign. The sign is the handedness, and the algorithm takes the positive one. Line L9 maps the two known directions , of image to their known places , in space; a rotation is fixed by where it sends two independent vectors.
Example
By hand. Take , the rotation by 90 degrees about the axis, and the rotation by 90 degrees about the axis. The beams are , and . The common directions are , and . In the images they are , , , , and . Line L5 gives and . In line L6, and , so is orthogonal to and , and the positive sign gives . Line L7 gives
the true rotation about , and in the same way , the true rotation about . The negative sign would give and , the answer for the mirror image of the object.
From images (a measurement). The tests use a density of 6 Gaussian blobs with random weights, centers in and widths from 0.12 to 0.2, and 5 random rotations (seed 1). Each image is , with angles (3 degree steps) and bins. The 10 common lines found in the sinograms are within 0.25 to 1.40 degrees of the true ones, with the right signs. The rotations after removing the global rotation and the reflection are within 0.26, 0.68, 0.91 and 1.00 degrees of the truth (the comparison is relative to the first image, so its error is 0). With only the first three images, the error is 1.35 degrees. With exact common lines, the error is below radians.
Correctness
The correctness proof proves the common-line identity above. It then proves that lines L4 to L9 are exact: if the common lines are exact, no two beams are equal or opposite, and the beams of some three images are linearly independent, the output is for all or for all , with one rotation (a theorem). The key facts are that for a rotation , and . The proof also shows that the reflection cannot be resolved from the images: the images of at the rotations are the images of at . So three images in general position fix the orientations up to a global rotation and the handedness, and no more data of this kind can fix the handedness. The search for the lines in lines L1 to L3 is not exact; its accuracy is a measurement.
Proof: Common lines exist, and exact common lines fix the rotations up to a global rotation and a reflectionfull
We use the notation of the page. is an integrable density on , are rotations, and image is . The columns of are the image axes and the beam direction . For a unit vector in the image plane, is the line projection of image in the direction , where is turned by 90 degrees; this is one line of the sinogram of . We write , and for the 3D Radon transform (integrals over planes).
The code only finds the common lines approximately, on a grid of angles with a parabola refinement, and the match of the lines is not a theorem; the page gives measurements for it. What is proved here is the part after the lines: the statements that make the search meaningful (Lemma 1) and the exactness of lines L4 to L9 (Theorems 3 and 4).
Lemma 1 (common lines). If , let , and . Then and are unit vectors, , and
Also , so the line of image in the direction is the line in the direction read in reverse.
Proof. The third coordinate of is , so , and ; the same holds for . For a unit in the image plane, the vectors , and are an orthonormal basis, and maps it to the orthonormal basis , , . So
because is an isometry onto the plane . With this is , and the same computation in image gives the same value. The last claim is the change , since .
By the Fourier slice theorem, with the convention , the 1D transform of is , so Lemma 1 says the same thing in Fourier space: the 2D transforms of and agree on the central lines in the directions and , which are the two images of the line where the central planes and meet.
Lemma 2 (frames). For linearly independent , is the matrix with the columns , $e_2 = $ the unit vector along , and . It is a rotation. For every rotation , . For the reflection , .
Proof. The columns are orthonormal by construction and , so the determinant is . An orthogonal keeps lengths and dot products, so the first two columns of are and . For any orthogonal , . For a rotation the third column is . For , with , it is , and changing the sign of the third column is multiplication by on the right.
Theorem 3 (placing one image, line L9). Let be a rotation and let be either the identity or the map . Suppose the placed images and have and , the common lines are exact, and the beams , , are linearly independent. Then
Proof. Let and (Lemma 1). They are not parallel: a vector parallel to both would be orthogonal to , and , which span . Write . Take first the identity. Then , and in the same way . By Lemma 2 with , the first frame is , and . For , use for vectors in the image plane: , and the same for . By Lemma 2 (both parts) the first frame is . The first two columns of lie in the image plane and the third is , so is the reflection in the image plane, which is . So .
Theorem 4 (the anchor triangle, lines L5 to L7). Let images , , have linearly independent beams and exact common lines. Lines L5 to L7 return and , with
where . The first case holds when the third coordinate of is positive, the second when it is negative, and it is never zero.
Proof. Put for the three common directions , , of Lemma 1. By Lemma 1, and , which is line L5. They are not parallel, by the argument of Theorem 3, so the determinant in the code is not zero. The unknown is a unit vector with
Since and span the plane , these two equations fix the first two coordinates of , and fixes the third up to its sign, . The third coordinate is , which is not zero, because is orthogonal to and , and a vector orthogonal to all three independent beams is zero. Line L6 takes the positive sign.
If the positive sign is the true one, line L6 returns , and line L7 computes by Lemma 2 with , as in Theorem 3. The same holds for , and . If the negative sign is the true one, line L6 returns , and , because they lie in the plane . So line L7 builds its frames from , , and the second half of the proof of Theorem 3 gives , and the same for . Also .
Corollary 5 (what the code returns from exact lines). Suppose no two beams are equal or opposite, the beams of some three images are linearly independent, and the common lines of all pairs are exact. Then rotations_from_common_lines returns for all , or for all , with one rotation .
Proof. For images , , , the two common lines and in image are parallel exactly when , that is, when one unit vector is orthogonal to , and , that is, when the three beams are linearly dependent. Line L4 picks the triple with the largest value of the smallest between the two common lines in each of its images. Some triple has independent beams and so a positive value, hence the chosen triple has a positive value and independent beams, and Theorem 4 places it. At each step of line L8, take any unplaced . Among the pairs of the anchor triple , , , at least one forms an independent triple with : if lay in the plane of every two of , , , it would lie in the intersection of the planes spanned by and by , which is the line of , so , against the hypothesis. So the largest found at line L8 is positive, its triple is independent, and Theorem 3 places with the same and the same . By induction every image gets . In floating point the code raises an error when the best value at line L4 or line L8 is below , instead of returning a meaningless answer.
Lemma 6 (the reflection cannot be resolved). Let . The images of at the rotations are the images of at the rotations .
Proof. .
So no method can tell the two answers of Corollary 5 apart from the images alone: the second one is the correct answer for the mirror image of the molecule, rotated by . The same lemma with a global rotation shows that cannot be fixed either: the images of at are the images of at . Corollary 5 and Lemma 6 together say that three or more images in general position fix the orientations exactly up to these two ambiguities. The function align_error measures the error after removing both. The tests check Corollary 5 on random rotations and the hand example of the page, Lemma 2, Lemma 6, and the error raised for single-axis tilts, where all beams lie in one plane.
Complexity
In the real-RAM model, let be the number of images, the image side, the number of sinogram angles and the number of bins. Line L1 builds one projector with entries and applies it to every image, . Line L2 compares lines with lines for each of the pairs, per pair (the per-iteration cost in the front matter) and in all; this is the main cost for small . Line L4 is . The code scans all unplaced images and all placed pairs at each of the steps of line L8, in total; keeping the best pair of each unplaced image and updating it when one image is placed makes it . Lines L5 to L7 and L9 are each. Memory is for the projector, for the sinograms and for the common lines. On the example above, one run takes about 0.5 s in pure Python (a measurement on a loaded machine).
Properties
- Exact on exact lines. With exact common lines and beams in general position, the output is exact up to a global rotation and the reflection (a theorem).
- Handedness open. The method returns one of two mirror solutions; the images cannot tell which is right (a theorem). The choice must come from other data, such as tilted pairs of images or known features of the reconstructed map.
- Needs at least three images. Two images fix only the angle between their beams and the common line, not the full relative rotation.
- No reference. The method needs no starting model, so it can give the first model of an unknown structure.
- Greedy. Each image uses only two common lines, so an error in one line passes to the images placed after it.
- Deterministic. The same images give the same output.
Variants and improvements
- Fourier-space search. The common line can be found by comparing central lines of the 2D Fourier transforms of the images, often with weights for each frequency, in place of the real-space line projections. By the slice theorem the two searches look for the same line.
- All common lines at once. Singer and Shkolnisky (2011) put the common lines of all pairs into one matrix whose top eigenvectors give all rotations together, and a semidefinite relaxation of the same least squares problem. These methods use every pair, so a few wrong lines do not spoil the result, and they can work at noise levels where the greedy method fails. The top eigenvectors come from power iteration or a Lanczos method.
- Voting. Each third image votes for the angle between two beams that its common lines imply; the most voted angle is used for each pair. This keeps the triangle step and reduces the effect of wrong lines.
- Refinement. The rough orientations become the start of a refinement by projection matching or by maximum likelihood, which uses the whole images and not only the common lines.
- Symmetric particles. For particles with point group symmetry, one image has common lines with itself, and the orientation of a single image can be found. Icosahedral viruses were an early use of this.
- Rotation averaging. The relative rotations from many triangles can be combined by rotation averaging, the same problem as in structure from motion.
When to use it
Use the common lines method when the orientations of projection images are unknown and no reference model exists, the images have a good signal-to-noise ratio (in cryo-EM, after averaging similar images into class averages), and the particle has no strong preferred orientation that puts all beams in one plane. When a reference model exists, matching the images against its projections is more robust. With raw noisy single images, use the global eigenvector or semidefinite methods, or a maximum likelihood method such as expectation maximization over the orientations.
Pitfalls
- Noise. The search for each line is a minimum over distances and breaks down quickly with noise. On the example above with Gaussian noise added to the pixels (three noise seeds per level, a measurement): with a standard deviation of 1 percent of the image peak, 30 of 30 lines are within 5 degrees and the rotations within 1.1 to 1.8 degrees; with 3 percent, 28 of 30 lines and rotations within 2.6 to 11.8 degrees; with 5 percent, 21 of 30 lines and errors of 36 to 74 degrees; with 10 percent, 7 of 30 lines and errors above 68 degrees. Raw cryo-EM images are far noisier than this.
- A badly shaped anchor triangle. If the beams of the three anchor images are nearly in one plane, or the two common lines inside an image are nearly parallel, the triangle step divides by a small number and small line errors become large rotation errors. With a fixed anchor (the first three images, and every other image placed from the first two), 20 random cases of the example type gave a median error of 10.9 degrees and a largest error of 108.6 degrees, with 4 cases above 20 degrees. With the choice of lines L4 and L8, the same cases gave a median of 3.5 degrees, a largest error of 19.6 degrees, and none above 20 degrees (a measurement).
- Beams in one plane. If all beams lie in one plane, as in a single-axis tilt series, every pair has the same common direction, the axis, and the rotations about the axis cannot be found (a theorem). The code raises an error in this case.
- The reversed line. The line at angle is the line at read in reverse. A search over that does not try the reversed lines finds the wrong line, or the right line with the wrong sign, for every pair whose match needs the reversal.
- Centering. A shift of an image shifts its line projections, by a different amount at each angle. The common-line identity holds only for centered images, so the images must be centered first.
- Comparing with the truth. An error measure must remove both the global rotation and the reflection. Comparing with directly reports large errors for correct answers.
Implementations
The Python code takes the images, the number of angles and the number of bins . It builds the sinograms with the pixel-driven projector of the shared helper imgkit, searches the common line of every pair with the parabola refinement, and then runs lines L4 to L9. It also has helpers for test data: random rotations from random unit quaternions, the exact projection of Gaussian blobs, and the exact common lines of two rotations. The tests check that commutes with rotations, that the exact common lines satisfy , the hand example, exact rotations from exact lines for 3, 4 and 8 images, that a global rotation does not change the lines, that the mirror object gives the same images, the error for coplanar beams and for fewer than 3 images, and the accuracy of the lines and the rotations found from the images of the example.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/common-lines-method/. The authors are listed in prov/41Z2MF.jsonl.
"""Orientations of projection images from their common lines (angular
reconstitution with a triangle of three images).
Model: image i is P_i(x, y) = int f(R_i (x, y, z)^T) dz for a 3D density f
and a rotation R_i. The columns of R_i are the image axes x, y and the beam
direction, written in the frame of the molecule.
Common lines: for images i and j with different beam directions, the unit
vector q along the cross product of the beam directions lies in both central
planes. In image i it is the direction c_ij = (R_i^T q)[0:2], in image j it is
c_ji = (R_j^T q)[0:2], and R_i [c_ij; 0] = R_j [c_ji; 0] = q. By the slice
theorem the 2D Fourier transforms of the images agree on these lines, and
equivalently the 1D projections of the images onto these directions agree
(both are the 3D Radon transform of f in the direction q). This code finds the
common lines in the sinograms of the images, then the rotations.
The answer is fixed only up to a global rotation and a reflection: the data
of (f, R_i) and of (f(J .), J R_i J) with J = diag(1, 1, -1) are equal. The
code gives the first image of its anchor triple the rotation I and picks the
mirror solution with a positive third coordinate of q_bc.
Images use the shared pixel convention: an n x n image covers [-1, 1]^2,
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n.
"""
import math
import imgkit as ik
# ------------------------------------------------------------------ 3x3 algebra
def matmul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
def transpose(a):
return [list(r) for r in zip(*a)]
def matvec(a, v):
return [sum(a[i][k] * v[k] for k in range(3)) for i in range(3)]
def cross(u, v):
return [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
def dot(u, v):
return sum(a * b for a, b in zip(u, v))
def unit(u):
r = math.sqrt(dot(u, u))
if r == 0:
raise ValueError("zero vector")
return [a / r for a in u]
def rotation_angle(a, b):
"""The angle of the rotation a^T b, in radians, from ||a - b||_F = 2 sqrt(2) sin(angle / 2)."""
d = math.sqrt(sum((a[i][k] - b[i][k]) ** 2 for i in range(3) for k in range(3)))
return 2 * math.asin(min(1.0, d / (2 * math.sqrt(2))))
def rotation_from_axis(axis, angle):
"""Rodrigues' formula."""
x, y, z = unit(axis)
c, s = math.cos(angle), math.sin(angle)
C = 1 - c
return [[c + x * x * C, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, c + y * y * C, y * z * C - x * s],
[z * x * C - y * s, z * y * C + x * s, c + z * z * C]]
def random_rotation(rng):
"""A rotation from a uniformly random unit quaternion."""
q = [rng.gauss(0, 1) for _ in range(4)]
w, x, y, z = unit(q)
return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
J = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]
# ------------------------------------------------------------------ test data
def project_gaussians(blobs, R, n):
"""The n x n image of int f(R (x, y, z)) dz for f = sum of w exp(-|x - c|^2 / (2 s^2)).
Each blob (w, c, s) projects to a 2D Gaussian with the center (R^T c)[0:2]
and the weight w s sqrt(2 pi), sampled at the pixel centers.
"""
xs, ys = ik.pixel_centers(n)
img = ik.new_image(n, n)
Rt = transpose(R)
for w, c, s in blobs:
m = matvec(Rt, c)
a = w * s * math.sqrt(2 * math.pi)
for i, y in enumerate(ys):
for j, x in enumerate(xs):
img[i][j] += a * math.exp(-((x - m[0]) ** 2 + (y - m[1]) ** 2) / (2 * s * s))
return img
def true_common_line(Ri, Rj):
"""(c_ij, c_ji) for the rotations of images i and j."""
q = unit(cross([r[2] for r in Ri], [r[2] for r in Rj]))
a, b = matvec(transpose(Ri), q), matvec(transpose(Rj), q)
return (a[0], a[1]), (b[0], b[1])
# ------------------------------------------------------------------ the method
def sinograms(images, L, nbins):
"""For each image, its line projections at the angles pi l / L, l = 0..L-1."""
n = len(images[0])
rows = ik.parallel_beam_matrix(n, [math.pi * l / L for l in range(L)], nbins)
out = []
for img in images:
v = ik.sp_matvec(rows, ik.flatten(img))
out.append([v[l * nbins:(l + 1) * nbins] for l in range(L)])
return out
def _line(S, a):
"""Line a of a sinogram for any integer a: the line at angle theta + pi is
the line at theta read in reverse, because the bins are symmetric."""
L = len(S)
v = S[a % L]
return v if (a // L) % 2 == 0 else v[::-1]
def _dist(u, v):
return sum((x - y) ** 2 for x, y in zip(u, v))
def _vertex(dm, d0, dp):
"""The offset in [-0.5, 0.5] of the vertex of the parabola through (-1, dm), (0, d0), (1, dp)."""
curv = dm - 2 * d0 + dp
if curv <= 0:
return 0.0
return max(-0.5, min(0.5, (dm - dp) / (2 * curv)))
def find_common_line(Si, Sj):
"""The best match of a line of Si with a line of Sj, read forward or reversed.
Returns (c_ij, c_ji, distance): c_ij = omega(alpha), and c_ji = omega(beta)
or -omega(beta) when the reversed line of Sj matches. The grid angles are
refined by a parabola through the distances at the two neighbors.
"""
L = len(Si)
both = list(Sj) + [v[::-1] for v in Sj] # line b + L is line b read in reverse
best = None
for a, u in enumerate(Si):
for b, v in enumerate(both):
d = _dist(u, v)
if best is None or d < best[0]:
best = (d, a, b)
d, a, b = best
u, v = Si[a], _line(Sj, b)
da = _vertex(_dist(_line(Si, a - 1), v), d, _dist(_line(Si, a + 1), v))
db = _vertex(_dist(u, _line(Sj, b - 1)), d, _dist(u, _line(Sj, b + 1)))
alpha, beta = math.pi * (a + da) / L, math.pi * (b + db) / L
return (math.cos(alpha), math.sin(alpha)), (math.cos(beta), math.sin(beta)), d
def frame(u, v):
"""The rotation with columns e1 = u/|u|, e2 = the part of v orthogonal to e1, e3 = e1 x e2."""
e1 = unit(u)
e2 = unit([b - dot(v, e1) * a for a, b in zip(e1, v)])
e3 = cross(e1, e2)
return [[e1[i], e2[i], e3[i]] for i in range(3)]
def _lift(c):
return [c[0], c[1], 0.0]
def _sin(c, d):
"""|sin| of the angle between two directions of an image."""
return abs(c[0] * d[1] - c[1] * d[0]) / (math.hypot(*c) * math.hypot(*d))
def _cos(c, d):
return (c[0] * d[0] + c[1] * d[1]) / (math.hypot(*c) * math.hypot(*d))
def triangle(cab, cac, cba, cbc, cca, ccb):
"""Rotations (I, R_b, R_c) of three images from their six common lines.
cab is the common line of images a and b seen in image a, and so on.
Of the two mirror solutions, the one with q_bc[2] > 0 is returned.
"""
q_ab, q_ac = _lift(cab), _lift(cac) # @line L5
cos_b, cos_c = _cos(cba, cbc), _cos(cca, ccb) # q_bc . q_ab and q_bc . q_ac
det = q_ab[0] * q_ac[1] - q_ab[1] * q_ac[0]
if abs(det) < 1e-12:
raise ValueError("the common lines of image a with images b and c coincide")
x = (cos_b * q_ac[1] - cos_c * q_ab[1]) / det
y = (q_ab[0] * cos_c - q_ac[0] * cos_b) / det
q_bc = [x, y, math.sqrt(max(0.0, 1 - x * x - y * y))] # @line L6
Rb = matmul(frame(q_ab, q_bc), transpose(frame(_lift(cba), _lift(cbc)))) # @line L7
Rc = matmul(frame(q_ac, q_bc), transpose(frame(_lift(cca), _lift(ccb))))
eye = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
return eye, Rb, Rc
def rotations_from_common_lines(c, N):
"""Rotations R_0..R_{N-1} from the common lines c[(i, j)] = c_ij of all pairs.
The anchor triple is the one whose worst in-image angle between its two
common lines is largest; it gets R = I for its first image. Then each
other image is placed from the two placed images whose common lines with
it are closest to perpendicular in it.
"""
best = None
for a in range(N): # @line L4
for b in range(N):
for d in range(b + 1, N):
if a in (b, d):
continue
s = min(_sin(c[(a, b)], c[(a, d)]), _sin(c[(b, a)], c[(b, d)]), _sin(c[(d, a)], c[(d, b)]))
if best is None or s > best[0]:
best = (s, a, b, d)
if best[0] < 1e-9:
raise ValueError("the beams of every three images lie in one plane")
_, a, b, d = best
R = [None] * N
R[a], R[b], R[d] = triangle(c[(a, b)], c[(a, d)], c[(b, a)], c[(b, d)], c[(d, a)], c[(d, b)])
while any(r is None for r in R): # @line L8
best = None
placed = [i for i in range(N) if R[i] is not None]
for k in range(N):
if R[k] is not None:
continue
for u in placed:
for v in placed:
if u < v:
s = _sin(c[(k, u)], c[(k, v)])
if best is None or s > best[0]:
best = (s, k, u, v)
if best[0] < 1e-9:
raise ValueError("no two placed images fix the next image")
_, k, u, v = best
qu, qv = matvec(R[u], _lift(c[(u, k)])), matvec(R[v], _lift(c[(v, k)]))
R[k] = matmul(frame(qu, qv), transpose(frame(_lift(c[(k, u)]), _lift(c[(k, v)])))) # @line L9
return R
def common_lines_method(images, L=60, nbins=23):
"""Estimate the rotations of N >= 3 projection images, up to a global
rotation and the reflection J."""
N = len(images)
if N < 3:
raise ValueError("need at least 3 images")
S = sinograms(images, L, nbins) # @line L1
c = {}
for i in range(N):
for j in range(i + 1, N):
cij, cji, _ = find_common_line(S[i], S[j]) # @line L2
c[(i, j)], c[(j, i)] = cij, cji # @line L3
return rotations_from_common_lines(c, N) # @line L10
def align_error(est, true):
"""The largest angle between est_0^T est_i and true_0^T true_i, for the
better of the two mirror solutions (as is, or conjugated by J)."""
e0, t0 = transpose(est[0]), transpose(true[0])
rel_e = [matmul(e0, R) for R in est]
rel_t = [matmul(t0, R) for R in true]
plain = max(rotation_angle(a, b) for a, b in zip(rel_e, rel_t))
mirrored = max(rotation_angle(a, matmul(J, matmul(b, J))) for a, b in zip(rel_e, rel_t))
return min(plain, mirrored)
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
test_common_lines_method.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/common-lines-method/. The authors are listed in prov/41Z2MF.jsonl.
import math
import random
import unittest
import common_lines_method as cl
DEG = math.pi / 180
def random_blobs(rng, m=6):
"""A density made of m Gaussian blobs (weight, center, width) inside the unit ball."""
return [(rng.uniform(0.5, 1.5), [rng.uniform(-0.45, 0.45) for _ in range(3)], rng.uniform(0.12, 0.2))
for _ in range(m)]
def exact_lines(Rs):
c = {}
for i in range(len(Rs)):
for j in range(i + 1, len(Rs)):
c[(i, j)], c[(j, i)] = cl.true_common_line(Rs[i], Rs[j])
return c
def line_error(est, true):
"""The angle between two common-line pairs (c_ij, c_ji), as lines with one shared sign."""
def ang(u, v):
return math.acos(max(-1.0, min(1.0, (u[0] * v[0] + u[1] * v[1]) / math.hypot(*u) / math.hypot(*v))))
plain = max(ang(est[0], true[0]), ang(est[1], true[1]))
flipped = max(ang(est[0], (-true[0][0], -true[0][1])), ang(est[1], (-true[1][0], -true[1][1])))
return min(plain, flipped)
_CASE = {}
def image_case():
"""Five 32 x 32 projections of a random density, their sinograms and detected common lines."""
if not _CASE:
rng = random.Random(1)
blobs = random_blobs(rng)
Rs = [cl.random_rotation(rng) for _ in range(5)]
images = [cl.project_gaussians(blobs, R, 32) for R in Rs]
S = cl.sinograms(images, 60, 23)
c = {}
for i in range(5):
for j in range(i + 1, 5):
c[(i, j)], c[(j, i)], _ = cl.find_common_line(S[i], S[j])
_CASE.update(Rs=Rs, images=images, c=c)
return _CASE
class TestAlgebra(unittest.TestCase):
def test_rotations_and_frame_equivariance(self):
rng = random.Random(7)
eye = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
for _ in range(20):
R = cl.random_rotation(rng)
self.assertLess(cl.rotation_angle(cl.matmul(cl.transpose(R), R), eye), 1e-12)
u = [rng.gauss(0, 1) for _ in range(3)]
v = [rng.gauss(0, 1) for _ in range(3)]
F = cl.frame(u, v)
self.assertLess(cl.rotation_angle(cl.matmul(cl.transpose(F), F), eye), 1e-12)
lhs = cl.frame(cl.matvec(R, u), cl.matvec(R, v))
self.assertLess(cl.rotation_angle(lhs, cl.matmul(R, F)), 1e-12)
axis, angle = [1.0, 2.0, -0.5], 0.7
self.assertAlmostEqual(cl.rotation_angle(cl.rotation_from_axis(axis, angle), eye), angle, places=12)
def test_true_common_line_is_shared(self):
rng = random.Random(3)
for _ in range(20):
Ri, Rj = cl.random_rotation(rng), cl.random_rotation(rng)
cij, cji = cl.true_common_line(Ri, Rj)
self.assertAlmostEqual(math.hypot(*cij), 1.0, places=12)
qi = cl.matvec(Ri, [cij[0], cij[1], 0.0])
qj = cl.matvec(Rj, [cji[0], cji[1], 0.0])
for a, b in zip(qi, qj):
self.assertAlmostEqual(a, b, places=12)
class TestExactLines(unittest.TestCase):
def test_hand_example(self):
# R_1 = I, R_2 = 90 degrees about x, R_3 = 90 degrees about y (the example of the page).
c = {(0, 1): (1.0, 0.0), (1, 0): (1.0, 0.0), (0, 2): (0.0, 1.0), (2, 0): (0.0, 1.0),
(1, 2): (0.0, 1.0), (2, 1): (-1.0, 0.0)}
R = cl.rotations_from_common_lines(c, 3)
want = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 0, -1], [0, 1, 0]], [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]]
for got, w in zip(R, want):
for rg, rw in zip(got, w):
for x, y in zip(rg, rw):
self.assertAlmostEqual(x, y, places=14)
Rx, Ry = want[1], want[2]
self.assertEqual(cl.true_common_line(want[0], Rx), ((1.0, 0.0), (1.0, 0.0)))
for (i, j), v in (((1, 2), cl.true_common_line(Rx, Ry)[0]), ((2, 1), cl.true_common_line(Rx, Ry)[1])):
self.assertAlmostEqual(v[0], c[(i, j)][0], places=14)
self.assertAlmostEqual(v[1], c[(i, j)][1], places=14)
def test_coplanar_beams_are_rejected(self):
# Single-axis tilts about x: every pair of images has the same common line.
Rs = [cl.rotation_from_axis([1.0, 0.0, 0.0], t) for t in (0.3, 1.0, 1.9, 2.5)]
with self.assertRaises(ValueError):
cl.rotations_from_common_lines(exact_lines(Rs), 4)
def test_exact_lines_give_exact_rotations(self):
rng = random.Random(11)
for N in (3, 4, 8):
Rs = [cl.random_rotation(rng) for _ in range(N)]
est = cl.rotations_from_common_lines(exact_lines(Rs), N)
self.assertLess(cl.align_error(est, Rs), 1e-9)
def test_global_rotation_does_not_change_lines(self):
rng = random.Random(12)
Rs = [cl.random_rotation(rng) for _ in range(4)]
G = cl.random_rotation(rng)
a, b = exact_lines(Rs), exact_lines([cl.matmul(G, R) for R in Rs])
for key in a:
for x, y in zip(a[key], b[key]):
self.assertAlmostEqual(x, y, places=12)
def test_reflection_gives_the_same_images(self):
rng = random.Random(5)
blobs = random_blobs(rng, 3)
mirror = [(w, [c[0], c[1], -c[2]], s) for w, c, s in blobs]
for _ in range(3):
R = cl.random_rotation(rng)
JRJ = cl.matmul(cl.J, cl.matmul(R, cl.J))
a, b = cl.project_gaussians(blobs, R, 12), cl.project_gaussians(mirror, JRJ, 12)
self.assertLess(max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb)), 1e-12)
# The mirrored rotations are a different solution, not a global rotation of the first.
Rs = [cl.random_rotation(rng) for _ in range(4)]
mirrored = [cl.matmul(cl.J, cl.matmul(R, cl.J)) for R in Rs]
rel = lambda X: [cl.matmul(cl.transpose(X[0]), R) for R in X]
far = max(cl.rotation_angle(x, y) for x, y in zip(rel(Rs), rel(mirrored)))
self.assertGreater(far, 0.1)
self.assertLess(cl.align_error(mirrored, Rs), 1e-9)
def test_needs_three_images(self):
with self.assertRaises(ValueError):
cl.common_lines_method([cl.project_gaussians([(1.0, [0, 0, 0], 0.2)], cl.J, 8)] * 2)
class TestImages(unittest.TestCase):
def test_detected_lines_are_close(self):
case = image_case()
Rs, c = case["Rs"], case["c"]
for i in range(5):
for j in range(i + 1, 5):
err = line_error((c[(i, j)], c[(j, i)]), cl.true_common_line(Rs[i], Rs[j]))
self.assertLess(err, 4 * DEG)
def test_orientations_from_images(self):
case = image_case()
est = cl.rotations_from_common_lines(case["c"], 5)
self.assertLess(cl.align_error(est, case["Rs"]), 5 * DEG)
def test_full_method_on_three_images(self):
case = image_case()
est = cl.common_lines_method(case["images"][:3])
self.assertLess(cl.align_error(est, case["Rs"][:3]), 6 * DEG)
if __name__ == "__main__":
unittest.main()
History
Crowther, DeRosier and Klug (1970) set out the reconstruction of a 3D structure from electron micrographs through central sections of its Fourier transform, and the common lines between central sections were used to find the orientations of images of symmetric virus particles. Van Heel (1987) gave angular reconstitution, which assigns the projection directions of images of an asymmetric particle a posteriori from their common lines, found in the sinograms of the images. Frank's book (2006) describes the method in the context of single-particle cryo-EM. Singer and Shkolnisky (2011) replaced the triangle steps by an eigenvector method and a semidefinite relaxation that use all common lines at once.
References
- R. A. Crowther, D. J. DeRosier and A. Klug, The reconstruction of a three-dimensional structure from projections and its application to electron microscopy, Proceedings of the Royal Society of London A 317(1530), 1970, pp. 319 to 340 (reconstruction from projections through central sections of the Fourier transform; general locator, section not confirmed)
- M. van Heel, Angular reconstitution, a posteriori assignment of projection directions for 3D reconstruction, Ultramicroscopy 21(2), 1987, pp. 111 to 123 (the orientations of unknown projections from their common lines)
- A. Singer and Y. Shkolnisky, Three-dimensional structure determination from common lines in cryo-EM by eigenvectors and semidefinite programming, SIAM Journal on Imaging Sciences 4(2), 2011, pp. 543 to 572 (all common lines at once, by an eigenvector method and by a semidefinite relaxation)
- J. Frank, Three-Dimensional Electron Microscopy of Macromolecular Assemblies, Oxford University Press, 2006, general locator (the single-particle methods, angular reconstitution among them)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 41Z2MF Edit this page History Report an error Markdown