Algorithm Search⌘K

Algorithmadvanced

SALSA

Also called stochastic approach for link-structure analysis.

Scores hubs and authorities of a query subgraph by two random walks on its bipartite hub-authority graph; the scores reduce to degrees weighted by component size.

Time
O(n + m) worst
Space
O(n + m) extra
Where
m = the number of links among them; n = the number of pages in the base set
Properties
deterministicdirectediterativenot weighted
Origin
Ronny Lempel, Shlomo Moran, 2000

SALSA (the stochastic approach for link-structure analysis) is a link analysis algorithm that gives each page of a small query graph a hub score and an authority score, as the stationary distributions of two random walks on the bipartite graph of hubs and authorities. Ronny Lempel and Shlomo Moran introduced it in 2000 as a stochastic form of HITS. Their analysis shows that the scores need no iteration at all: inside each connected component, the authority score of a page is proportional to its in-degree, and the component as a whole gets a weight proportional to its number of authorities. Because each vote is divided by the degrees, a tightly knit block of pages cannot take all the weight, as it does in HITS.

In plain words

Search engines first collect a small set of pages about a query, with the pages that link to them and the pages they link to. Some pages are good lists of links (hubs) and some are good sources (authorities). SALSA imagines a walker who stands on a source page, goes back along a random link to a page that points to it, and then forward along a random link of that list. The fraction of time the walker spends on a page is its authority score. A second walker does the same with the roles of lists and sources swapped. When all the pages are joined together, the time spent on a source turns out to depend only on how many pages point to it. When the graph falls into separate parts, each part gets a share that depends on its size.

The problem

The input is the base set of a query: a directed graph G=(V,E)G = (V, E) on nn pages with mm links, built as for HITS from a root set of pages that match the query, plus the pages that link to the root set and the pages that the root set links to. Self links are removed and repeated links count once. Write in(p)\mathrm{in}(p) and out(q)\mathrm{out}(q) for the degrees. The hub side is H={q:out(q)>0}H = \{q : \mathrm{out}(q) > 0\} and the authority side is A={p:in(p)>0}A = \{p : \mathrm{in}(p) > 0\}; a page can be on both sides. The bipartite graph G~\tilde G has an edge between hub qq and authority pp for each link (q,p)(q, p).

The authority chain on AA moves from authority ii to a random hub qq that links to ii, then to a random authority jj that qq links to:

PA(i,j)=∑q: (q,i)∈E, (q,j)∈E1in(i) out(q).P_A(i, j) = \sum_{q :\ (q, i) \in E,\ (q, j) \in E} \frac{1}{\mathrm{in}(i)\, \mathrm{out}(q)}.

The hub chain on HH is the same with the roles swapped: PH(q,r)=∑p: (q,p)∈E, (r,p)∈E1/(out(q) in(p))P_H(q, r) = \sum_{p :\ (q, p) \in E,\ (r, p) \in E} 1 / (\mathrm{out}(q)\, \mathrm{in}(p)). The output is the authority vector a=lim⁡kuAPAka = \lim_k u_A P_A^k and the hub vector h=lim⁡kuHPHkh = \lim_k u_H P_H^k, where uAu_A and uHu_H are the uniform distributions on AA and HH. In matrix form, with WrW_r the adjacency matrix with each row divided by its sum and WcW_c the adjacency matrix with each column divided by its sum, PAP_A is the part of Wc⊤WrW_c^\top W_r on the authority rows and columns, and PHP_H is the part of WrWc⊤W_r W_c^\top on the hub rows and columns. HITS uses W⊤WW^\top W and WW⊤W W^\top with no division.

The algorithm

The closed form of Lempel and Moran turns the definition into a count. Let G~\tilde G have components cc with authority sets AcA_c, hub sets HcH_c and mcm_c links.

  1. SALSA(G) ▷ G = (V, E), the base set of a query
  2. 1E ← E without self links and repeated links
  3. 2H ← {q : out(q) > 0}; A ← {p : in(p) > 0}
  4. 3label the connected components of the undirected bipartite graph G̃
  5. 4for each component c: count |H_c|, |A_c| and m_c = |E_c|
  6. 5for each p ∈ A in component c: a(p) ← (|A_c| / |A|) · in(p) / m_c
  7. 6for each q ∈ H in component c: h(q) ← (|H_c| / |H|) · out(q) / m_c
  8. 7return h, a

Pages ranked by aa (or by hh) go highest first, with ties to the smaller page number. The definition can also be run as written, by power iteration of the two chains from the uniform start. Each step costs O(m)O(m): spread the mass of each authority over the hubs that link to it, then the mass of each hub over its links. The test file runs both and checks that they agree.

Example

Take twelve pages. Hubs 0 to 3 each link to authorities 9 and 10, hubs 4 to 8 each link to authority 11, and hub 0 also links to 11. So m=14m = 14, in(9)=in(10)=4\mathrm{in}(9) = \mathrm{in}(10) = 4 and in(11)=6\mathrm{in}(11) = 6, and G~\tilde G is connected through hub 0. From authority 11 the walker goes back to one of its six hubs; only hub 0 can send it to 9 or 10, so PA(11,9)=PA(11,10)=16⋅13=118P_A(11, 9) = P_A(11, 10) = \tfrac{1}{6} \cdot \tfrac{1}{3} = \tfrac{1}{18} and PA(11,11)=89P_A(11, 11) = \tfrac{8}{9}. From authority 9, PA(9,9)=PA(9,10)=1124P_A(9, 9) = P_A(9, 10) = \tfrac{11}{24} and PA(9,11)=112P_A(9, 11) = \tfrac{1}{12}. The stationary vector is

a(9)=a(10)=414=27≈0.2857,a(11)=614=37≈0.4286.a(9) = a(10) = \tfrac{4}{14} = \tfrac{2}{7} \approx 0.2857, \qquad a(11) = \tfrac{6}{14} = \tfrac{3}{7} \approx 0.4286.

As a check, a(11)PA(11,11)+2⋅a(9)PA(9,11)=37⋅89+2⋅27⋅112=37a(11) P_A(11, 11) + 2 \cdot a(9) P_A(9, 11) = \tfrac{3}{7} \cdot \tfrac{8}{9} + 2 \cdot \tfrac{2}{7} \cdot \tfrac{1}{12} = \tfrac{3}{7}. The hub scores are out(q)/14\mathrm{out}(q)/14: 314\tfrac{3}{14} for hub 0, 17\tfrac{1}{7} for hubs 1 to 3 and 114\tfrac{1}{14} for hubs 4 to 8. HITS, normalized to sum 1, gives the authorities about 0.36600.3660, 0.36600.3660 and 0.26790.2679: it ranks the block 9 and 10 above page 11, although more pages link to 11.

Now remove the link 0→110 \to 11. The graph G~\tilde G splits into the block (four hubs, two authorities, eight links) and the star (five hubs, one authority, five links). Theorem 2 of the proof file gives a(9)=a(10)=23⋅48=13a(9) = a(10) = \tfrac{2}{3} \cdot \tfrac{4}{8} = \tfrac13 and a(11)=13⋅55=13a(11) = \tfrac{1}{3} \cdot \tfrac{5}{5} = \tfrac13, and every hub gets 19\tfrac19. HITS gives 12\tfrac12, 12\tfrac12 and 00: the dominant eigenvalue of W⊤WW^\top W belongs to the block (8 against 5), so the star gets nothing. This is the tightly knit community (TKC) effect that Lempel and Moran describe.

Correctness

The file proofs/correctness.md proves the closed form. Each row of PAP_A sums to 1. The chain is reversible with weights in(i)\mathrm{in}(i), because in(i)PA(i,j)\mathrm{in}(i) P_A(i, j) is a sum over the common hubs of 1/out(q)1/\mathrm{out}(q), which is symmetric in ii and jj. So in(i)/m\mathrm{in}(i)/m is stationary. Two authorities can reach each other exactly when they lie in the same component of G~\tilde G, and every state has a positive self loop, so on a connected G~\tilde G the chain is irreducible and aperiodic: its stationary distribution is unique, and power iteration converges to it from any start. On a general G~\tilde G the chain splits into one block per component, the uniform start puts mass ∣Ac∣/∣A∣|A_c|/|A| on block cc, and the block keeps it. This gives line L5, and the hub case gives line L6.

Proof: SALSA scores are the in-degrees and out-degrees, weighted by component sizefull

Let EE be the set of links of the base set after self links and repeated links are removed, and let m=∣E∣≥1m = |E| \ge 1. Write in(p)\mathrm{in}(p) and out(q)\mathrm{out}(q) for the in-degree and out-degree. The hub side is H={q:out(q)>0}H = \{q : \mathrm{out}(q) > 0\} and the authority side is A={p:in(p)>0}A = \{p : \mathrm{in}(p) > 0\}. The bipartite graph G~\tilde G has a node qhq_h for each q∈Hq \in H, a node pap_a for each p∈Ap \in A, and an undirected edge {qh,pa}\{q_h, p_a\} for each link (q,p)∈E(q, p) \in E. A page in both sets gives two different nodes.

The authority chain moves from an authority ii to a uniformly random hub qq with (q,i)∈E(q, i) \in E, and then to a uniformly random authority jj with (q,j)∈E(q, j) \in E. Its transition matrix is

PA(i,j)=∑q: (q,i)∈E, (q,j)∈E1in(i) out(q).P_A(i, j) = \sum_{q :\ (q, i) \in E,\ (q, j) \in E} \frac{1}{\mathrm{in}(i)\, \mathrm{out}(q)}.

The hub chain moves from a hub qq along a random out-link to pp and then back along a random in-link of pp to a hub rr: PH(q,r)=∑p: (q,p)∈E, (r,p)∈E1out(q) in(p)P_H(q, r) = \sum_{p :\ (q, p) \in E,\ (r, p) \in E} \frac{1}{\mathrm{out}(q)\, \mathrm{in}(p)}.

SALSA defines the authority scores as lim⁡k→∞uAPAk\lim_{k \to \infty} u_A P_A^k, where uAu_A is the uniform distribution on AA, and the hub scores in the same way with PHP_H and the uniform distribution uHu_H on HH. The lemmas below show that the limits exist and give them in closed form. We prove the authority case; the hub case is the same proof with the roles of in and out swapped.

Lemma 1 (stochastic). Each row of PAP_A sums to 11.

Proof. ∑jPA(i,j)=∑q:(q,i)∈E1in(i)∑j:(q,j)∈E1out(q)\sum_j P_A(i, j) = \sum_{q : (q, i) \in E} \frac{1}{\mathrm{in}(i)} \sum_{j : (q, j) \in E} \frac{1}{\mathrm{out}(q)}. The inner sum has out(q)\mathrm{out}(q) terms equal to 1/out(q)1/\mathrm{out}(q), so it is 11. The outer sum has in(i)\mathrm{in}(i) terms equal to 1/in(i)1/\mathrm{in}(i). □\square

Lemma 2 (reversible). For all authorities ii and jj, in(i)PA(i,j)=in(j)PA(j,i)\mathrm{in}(i) P_A(i, j) = \mathrm{in}(j) P_A(j, i).

Proof. Both sides equal ∑q:(q,i)∈E, (q,j)∈E1/out(q)\sum_{q : (q, i) \in E,\ (q, j) \in E} 1/\mathrm{out}(q), which is symmetric in ii and jj. □\square

Lemma 3 (components). PA(i,j)>0P_A(i, j) > 0 if and only if some hub links to both ii and jj. Two authorities ii and jj can reach each other in the chain if and only if iai_a and jaj_a are in the same connected component of G~\tilde G. Each PA(i,i)>0P_A(i, i) > 0.

Proof. The first claim holds because every term of the sum is positive. A path in G~\tilde G alternates between hub nodes and authority nodes, so a path from iai_a to jaj_a is a sequence of authorities i=i0,i1,…,ir=ji = i_0, i_1, \ldots, i_r = j in which each consecutive pair shares a hub, which is a path of positive steps of the chain; the converse reads the same sequence backwards. Every authority ii has some hub qq with (q,i)∈E(q, i) \in E, and the term for qq in PA(i,i)P_A(i, i) is positive. □\square

Let the components of G~\tilde G be c=1,…,Cc = 1, \ldots, C, with authority sets AcA_c, hub sets HcH_c and link sets EcE_c, so mc=∣Ec∣=∑p∈Acin(p)=∑q∈Hcout(q)m_c = |E_c| = \sum_{p \in A_c} \mathrm{in}(p) = \sum_{q \in H_c} \mathrm{out}(q). Each link lies in exactly one component, because its two ends are joined by an edge.

Theorem 1 (connected case). If G~\tilde G is connected, the authority chain has the unique stationary distribution π(i)=in(i)/m\pi(i) = \mathrm{in}(i)/m, and uAPAk→πu_A P_A^k \to \pi.

Proof. π\pi is a distribution, because the in-degrees sum to mm. By Lemma 2, ∑iπ(i)PA(i,j)=1m∑iin(j)PA(j,i)=π(j)\sum_i \pi(i) P_A(i, j) = \frac{1}{m} \sum_i \mathrm{in}(j) P_A(j, i) = \pi(j), using Lemma 1 in the last step. So π\pi is stationary. By Lemma 3 the chain is irreducible and each state has a self loop, so it is aperiodic. A finite irreducible chain has exactly one stationary distribution, and a finite irreducible aperiodic chain converges to it from every start (the convergence theorem for finite Markov chains). □\square

Theorem 2 (general case). For each authority pp in component cc,

lim⁡k→∞(uAPAk)(p)=∣Ac∣∣A∣⋅in(p)mc,\lim_{k \to \infty} (u_A P_A^k)(p) = \frac{|A_c|}{|A|} \cdot \frac{\mathrm{in}(p)}{m_c},

and for each hub qq in component cc, lim⁡k→∞(uHPHk)(q)=∣Hc∣∣H∣⋅out(q)mc\lim_{k \to \infty} (u_H P_H^k)(q) = \frac{|H_c|}{|H|} \cdot \frac{\mathrm{out}(q)}{m_c}.

Proof. By Lemma 3, PA(i,j)=0P_A(i, j) = 0 when ii and jj lie in different components, so PAP_A is block diagonal with one block PcP_c for each component, and each block is a stochastic matrix by Lemma 1. Then (uAPAk)(u_A P_A^k) restricted to AcA_c equals ∣Ac∣∣A∣⋅(ucPck)\frac{|A_c|}{|A|} \cdot (u_c P_c^k), where ucu_c is uniform on AcA_c: the start puts mass ∣Ac∣/∣A∣|A_c|/|A| on the block, spread evenly, and the block never sends mass out. Component cc is a connected bipartite graph on its own, so Theorem 1 applied to it gives ucPck→in(p)/mcu_c P_c^k \to \mathrm{in}(p)/m_c. □\square

This is Proposition 2 of Lempel and Moran in the unweighted case. The weight ∣Ac∣/∣A∣|A_c|/|A| comes from the uniform start. With another start the limit gives the component other weights, while the scores inside a component stay proportional to in-degree. This is why SALSA fixes the start.

Theorem 3 (the implementation). The function salsa returns these limits.

Proof. Line L1 builds EE. Line L2 builds HH and AA from the degrees. Line L3 labels the nodes of G~\tilde G by a graph search from each node that is not yet labelled; a search labels exactly the nodes that are connected to its start, so two nodes get the same label if and only if they are in the same component. Line L4 counts, for each label, the hubs, the authorities and the links, a link being counted at its hub. Lines L5 and L6 then evaluate the formulas of Theorem 2. □\square

Cost. Removing repeated links costs O(m)O(m) expected time with a hash set. Building the adjacency lists, the search and the counts cost O(n+m)O(n + m), and lines L5 and L6 cost O(n)O(n). So SALSA costs O(n+m)O(n + m) besides the duplicate removal, with no iteration. The implementation sorts the links once to fix their order, which adds O(mlog⁡m)O(m \log m).

Complexity

Repeated links can be removed in O(n+m)O(n + m) worst-case time by two passes of counting sort on the pairs, or in expected O(m)O(m) time with a hash set. The degrees, the graph search for the components and the counts take O(n+m)O(n + m), and lines L5 and L6 take O(n)O(n). So SALSA costs Θ(n+m)\Theta(n + m) time on the word RAM and O(n+m)O(n + m) extra space for the bipartite graph, with no iteration. Power iteration of the chains costs O(m)O(m) for each step, and the number of steps depends on the second eigenvalue of each block, which can be close to 1. The closed form avoids that cost. The implementation sorts the links once to fix their order, which adds O(mlog⁡m)O(m \log m). The real cost of query-time link analysis is building the base set, which needs the links into and out of each root page.

Properties

  • In-degree inside a component. On a connected G~\tilde G, SALSA ranks authorities exactly as the in-degree does, and hubs exactly as the out-degree does. Borodin, Roberts, Rosenthal and Tsaparas make the same point in their comparison of link analysis rankings.
  • Component weights. Across components, the score is the in-degree share inside the component times the share of authorities in the component. A page in a small component can beat a page with a larger in-degree in a big one, and the other way round.
  • Weighted links. With link weights, Lempel and Moran's result uses the weighted in-degree, the sum of the weights of the links into a page.
  • Stable against dense blocks. Because each step divides by out(q)\mathrm{out}(q) and in(i)\mathrm{in}(i), a dense block gets weight in proportion to its links and its authorities, not by the size of its largest eigenvalue as in HITS.
  • Deterministic and exact. The closed form uses only integer counts, so the scores are exact rational numbers.

Variants and improvements

  • Weighted SALSA. Give each link a weight, for example lower for links between pages of the same site, and replace the degrees by the sums of the weights.
  • SALSA on the global graph. The same chains can run on the whole web graph instead of a query graph; on a connected graph this is in-degree ranking, which is easy to spam with a link farm.
  • Random walks with restart. Adding a jump to a random page, as in PageRank, makes the chain irreducible on any graph, at the cost of the closed form.
  • Other bipartite graphs. The same two walks can run on any bipartite graph, for example users and the items they chose. The closed form shows that, without a restart, they rank items by popularity inside each component.

When to use it

Use SALSA when you want a query-dependent link score that rewards pages many hubs point to, without the instability of HITS on graphs with a dominant dense block. Know that, on a connected base set, you get in-degree ranking, so compute it as a count. If the base set has several components, the component weights carry the extra information. For a global, query-independent score, PageRank or TrustRank is the usual choice.

Pitfalls

  • Iterating when a count is enough. The closed form is exact and linear in the input. Power iteration can take many steps when the second eigenvalue is near 1, and still gives only an approximation.
  • Mixing the two sides. A page that is both a hub and an authority is two nodes of G~\tilde G. Merging them changes the components and the scores.
  • Forgetting the start. The component weights ∣Ac∣/∣A∣|A_c|/|A| come from the uniform start. A different start, or normalizing each component on its own, gives other scores for pages in different components.
  • Repeated links and self links. If they are kept, the degrees and the components change. State the rule, and remove both as HITS implementations do.
  • Ties. In-degrees are small integers, so many pages tie. Break ties by a fixed rule, here the smaller page number.

Implementations

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.

salsa_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/salsa-algorithm/. The authors are listed in prov/XD0VVF.jsonl.
"""SALSA of Lempel and Moran (WWW9 2000, ACM TOIS 2001), unweighted.

Pages are the integers 0 to n - 1 and an edge (q, p) is a link from q to p.
Self links are removed and repeated links count once. A page with an
out-link is a hub, a page with an in-link is an authority, and a page can
be both. The scores are the stationary distributions of two Markov chains
on the bipartite graph of hubs and authorities, started from the uniform
distribution on each side.
"""

from fractions import Fraction
from typing import Iterable

Number = float | Fraction


def clean_links(n: int, edges: Iterable[tuple[int, int]]) -> list[tuple[int, int]]:
    """Distinct links (q, p) with q != p, sorted."""
    arcs = set()
    for q, p in edges:
        if not (0 <= q < n and 0 <= p < n):
            raise ValueError("page out of range")
        if q != p:
            arcs.add((q, p))
    return sorted(arcs)


def degrees(n: int, arcs: list[tuple[int, int]]) -> tuple[list[int], list[int]]:
    out, inn = [0] * n, [0] * n
    for q, p in arcs:
        out[q] += 1
        inn[p] += 1
    return out, inn


def salsa(n: int, edges: Iterable[tuple[int, int]], exact: bool = False) -> tuple[list[Number], list[Number]]:
    """Return (hub scores, authority scores) by the closed form of Lempel and Moran.

    A page that is not a hub has hub score 0, and one that is not an authority
    has authority score 0. With exact=True the scores are Fractions.
    """
    arcs = clean_links(n, edges)  # @line L1
    out, inn = degrees(n, arcs)
    hubs = [q for q in range(n) if out[q] > 0]  # @line L2
    auths = [p for p in range(n) if inn[p] > 0]
    # The bipartite graph has 2n sides: hub q is node q and authority p is node n + p.
    adj: list[list[int]] = [[] for _ in range(2 * n)]
    for q, p in arcs:
        adj[q].append(n + p)
        adj[n + p].append(q)
    label = [-1] * (2 * n)  # @line L3
    for start in range(2 * n):
        if label[start] >= 0 or not adj[start]:
            continue
        label[start] = start
        stack = [start]
        while stack:
            u = stack.pop()
            for w in adj[u]:
                if label[w] < 0:
                    label[w] = start
                    stack.append(w)
    nh: dict[int, int] = {}  # @line L4
    na: dict[int, int] = {}
    ne: dict[int, int] = {}
    for q in hubs:
        nh[label[q]] = nh.get(label[q], 0) + 1
    for p in auths:
        na[label[n + p]] = na.get(label[n + p], 0) + 1
    for q, _ in arcs:
        ne[label[q]] = ne.get(label[q], 0) + 1

    def find(x: int) -> int:
        return label[x]

    def frac(a: int, b: int) -> Number:
        return Fraction(a, b) if exact else a / b

    zero: Number = Fraction(0) if exact else 0.0
    a: list[Number] = [zero] * n
    h: list[Number] = [zero] * n
    for p in auths:  # @line L5
        c = find(n + p)
        a[p] = frac(na[c] * inn[p], len(auths) * ne[c])
    for q in hubs:  # @line L6
        c = find(q)
        h[q] = frac(nh[c] * out[q], len(hubs) * ne[c])
    return h, a  # @line L7


def authority_step(n: int, arcs: list[tuple[int, int]], x: list[Number]) -> list[Number]:
    """One step of the authority chain: back to a random hub that links to the page, then forward on a random link of that hub."""
    out, inn = degrees(n, arcs)
    y = [x[0] * 0 for _ in range(n)]
    for q, p in arcs:
        y[q] += x[p] / inn[p]
    z = [x[0] * 0 for _ in range(n)]
    for q, p in arcs:
        z[p] += y[q] / out[q]
    return z


def hub_step(n: int, arcs: list[tuple[int, int]], x: list[Number]) -> list[Number]:
    """One step of the hub chain: forward on a random link, then back to a random hub that links to that authority."""
    out, inn = degrees(n, arcs)
    y = [x[0] * 0 for _ in range(n)]
    for q, p in arcs:
        y[p] += x[q] / out[q]
    z = [x[0] * 0 for _ in range(n)]
    for q, p in arcs:
        z[q] += y[p] / inn[p]
    return z


def salsa_power(n: int, edges: Iterable[tuple[int, int]], tol: float = 1e-13, max_rounds: int = 100000) -> tuple[list[float], list[float], int]:
    """The definition: run both chains from the uniform start until no score moves by more than tol.

    Returns (hub scores, authority scores, rounds used).
    """
    arcs = clean_links(n, edges)
    out, inn = degrees(n, arcs)
    hubs = [q for q in range(n) if out[q] > 0]
    auths = [p for p in range(n) if inn[p] > 0]
    a = [1.0 / len(auths) if inn[p] else 0.0 for p in range(n)] if auths else [0.0] * n
    h = [1.0 / len(hubs) if out[q] else 0.0 for q in range(n)] if hubs else [0.0] * n
    for r in range(1, max_rounds + 1):
        a2, h2 = authority_step(n, arcs, a), hub_step(n, arcs, h)
        moved = max([abs(u - v) for u, v in zip(a, a2)] + [abs(u - v) for u, v in zip(h, h2)])
        a, h = a2, h2
        if moved <= tol:
            return h, a, r
    raise RuntimeError("no convergence")


def authority_matrix(n: int, edges: Iterable[tuple[int, int]]) -> dict[tuple[int, int], Fraction]:
    """The exact transition probabilities P_A(i, j) of the authority chain, for authorities i and j."""
    arcs = clean_links(n, edges)
    out, inn = degrees(n, arcs)
    by_hub: dict[int, list[int]] = {}
    for q, p in arcs:
        by_hub.setdefault(q, []).append(p)
    pa: dict[tuple[int, int], Fraction] = {}
    for q, ps in by_hub.items():
        for i in ps:
            for j in ps:
                pa[(i, j)] = pa.get((i, j), Fraction(0)) + Fraction(1, inn[i] * out[q])
    return pa
test_salsa_algorithm.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/salsa-algorithm/. The authors are listed in prov/XD0VVF.jsonl.

import random
from fractions import Fraction

import pytest

from salsa_algorithm import authority_matrix, authority_step, clean_links, hub_step, salsa, salsa_power

# The example of the page: hubs 0 to 3 link to authorities 9 and 10, hubs 4 to 8 link to 11, and 0 also links to 11.
BLOCK = [(q, p) for q in range(4) for p in (9, 10)]
STAR = [(q, 11) for q in range(4, 9)]
CONNECTED = BLOCK + STAR + [(0, 11)]


def random_graph(rng: random.Random, n: int, prob: float) -> list[tuple[int, int]]:
    return [(q, p) for q in range(n) for p in range(n) if q != p and rng.random() < prob]


def components(n: int, arcs: list[tuple[int, int]]) -> list[set[int]]:
    """Authority sets of the connected components of the bipartite graph, by a plain search."""
    adj: dict[tuple[str, int], set[tuple[str, int]]] = {}
    for q, p in arcs:
        adj.setdefault(("h", q), set()).add(("a", p))
        adj.setdefault(("a", p), set()).add(("h", q))
    seen: set[tuple[str, int]] = set()
    comps = []
    for v in sorted(adj):
        if v in seen:
            continue
        stack, comp = [v], set()
        seen.add(v)
        while stack:
            u = stack.pop()
            if u[0] == "a":
                comp.add(u[1])
            for w in adj[u]:
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        comps.append(comp)
    return comps


def stationary(pa: dict[tuple[int, int], Fraction], nodes: list[int]) -> list[Fraction]:
    """Solve pi P = pi with sum(pi) = 1 exactly, by Gaussian elimination."""
    k = len(nodes)
    rows = [[(pa.get((nodes[i], nodes[j]), Fraction(0)) - (1 if i == j else 0)) for i in range(k)] + [Fraction(0)] for j in range(k)]
    rows[-1] = [Fraction(1)] * k + [Fraction(1)]
    for c in range(k):
        piv = next(r for r in range(c, k) if rows[r][c] != 0)
        rows[c], rows[piv] = rows[piv], rows[c]
        for r in range(k):
            if r != c and rows[r][c] != 0:
                f = rows[r][c] / rows[c][c]
                rows[r] = [x - f * y for x, y in zip(rows[r], rows[c])]
    return [rows[i][k] / rows[i][i] for i in range(k)]


def test_example_connected() -> None:
    h, a = salsa(12, CONNECTED, exact=True)
    assert [a[p] for p in (9, 10, 11)] == [Fraction(2, 7), Fraction(2, 7), Fraction(3, 7)]
    assert h[0] == Fraction(3, 14) and h[1] == h[2] == h[3] == Fraction(1, 7)
    assert all(h[q] == Fraction(1, 14) for q in range(4, 9))
    hp, ap, _ = salsa_power(12, CONNECTED)
    assert all(abs(float(x) - y) < 1e-9 for x, y in zip(a + h, ap + hp))


def test_example_two_components() -> None:
    h, a = salsa(12, BLOCK + STAR, exact=True)
    assert [a[p] for p in (9, 10, 11)] == [Fraction(1, 3)] * 3
    assert all(h[q] == Fraction(1, 9) for q in range(9))


def test_closed_form_matches_power_iteration() -> None:
    rng = random.Random(2)
    for _ in range(80):
        n = rng.randrange(1, 10)
        edges = random_graph(rng, n, rng.choice([0.15, 0.3, 0.6]))
        h, a = salsa(n, edges)
        hp, ap, _ = salsa_power(n, edges)
        assert all(abs(x - y) < 1e-9 for x, y in zip(h + a, hp + ap))


def test_closed_form_is_exactly_stationary() -> None:
    rng = random.Random(4)
    for _ in range(80):
        n = rng.randrange(1, 10)
        edges = random_graph(rng, n, 0.3)
        arcs = clean_links(n, edges)
        h, a = salsa(n, edges, exact=True)
        assert authority_step(n, arcs, a) == a
        assert hub_step(n, arcs, h) == h
        if arcs:
            assert sum(a) == 1 and sum(h) == 1


def test_connected_component_gives_in_degree() -> None:
    # On a connected bipartite graph the unique stationary distribution of P_A is in(p) / m.
    rng = random.Random(9)
    done = 0
    while done < 30:
        n = rng.randrange(2, 9)
        arcs = clean_links(n, random_graph(rng, n, 0.45))
        comps = components(n, arcs)
        if len(comps) != 1:
            continue
        done += 1
        auths = sorted(comps[0])
        pa = authority_matrix(n, arcs)
        for i in auths:
            assert sum(pa.get((i, j), Fraction(0)) for j in auths) == 1
            assert pa[(i, i)] > 0
        pi = stationary(pa, auths)
        inn = {p: sum(1 for _, x in arcs if x == p) for p in auths}
        assert pi == [Fraction(inn[p], len(arcs)) for p in auths]
        _, a = salsa(n, arcs, exact=True)
        assert [a[p] for p in auths] == pi


def test_component_mass_is_preserved() -> None:
    rng = random.Random(6)
    for _ in range(40):
        n = rng.randrange(2, 10)
        arcs = clean_links(n, random_graph(rng, n, 0.2))
        auths = sorted({p for _, p in arcs})
        if not auths:
            continue
        x = [Fraction(1, len(auths)) if p in auths else Fraction(0) for p in range(n)]
        for _ in range(3):
            x = authority_step(n, arcs, x)
        _, a = salsa(n, arcs, exact=True)
        for comp in components(n, arcs):
            share = Fraction(len(comp), len(auths))
            assert sum(x[p] for p in comp) == share
            assert sum(a[p] for p in comp) == share


def test_links_are_cleaned_and_empty_graph() -> None:
    assert clean_links(3, [(0, 1), (0, 1), (2, 2)]) == [(0, 1)]
    assert salsa(3, [(0, 1), (0, 1), (2, 2)], exact=True) == salsa(3, [(0, 1)], exact=True)
    assert salsa(3, [], exact=True) == ([0, 0, 0], [0, 0, 0])
    with pytest.raises(ValueError):
        salsa(2, [(0, 5)])

History

Lempel and Moran presented SALSA at the Ninth International World Wide Web Conference (WWW9) in Amsterdam in 2000, under the title "The stochastic approach for link-structure analysis (SALSA) and the TKC effect", and published the full version in ACM Transactions on Information Systems in 2001. They designed it as a random walk version of Kleinberg's hubs and authorities. Their main analytic result is that the stationary distributions reduce to weighted degrees, scaled by the sizes of the components. Borodin, Roberts, Rosenthal and Tsaparas later placed SALSA among the link analysis ranking algorithms and compared it with HITS and in-degree ranking in theory and experiments.

References

  1. R. Lempel and S. Moran, SALSA, the stochastic approach for link-structure analysis, ACM Transactions on Information Systems 19(2), 131-160 (2001), the two Markov chains on the bipartite hub and authority graph, the proposition that an irreducible authority chain has a stationary distribution proportional to the weighted in-degree, the proposition for several components with a uniform start, and the TKC effect of HITS; this journal version is the one the page relies on
  2. R. Lempel and S. Moran, The stochastic approach for link-structure analysis (SALSA) and the TKC effect, Computer Networks 33(1-6), 387-401 (2000), Proceedings of the 9th International World Wide Web Conference (WWW9), the conference version, with the definition of the chains, the analysis of their stationary distributions and the examples of the TKC effect
  3. Allan Borodin, Gareth O. Roberts, Jeffrey S. Rosenthal and Panayiotis Tsaparas, Link analysis ranking, algorithms, theory, and experiments, ACM Transactions on Internet Technology 5(1), 231-297 (2005), the section on SALSA (on a connected graph it ranks authorities by in-degree) and the comparison of InDegree, HITS and SALSA

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.worst
  • 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