Algorithm Search⌘K

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
Properties
deterministicexact on exact linesnot handedness resolvednot in placenot iterativeneeds three imagesiterative
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 ff on R3\mathbb{R}^3 and there are m≥3m \ge 3 unknown rotations R1,…,RmR_1, \dots, R_m. The input is the images

Pi(x,y)=∫f(Ri(x,y,z)T) dz,i=1,…,m,P_i(x, y) = \int f\big(R_i (x, y, z)^T\big)\, dz, \qquad i = 1, \dots, m,

sampled on n×nn \times n grids. The columns of RiR_i are the image axes and the beam direction νi=Rie3\nu_i = R_i e_3, written in the frame of the object. An n×nn \times n image covers [−1,1]2[-1, 1]^2, with the pixel centers xj=−1+(2j+1)/nx_j = -1 + (2j+1)/n and yi=1−(2i+1)/ny_i = 1 - (2i+1)/n; the images must be centered, so that the origin of the object projects to the center of every image. The output is rotations R^1,…,R^m\hat R_1, \dots, \hat R_m with R^iTR^j=RiTRj\hat R_i^T \hat R_j = R_i^T R_j for all pairs, or the same with every RiR_i replaced by JRiJJ R_i J, where J=diag(1,1,−1)J = \mathrm{diag}(1, 1, -1).

Common lines. For a unit vector cc in the image plane, let pi(c,s)=∫Pi(sc+tc⊥) dtp_i(c, s) = \int P_i(s c + t c^\perp)\, dt be the line projection of image ii in the direction cc, one line of its sinogram. If νi≠±νj\nu_i \ne \pm \nu_j, the unit vector qq along νi×νj\nu_i \times \nu_j lies in both central planes. In the coordinates of image ii it is the direction cij=(RiTq)1,2c_{ij} = (R_i^T q)_{1,2}, and in image jj it is cji=(RjTq)1,2c_{ji} = (R_j^T q)_{1,2}. Then

pi(cij,s)=pj(cji,s)for all s,p_i(c_{ij}, s) = p_j(c_{ji}, s) \quad \text{for all } s,

because both sides are the integral of ff over the plane {x:x⋅q=s}\{x : x \cdot q = s\}, that is the 3D Radon transform of ff at (q,s)(q, s) (a theorem, proved in the correctness proof). In Fourier space, with Fg(ξ)=∫g(x)e−2πix⋅ξ dx\mathcal{F} g(\xi) = \int g(x) e^{-2\pi i x \cdot \xi}\, dx, the 1D transform of this line projection is Ff\mathcal{F} f on the line through the origin in the direction qq. A line in the direction −c-c is the line in the direction cc read in reverse, so a search over the angles [0,π)[0, \pi) must also try each line of the second image reversed.

The algorithm

FRAME(u,v)\mathrm{FRAME}(u, v) is the rotation with the columns u/∣u∣u/|u|, the unit vector along the part of vv orthogonal to uu, and the cross product of these two. A 2D direction cc is used as the 3D vector (c1,c2,0)(c_1, c_2, 0). The angle ω(α)\omega(\alpha) is the direction (cos⁡α,sin⁡α)(\cos\alpha, \sin\alpha).

  1. COMMON-LINES(P_1..P_m, a)
  2. 1S_i ← the line projections of P_i at the angles πl/a, l = 0..a-1, for each i
  3. 2for 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
  4. 3c_ij ← ω(α); c_ji ← ω(β), or -ω(β) for a reversed match
  5. 4pick the triple (r, b, d) whose smallest |sin| between the two common lines in any of its three images is largest
  6. 5q_rb ← c_rb; q_rd ← c_rd ▷ R_r = I
  7. 6q_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
  8. 7R_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
  9. 8while some image has no rotation, pick an unplaced k and placed u, v with the largest |sin| between c_ku and c_kv
  10. 9R_k ← FRAME(R_u c_uk, R_v c_vk) FRAME(c_ku, c_kv)^T
  11. 10return R_1..R_m

Line L6 is the triangle step. In the frame of image rr, the common directions qrbq_{rb} and qrdq_{rd} lie in the plane z=0z = 0, and the unknown qbdq_{bd} has known dot products with both, because the angle between two common lines inside image bb is the angle between the corresponding directions in space. Two linear equations give the first two coordinates of qbdq_{bd}, 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 ckuc_{ku}, ckvc_{kv} of image kk to their known places RucukR_u c_{uk}, RvcvkR_v c_{vk} in space; a rotation is fixed by where it sends two independent vectors.

Example

By hand. Take R1=IR_1 = I, R2R_2 the rotation by 90 degrees about the xx axis, and R3R_3 the rotation by 90 degrees about the yy axis. The beams are ν1=e3\nu_1 = e_3, ν2=(0,−1,0)\nu_2 = (0, -1, 0) and ν3=(1,0,0)\nu_3 = (1, 0, 0). The common directions are q12=e1q_{12} = e_1, q13=e2q_{13} = e_2 and q23=e3q_{23} = e_3. In the images they are c12=(1,0)c_{12} = (1, 0), c21=(1,0)c_{21} = (1, 0), c13=(0,1)c_{13} = (0, 1), c31=(0,1)c_{31} = (0, 1), c23=(0,1)c_{23} = (0, 1) and c32=(−1,0)c_{32} = (-1, 0). Line L5 gives q12=e1q_{12} = e_1 and q13=e2q_{13} = e_2. In line L6, c21⋅c23=0c_{21} \cdot c_{23} = 0 and c31⋅c32=0c_{31} \cdot c_{32} = 0, so q23q_{23} is orthogonal to e1e_1 and e2e_2, and the positive sign gives q23=e3q_{23} = e_3. Line L7 gives

R2=FRAME(e1,e3) FRAME(e1,e2)T=[e1,e3,−e2]=(10000−1010),R_2 = \mathrm{FRAME}(e_1, e_3)\, \mathrm{FRAME}(e_1, e_2)^T = [e_1, e_3, -e_2] = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & 1 & 0 \end{pmatrix},

the true rotation about xx, and in the same way R3=FRAME(e2,e3) FRAME(e2,−e1)TR_3 = \mathrm{FRAME}(e_2, e_3)\, \mathrm{FRAME}(e_2, -e_1)^T, the true rotation about yy. The negative sign would give JR2JJ R_2 J and JR3JJ R_3 J, 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 [−0.45,0.45]3[-0.45, 0.45]^3 and widths from 0.12 to 0.2, and 5 random rotations (seed 1). Each image is 32×3232 \times 32, with a=60a = 60 angles (3 degree steps) and d=23d = 23 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 10−1510^{-15} 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 R^i=GRi\hat R_i = G R_i for all ii or R^i=JGRiJ\hat R_i = J G R_i J for all ii, with one rotation GG (a theorem). The key facts are that FRAME(Tu,Tv)=T FRAME(u,v)\mathrm{FRAME}(T u, T v) = T\, \mathrm{FRAME}(u, v) for a rotation TT, and FRAME(Ju,Jv)=J FRAME(u,v) J\mathrm{FRAME}(J u, J v) = J\, \mathrm{FRAME}(u, v)\, J. The proof also shows that the reflection cannot be resolved from the images: the images of f(Jx)f(J x) at the rotations JRiJJ R_i J are the images of ff at RiR_i. 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. ff is an integrable density on R3\mathbb{R}^3, R1,…,RmR_1, \dots, R_m are rotations, and image ii is Pi(x,y)=∫f(Ri(x,y,z)T) dzP_i(x, y) = \int f(R_i (x, y, z)^T)\, dz. The columns of RiR_i are the image axes and the beam direction νi=Rie3\nu_i = R_i e_3. For a unit vector cc in the image plane, pi(c,s)=∫Pi(sc+tc⊥) dtp_i(c, s) = \int P_i(s c + t c^\perp)\, dt is the line projection of image ii in the direction cc, where c⊥c^\perp is cc turned by 90 degrees; this is one line of the sinogram of PiP_i. We write c^=(c1,c2,0)T\hat c = (c_1, c_2, 0)^T, and Rf(ω,s)=∫x⋅ω=sf dA\mathcal{R} f(\omega, s) = \int_{x \cdot \omega = s} f\, dA for the 3D Radon transform (integrals over planes).

The code only finds the common lines approximately, on a grid of aa 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 νi≠±νj\nu_i \ne \pm \nu_j, let q=(νi×νj)/∣νi×νj∣q = (\nu_i \times \nu_j)/|\nu_i \times \nu_j|, cij=(RiTq)1,2c_{ij} = (R_i^T q)_{1,2} and cji=(RjTq)1,2c_{ji} = (R_j^T q)_{1,2}. Then cijc_{ij} and cjic_{ji} are unit vectors, Ric^ij=Rjc^ji=qR_i \hat c_{ij} = R_j \hat c_{ji} = q, and

pi(cij,s)=pj(cji,s)=Rf(q,s)for all s.p_i(c_{ij}, s) = p_j(c_{ji}, s) = \mathcal{R} f(q, s) \quad \text{for all } s.

Also pi(−c,s)=pi(c,−s)p_i(-c, s) = p_i(c, -s), so the line of image jj in the direction −cji-c_{ji} is the line in the direction cjic_{ji} read in reverse.

Proof. The third coordinate of RiTqR_i^T q is νi⋅q=0\nu_i \cdot q = 0, so RiTq=c^ijR_i^T q = \hat c_{ij}, ∣cij∣=∣q∣=1|c_{ij}| = |q| = 1 and Ric^ij=qR_i \hat c_{ij} = q; the same holds for jj. For a unit cc in the image plane, the vectors c^\hat c, c^⊥\hat c^\perp and e3e_3 are an orthonormal basis, and RiR_i maps it to the orthonormal basis Ric^R_i \hat c, Ric^⊥R_i \hat c^\perp, νi\nu_i. So

pi(c,s)=∬f(sRic^+tRic^⊥+z νi) dt dz=Rf(Ric^,s),p_i(c, s) = \iint f\big(s R_i \hat c + t R_i \hat c^\perp + z\, \nu_i\big)\, dt\, dz = \mathcal{R} f(R_i \hat c, s),

because (t,z)↦sRic^+tRic^⊥+zνi(t, z) \mapsto s R_i \hat c + t R_i \hat c^\perp + z \nu_i is an isometry onto the plane {x:x⋅Ric^=s}\{x : x \cdot R_i \hat c = s\}. With c=cijc = c_{ij} this is Rf(q,s)\mathcal{R} f(q, s), and the same computation in image jj gives the same value. The last claim is the change t↦−tt \mapsto -t, since (−c)⊥=−c⊥(-c)^\perp = -c^\perp. □\square

By the Fourier slice theorem, with the convention Fg(ξ)=∫g(x)e−2πix⋅ξ dx\mathcal{F} g(\xi) = \int g(x) e^{-2\pi i x \cdot \xi}\, dx, the 1D transform of s↦Rf(q,s)s \mapsto \mathcal{R} f(q, s) is ρ↦Ff(ρq)\rho \mapsto \mathcal{F} f(\rho q), so Lemma 1 says the same thing in Fourier space: the 2D transforms of PiP_i and PjP_j agree on the central lines in the directions cijc_{ij} and cjic_{ji}, which are the two images of the line where the central planes νi⊥\nu_i^\perp and νj⊥\nu_j^\perp meet.

Lemma 2 (frames). For linearly independent u,v∈R3u, v \in \mathbb{R}^3, FRAME(u,v)\mathrm{FRAME}(u, v) is the matrix with the columns e1=u/∣u∣e_1 = u/|u|, $e_2 = $ the unit vector along v−(v⋅e1)e1v - (v \cdot e_1) e_1, and e3=e1×e2e_3 = e_1 \times e_2. It is a rotation. For every rotation TT, FRAME(Tu,Tv)=T FRAME(u,v)\mathrm{FRAME}(Tu, Tv) = T\, \mathrm{FRAME}(u, v). For the reflection J=diag(1,1,−1)J = \mathrm{diag}(1, 1, -1), FRAME(Ju,Jv)=J FRAME(u,v) J\mathrm{FRAME}(Ju, Jv) = J\, \mathrm{FRAME}(u, v)\, J.

Proof. The columns are orthonormal by construction and e3=e1×e2e_3 = e_1 \times e_2, so the determinant is +1+1. An orthogonal TT keeps lengths and dot products, so the first two columns of FRAME(Tu,Tv)\mathrm{FRAME}(Tu, Tv) are Te1T e_1 and Te2T e_2. For any orthogonal TT, Ta×Tb=det⁡(T) T(a×b)Ta \times Tb = \det(T)\, T(a \times b). For a rotation the third column is Te3T e_3. For JJ, with det⁡J=−1\det J = -1, it is −Je3-J e_3, and changing the sign of the third column is multiplication by JJ on the right. □\square

Theorem 3 (placing one image, line L9). Let GG be a rotation and let ϵ\epsilon be either the identity or the map X↦JXJX \mapsto J X J. Suppose the placed images uu and vv have R^u=ϵ(GRu)\hat R_u = \epsilon(G R_u) and R^v=ϵ(GRv)\hat R_v = \epsilon(G R_v), the common lines are exact, and the beams νk\nu_k, νu\nu_u, νv\nu_v are linearly independent. Then

R^k=FRAME(R^uc^uk,R^vc^vk) FRAME(c^ku,c^kv)T=ϵ(GRk).\hat R_k = \mathrm{FRAME}(\hat R_u \hat c_{uk}, \hat R_v \hat c_{vk})\, \mathrm{FRAME}(\hat c_{ku}, \hat c_{kv})^T = \epsilon(G R_k).

Proof. Let quk=Ruc^uk=Rkc^kuq_{uk} = R_u \hat c_{uk} = R_k \hat c_{ku} and qvk=Rvc^vk=Rkc^kvq_{vk} = R_v \hat c_{vk} = R_k \hat c_{kv} (Lemma 1). They are not parallel: a vector parallel to both would be orthogonal to νk\nu_k, νu\nu_u and νv\nu_v, which span R3\mathbb{R}^3. Write F=FRAME(c^ku,c^kv)F = \mathrm{FRAME}(\hat c_{ku}, \hat c_{kv}). Take first ϵ\epsilon the identity. Then R^uc^uk=Gquk=GRkc^ku\hat R_u \hat c_{uk} = G q_{uk} = G R_k \hat c_{ku}, and in the same way R^vc^vk=GRkc^kv\hat R_v \hat c_{vk} = G R_k \hat c_{kv}. By Lemma 2 with T=GRkT = G R_k, the first frame is GRkFG R_k F, and R^k=GRkFFT=GRk\hat R_k = G R_k F F^T = G R_k. For ϵ(X)=JXJ\epsilon(X) = J X J, use Jc^=c^J \hat c = \hat c for vectors in the image plane: R^uc^uk=JGRuJc^uk=JGquk\hat R_u \hat c_{uk} = J G R_u J \hat c_{uk} = J G q_{uk}, and the same for vv. By Lemma 2 (both parts) the first frame is J GRkF JJ\, G R_k F\, J. The first two columns of FF lie in the image plane and the third is ±e3\pm e_3, so FJFTF J F^T is the reflection in the image plane, which is JJ. So R^k=JGRkFJFT=JGRkJ\hat R_k = J G R_k F J F^T = J G R_k J. □\square

Theorem 4 (the anchor triangle, lines L5 to L7). Let images aa, bb, dd have linearly independent beams and exact common lines. Lines L5 to L7 return R^a=I\hat R_a = I and R^b\hat R_b, R^d\hat R_d with

R^i=GRi  for i∈{a,b,d},orR^i=JGRiJ  for i∈{a,b,d},\hat R_i = G R_i \ \text{ for } i \in \{a, b, d\}, \qquad \text{or} \qquad \hat R_i = J G R_i J \ \text{ for } i \in \{a, b, d\},

where G=RaTG = R_a^T. The first case holds when the third coordinate of GqbdG q_{bd} is positive, the second when it is negative, and it is never zero.

Proof. Put qxy′=Gqxyq'_{xy} = G q_{xy} for the three common directions qabq_{ab}, qadq_{ad}, qbdq_{bd} of Lemma 1. By Lemma 1, qab′=RaTRac^ab=c^abq'_{ab} = R_a^T R_a \hat c_{ab} = \hat c_{ab} and qad′=c^adq'_{ad} = \hat c_{ad}, which is line L5. They are not parallel, by the argument of Theorem 3, so the 2×22 \times 2 determinant in the code is not zero. The unknown qbd′q'_{bd} is a unit vector with

qbd′⋅qab′=qbd⋅qab=Rbc^bd⋅Rbc^ba=cbd⋅cba,qbd′⋅qad′=cdb⋅cda.q'_{bd} \cdot q'_{ab} = q_{bd} \cdot q_{ab} = R_b \hat c_{bd} \cdot R_b \hat c_{ba} = c_{bd} \cdot c_{ba}, \qquad q'_{bd} \cdot q'_{ad} = c_{db} \cdot c_{da}.

Since qab′q'_{ab} and qad′q'_{ad} span the plane z=0z = 0, these two equations fix the first two coordinates (x,y)(x, y) of qbd′q'_{bd}, and ∣qbd′∣=1|q'_{bd}| = 1 fixes the third up to its sign, ±1−x2−y2\pm\sqrt{1 - x^2 - y^2}. The third coordinate is qbd′⋅e3=Gqbd⋅Gνa=qbd⋅νaq'_{bd} \cdot e_3 = G q_{bd} \cdot G \nu_a = q_{bd} \cdot \nu_a, which is not zero, because qbdq_{bd} is orthogonal to νb\nu_b and νd\nu_d, 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 qbd′q'_{bd}, and line L7 computes R^b=FRAME(Gqab,Gqbd) FRAME(c^ba,c^bd)T=GRb\hat R_b = \mathrm{FRAME}(G q_{ab}, G q_{bd})\, \mathrm{FRAME}(\hat c_{ba}, \hat c_{bd})^T = G R_b by Lemma 2 with T=GRbT = G R_b, as in Theorem 3. The same holds for dd, and R^a=I=GRa\hat R_a = I = G R_a. If the negative sign is the true one, line L6 returns Jqbd′J q'_{bd}, and qab′=Jqab′q'_{ab} = J q'_{ab}, qad′=Jqad′q'_{ad} = J q'_{ad} because they lie in the plane z=0z = 0. So line L7 builds its frames from JGqabJ G q_{ab}, JGqbdJ G q_{bd}, and the second half of the proof of Theorem 3 gives R^b=JGRbJ\hat R_b = J G R_b J, and the same for dd. Also I=JGRaJI = J G R_a J. □\square

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 R^i=GRi\hat R_i = G R_i for all ii, or R^i=JGRiJ\hat R_i = J G R_i J for all ii, with one rotation GG.

Proof. For images kk, uu, vv, the two common lines ckuc_{ku} and ckvc_{kv} in image kk are parallel exactly when qku∥qkvq_{ku} \parallel q_{kv}, that is, when one unit vector is orthogonal to νk\nu_k, νu\nu_u and νv\nu_v, that is, when the three beams are linearly dependent. Line L4 picks the triple with the largest value of the smallest ∣sin⁡∣|\sin| 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 kk. Among the pairs of the anchor triple aa, bb, dd, at least one forms an independent triple with νk\nu_k: if νk\nu_k lay in the plane of every two of νa\nu_a, νb\nu_b, νd\nu_d, it would lie in the intersection of the planes spanned by νa,νb\nu_a, \nu_b and by νa,νd\nu_a, \nu_d, which is the line of νa\nu_a, so νk=±νa\nu_k = \pm \nu_a, against the hypothesis. So the largest ∣sin⁡∣|\sin| found at line L8 is positive, its triple is independent, and Theorem 3 places kk with the same GG and the same ϵ\epsilon. By induction every image gets ϵ(GRi)\epsilon(G R_i). In floating point the code raises an error when the best value at line L4 or line L8 is below 10−910^{-9}, instead of returning a meaningless answer. □\square

Lemma 6 (the reflection cannot be resolved). Let fJ(x)=f(Jx)f_J(x) = f(J x). The images of fJf_J at the rotations JRiJJ R_i J are the images of ff at the rotations RiR_i.

Proof. ∫fJ(JRiJ(x,y,z)T) dz=∫f(Ri(x,y,−z)T) dz=Pi(x,y)\int f_J(J R_i J (x, y, z)^T)\, dz = \int f(R_i (x, y, -z)^T)\, dz = P_i(x, y). □\square

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 fJf_J of the molecule, rotated by JGJJ G J. The same lemma with a global rotation shows that GG cannot be fixed either: the images of f(GT⋅)f(G^T \cdot) at GRiG R_i are the images of ff at RiR_i. 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 mm be the number of images, nn the image side, aa the number of sinogram angles and dd the number of bins. Line L1 builds one projector with O(an2)O(a n^2) entries and applies it to every image, O(man2)O(m a n^2). Line L2 compares aa lines with 2a2a lines for each of the m(m−1)/2m(m-1)/2 pairs, O(a2d)O(a^2 d) per pair (the per-iteration cost in the front matter) and O(m2a2d)O(m^2 a^2 d) in all; this is the main cost for small mm. Line L4 is O(m3)O(m^3). The code scans all unplaced images and all placed pairs at each of the mm steps of line L8, O(m4)O(m^4) in total; keeping the best pair of each unplaced image and updating it when one image is placed makes it O(m3)O(m^3). Lines L5 to L7 and L9 are O(1)O(1) each. Memory is O(an2)O(a n^2) for the projector, O(mad)O(m a d) for the sinograms and O(m2)O(m^2) 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 2a22a^2 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 α+π\alpha + \pi is the line at α\alpha read in reverse. A search over [0,π)[0, \pi) 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 R^i\hat R_i with RiR_i directly reports large errors for correct answers.

Implementations

The Python code takes the images, the number of angles aa and the number of bins dd. 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 FRAME\mathrm{FRAME} commutes with rotations, that the exact common lines satisfy Ricij=RjcjiR_i c_{ij} = R_j c_{ji}, 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.

common_lines_method.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_iteration
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example