The search process
- Build a precinct adjacency graph and connect otherwise disconnected geographic components with virtual edges.
- Create a population-balanced starting plan, or validate a user-supplied starting assignment.
- Calculate the starting score and record the plan as both the current and best plan.
- Propose a two-district recombination, an optional three-district recombination, or an optional one-precinct boundary flip.
- Reject a proposal that cannot satisfy the active population bound or construction-time connectivity requirements.
- Score a valid proposal and apply the current acceptance rule.
- Independently retain the lowest-total-score accepted plan encountered during the run.
Graph and connectivity
Mosaic represents each input polygon as a node. An edge connects polygons that share positive boundary length or overlap in area; corner-only contact does not create an edge.
Islands and exclaves
If the graph has disconnected components, Mosaic adds virtual edges to the working graph. It starts with the component containing the greatest population and attaches the remaining components one at a time. Same-county connections are preferred when county data is available, then polygon distance and node order break ties.
Virtual edges can participate in movement and connectivity. They are excluded from Cut Edges and the adjacency inputs for Neighborhood Severance and Community Dispersion. They do not modify the source shapefile.
Exact bridge procedure
Candidate bridges are prefiltered by centroid distance and finalized with polygon-to-polygon distance. Bridge construction is deterministic and uses no random-number generator.
A district may be connected in Mosaic's working graph only because of a virtual edge. This is working connectivity, not a claim of physical land adjacency.
Recombination and other moves
Two-district recombination
Mosaic selects an edge that currently crosses a district boundary, combines the two districts on that edge, builds a randomized minimum spanning tree across the combined region, and looks for a tree cut that gives both replacement districts an allowed population.
Exact tree and cut procedure
- Assign a random edge ordering and run a minimum-spanning-tree procedure.
- Choose a root uniformly among tree vertices whose degree is greater than one.
- Calculate the population of every rooted subtree.
- Scan vertices in ascending local node order and take the first parent edge that produces an allowed split.
- Try up to 100 trees before treating the move as unsuccessful.
The district pair is also not uniform: selecting a boundary edge gives pairs with longer graph boundaries more opportunities to be selected.
Fast tree generation
This option changes how Mosaic randomizes the edge order used to build proposal trees. The default fast mode uses a local xorshift64* random generator for its edge shuffle and root choice. Turning it off uses the reference randomization path. With County-edge bias on, the reference path sorts uniform edge weights with cross-county weights multiplied by the bias B. The fast path draws the same order distribution without sorting: each cross-county edge joins the early part of the order with probability 1/B, and the early and late parts are each shuffled.
Both modes apply randomized Kruskal construction, scan for the first population-valid cut in the same node order, and try at most 100 trees. Neither samples spanning trees uniformly. Fast mode uses modulo reduction in its shuffle, which introduces a small sampling bias; it also consumes random values differently, so the same seed does not imply the same proposal sequence across modes.
Three-district recombination
When enabled, Mosaic sometimes combines three neighboring districts. It first carves one population-balanced district from the combined region, then divides the remainder into two. This is a two-stage procedure, not a single uniform three-way cut.
Exact three-district procedure
- Select one current boundary edge to choose districts A and B. As with ordinary ReCom, district pairs with more boundary edges have more chances to be selected.
- Select one boundary edge leaving A or B to choose an adjacent third district C. A candidate C with more edges to A or B is therefore more likely to be chosen.
- Merge A, B, and C. Try up to 20 randomized trees to carve one connected piece inside the active population limit. Only the carved piece must be valid at this first stage.
- Split the remaining area into two population-valid connected pieces. Mosaic first checks whether the successful first-stage tree already supplies that split; if not, it tries up to 20 new randomized trees on the remainder.
- Label the three new pieces A, B, and C. If either stage fails, the entire proposal fails and the assignment is unchanged.
Fast tree generation and County-Edge Bias apply to these tree cuts in the same way they apply to ordinary ReCom.
Polish flips
A polish flip moves one boundary precinct into a neighboring district. Mosaic checks that the source district remains connected and that both affected districts stay within the active population bound. The default dispatch rate rises later in the run while preserving some recombination moves through the end.
Exact flip procedure and timing
When flips are enabled, Mosaic checks for a flip before either kind of ReCom. The flip probability is 5% at the start, reaches 50% at the selected 50% crossover, and reaches 85% at the end.
- Select a current district-boundary edge and randomly choose which direction to move across it. County-Edge Bias, when active, makes cross-county edges less likely to be selected.
- Reject the attempt if moving the selected precinct would empty its source district.
- Require the new source and destination populations to remain inside the active population limit.
- Require the source district to remain connected after removal. The destination remains connected because the precinct crosses an existing boundary edge into it.
- Try at most 100 boundary-edge and direction choices. If none passes, the iteration has no proposal to score.
A valid flip is scored and accepted or rejected by the same annealing rule as a ReCom proposal.
How the move settings combine
Each iteration first tests the current flip probability. Only when no flip is selected does Mosaic test the n=3 ReCom Mix percentage; otherwise it uses ordinary two-district ReCom.
The n=3 percentage is therefore conditional, not the share of all iterations. With flips enabled, its approximate overall chance is (1 − flip probability) × n=3 percentage.
County-edge bias
County-edge bias changes proposal probabilities rather than adding a score. It makes cross-county graph edges less likely to enter the proposal tree and less likely to be selected for a flip. It steers the search but does not prevent county splits.
Acceptance and cooling
Mosaic minimizes a weighted total. With annealing enabled, a proposal that does not increase the total is always accepted. A worse proposal may still be accepted according to:
Here Δ is the increase in total score and T is the current temperature. This is a Metropolis acceptance criterion used with a changing temperature. If annealing is disabled, Mosaic accepts every valid proposal, not only improvements.
Guided cooling
Guided mode calculates one geometric cooling rate intended to move from the initial temperature to the target temperature at the selected guide point in the run. It does not continuously adapt to the observed acceptance rate.
Formula and Launch Watch
Launch Watch can re-anchor the proportional temperature once after the opening portion of the run and recalculate the remaining Guided rate. This is a one-time adjustment, not acceptance-rate tuning.
Static cooling
Static mode multiplies the temperature by the user-selected cooling rate after every numbered iteration. Cooling also occurs after an unsuccessful move attempt or a rejected valid proposal.
Population constraints
For ideal population P and active tolerance t, a changed district must fall inside the inclusive interval:
This hard rule is separate from the optional Population Deviation score. A plan can satisfy the hard limit even when the soft score assigns a penalty within that range.
The optional tolerance ratchet tightens the hard proposal limit during the latter portion of a run. It never loosens the current bound and does not tighten past the deviation the current map has already achieved.
Current and best plans
The current plan is the state from which Mosaic proposes the next move. Because annealing can accept a worse plan, it may not be the best plan encountered. Mosaic separately records an accepted plan only when its total score is strictly lower than the previous best.
Revert to Best rewinds the assignment, score, iteration, temperature, and chart histories to that recorded point. Exports use the current plan on the map; they do not silently substitute the best plan.
Relight and Hot Start
Hot Start uses one loaded assignment as the starting plan. Relight instead uses the map currently on screen each time Start is pressed, so successive runs can continue from one another. They cannot be active together.
Arming Relight saves the current search settings, then applies a refinement preset: annealing on; Guided cooling; Initial Temp Factor 0.01; Guide Point 0.80; Launch Watch off; n=3 ReCom Mix 50%; flips on; and the flip 50% crossover at 75% of the run. It also shows the full plot history instead of limiting plots to the latest 10,000 iterations. It does not replace the selected score weights, iteration count, or population tolerance.
Clear Relight restores the saved search settings and removes the current-map start. Reset, loading a new shapefile, or changing the district count also clears it. At Start, the displayed map must still match the selected district count and population tolerance.
Score methodology
The optimizer minimizes a weighted sum:
Most optimizer penalties use 0 = best, but they do not share a common natural scale. Charts often show a friendlier rating, signed statistic, probability, or count instead of the penalty. Equal numeric weights therefore do not guarantee equal practical influence.
Notation, input rules, and rounding
k is the number of districts, aᵢ is precinct i's zero-based district assignment, Popᵢ is general population, and I = ΣPopᵢ/k is ideal population. Unless stated otherwise, plan-level means weight districts equally.
Election fractions remain in 0–1 units. Demographic scores use Uᵢ for the selected demographic total and Gᵢ for a compatible group count in the same universe. The source columns may be CVAP, VAP, total population, or another coherent basis; Mosaic's formulas do not inherently require VAP.
Mosaic scores Black, Latino, and Asian groups separately. White may be selected for the demographic map fill but is not a scored group. The formulas do not require the selected group columns to be mutually exclusive or exhaustive.
Where this page says round, Mosaic uses ties-to-even rounding.
Geography and population
Polsby-Popper, approximate Reock, and Compactness
All geometry is measured in the shapefile's current coordinate reference system; the scorer does not reproject it. For district d, Mosaic reconstructs its area and perimeter from precinct areas, exterior edges, and shared boundaries, then calculates:
PP_d = clip(4π × area_d / perimeter_d², 0, 1) PP penalty = 100 × (1 − mean_d(PP_d))
Approximate Reock selects each precinct's extreme point in 16 evenly spaced directions. For each district it finds the farthest pair among the retained directional extremes and treats half that distance as a radius:
radius_d = max pairwise distance among 16 directional extremes / 2 Reock_d = min(area_d / (π × radius_d²), 1) when radius_d > 0; otherwise 0 Reock penalty = 100 × (1 − mean_d(Reock_d))
This is deterministic but is not a minimum-enclosing-circle calculation and does not verify that the implied circle encloses the district.
Combined Compactness applies a scorecard to the two mean ratings and averages the resulting penalties. In clipped mode, a rating x maps linearly from penalty 100 at lo to 0 at hi. The bands are PP [0.10, 0.50] and Reock [0.25, 0.50].
B_clipped(x; lo, hi) = 100 − 100 × (clip(x,lo,hi) − lo)/(hi − lo) Compactness penalty = 0.5 × B(PP) + 0.5 × B(Reock)
Default “unclipped” mode is still bounded. It follows the same line until PP 0.44 or Reock 0.4625, then eases from penalty 15 to penalty 0 at raw rating 0.65, using exponents 3.5 and 5.0 respectively. The chart shows 100 − penalty.
Cut Edges
The objective is the raw number of real adjacency edges whose endpoints fall in different districts. Virtual bridge edges are excluded. This is an unnormalized graph count, so its scale depends on the input geography.
County Congruence
Let M_cd be the population shared by county c and district d, P_c = Σ_d M_cd, Q_d = Σ_c M_cd, and P = Σ_c P_c. For each county, wholly contained districts are combined before taking one square root; partial pieces receive separate square roots:
S_c = Σ_partial d √(M_cd/P_c) + √(Σ_whole d M_cd/P_c) raw_county = Σ_c (P_c/P) × S_c
The district direction is symmetric: exchange counties and districts to obtain raw_district. The ordinary no-split reference is 1 in either direction. Default mode uses:
penalty = 0.5 × 45 × max(0, raw_county − 1)
+ 0.5 × 45 × max(0, raw_district − 1)This default penalty is not capped at 100. The optional clipped scorecard maps each direction between a problem-size reference and 1.33 × reference, averages the two 0–100 results, then multiplies by 0.20; its actual range is therefore 0–20. County-Edge Bias is a proposal preference, not part of this score.
Classic Splitting
Classic Splitting has two independent weighted components, not one combined objective. If touches_c is the number of districts containing any population from county c:
allowance_c = ceil(P_c / max(I,1)) ExcessCount = Σ_c max(0, touches_c − allowance_c) Excess penalty = 10 × ExcessCount
For the single-county component, with population tolerance t:
min district population = max(I × (1−t), 1) population-only bound = Σ_c floor(P_c / min district population) actual clean = number of districts touching exactly one county Single-county penalty = 10 × (population-only bound − actual clean)
The displayed “maximum feasible” line is only a population arithmetic bound. It does not prove contiguity or simultaneous drawability. The chart shows raw ExcessCount and actual clean districts, not the two optimizer penalties.
Population Deviation
For each district, Mosaic measures the absolute fractional difference from ideal population, subtracts the optional safe-harbor band, squares the remaining excess, and sums across districts.
The chart shows maximum and mean absolute deviation in percent, not this penalty.
Alignment
Alignment is a one-sided reference-district cohesion measure. Let M_ad be the selected weight from reference district a that lies in proposed district d, G_a = Σ_d M_ad, and f_ad = M_ad/G_a. Then:
cohesion_a = Σ_d f_ad² penalty = 100 × Σ_a G_a × (1 − cohesion_a) / Σ_a G_a
The weight basis is general population by default, or the selected party's votes when party focus is available. An optional restriction includes only reference districts where that party's two-party share is strictly above the threshold (default 0.535). The chart shows 100 − penalty and the minimum reference-district cohesion.
Because the measure is one-sided, merging several intact reference districts into one proposed district is not itself penalized.
Election model and partisan scores
Election-based scores use the selected Democratic and Republican vote columns. For district i, sᵢ = Dᵢ/(Dᵢ+Rᵢ); a zero-turnout district is assigned sᵢ=0.5. Statewide share V is turnout-weighted.
p = clip(user P(win at 55%), 0.501, 0.9999) σdistrict = 0.05 / Φ⁻¹(p) σcombined = √(σswing² + σdistrict²) P(D wins district i) = Φ((sᵢ − 0.5) / σcombined)
Defaults are P(win at 55%)=0.9 and σswing=0.03, giving σdistrict≈0.0390152 and σcombined≈0.0492157. Chamber probabilities preserve correlated statewide swing with 17-point Gauss-Hermite quadrature and a Poisson-binomial seat-count calculation.
Shared directional penalty mapping
Mean-Median, Efficiency Gap, and Partisan Bias convert a signed statistic x and positive bound B to distance d:
Fair: d = min(1, |x|/B) Favor Dem: d = clip((x+B)/(2B), 0, 1) Favor Rep: d = clip((B−x)/(2B), 0, 1) linear penalty = 100d quadratic penalty = 100d²
The quadratic toggle applies to all three metrics. Charts still show the untransformed signed statistic.
Mean-Median Difference
Districts are equally weighted. The default directional bound is B=0.20. The chart shows the signed raw fraction rather than a percent or penalty.
Efficiency Gap
Static mode uses strict sᵢ>0.5 for a Democratic win. Democratic wasted votes are (sᵢ−0.5)Tᵢ when Democrats win and sᵢTᵢ otherwise; Republican wasted votes are the complementary losing or surplus votes. The raw gap is Σ(wasted D − wasted R)/ΣTᵢ.
Default Robust mode uses a closed-form expectation:
σEG = √(0.03² + σdistrict²) qᵢ = Φ((sᵢ−0.5)/σEG) raw = Σ Tᵢ × ((2sᵢ−0.5) − qᵢ) / ΣTᵢ
Robust EG always uses 0.03 for its statewide swing term; the shared Swing setting does not change it. The default directional bound is B=0.35. The chart shows the signed raw fraction.
Partisan Bias and Partisan Gini
Let S(v)=meanᵢ Φ((sᵢ+(v−V)−0.5)/σcombined) be the smoothed Democratic seat-share curve under uniform swing.
Partisan Bias raw = 0.5 − S(0.5) Bias default bound B = 0.25
Positive Bias favors Republicans under Mosaic's sign convention. Partisan Gini evaluates |S(v) − (1−S(1−v))| on the grid 0.35, 0.37, …, 0.65, integrates it by the trapezoid rule, and uses:
The Gini chart shows this good-low penalty, not the raw area and not a reversed rating.
Proportionality and inversion risk
Default mode compares expected Democratic seat share E_S=mean(pᵢ) with statewide vote share V. It discounts a winner's bonus within |V−0.5| and scales the remaining magnitude against 0.42; the within-bonus multiplier is 0.25.
Inversion risk is the quadrature-integrated probability that the statewide popular-vote loser wins a strict chamber majority. The popular-vote winner switch is smoothed with a normal CDF of scale 0.005. Tied chambers count for neither party.
The chart shows good-high 100−penalty and bad-high 100×inversion risk on the same panel.
Competitiveness
kernelᵢ = 1 − 4(pᵢ−0.5)² cDf = mean(kernelᵢ)
Clipped mode maps cDf=0 to rating 0 and cDf≥0.75 to rating 100. Default mode follows that line through cDf=0.5625 (penalty 25), then eases to penalty 0 only at cDf=1 with exponent 7/3. The chart shows 100−penalty.
Expected seats, Majority, and Hinge
Expected Democratic seats E_D = Σᵢ pᵢ Favor Dem penalty = 100 × (k−E_D)/k Favor Rep penalty = 100 × E_D/k
Chance of Majority uses a strict majority. For even-sized chambers, a tie belongs to neither party, so Democratic and Republican majority chances need not sum to 1.
Hinge uses the selected party's probability of reaching at least the selected threshold. Both probability objectives use penalty=100×(1−probability)^1.5; charts show 100×probability.
Demographic scores
These scores use the demographic total and group-population columns selected at load time. Every group numerator must use the same universe as its denominator. A group can be not applicable when the input does not provide enough population, adjacency, or geographic concentration for that score to measure.
Electoral Opportunity
For group g in district d, aggregate selected-universe total U_d and group count G_gd. Defaults are midpoint m=0.44, steepness τ=0.05, and solid reference s=0.55.
share_gd = G_gd / max(U_d,1) P_gd = 1 / (1 + exp(−(share_gd−m)/τ)) ref_g = max(sigmoid((s−m)/τ), 10⁻⁹) T_g = (statewide G_g / statewide U) × k target_g = round(T_g)
Let x=P_gd/ref_g. Hard district credit is min(x,1). Default soft credit is (x⁻⁸+1)⁻¹⁄⁸. Mosaic sums only the largest target_g credits. Displayed Seats and per-group Rating always use hard credit; the optimizer uses soft credit when “Unclipped” is on.
Smart Targets supplies a greedy reference credit D_g and applicability signal. Hard credit is displayed as Opportunity count. An applicable group's rating is 100×min(hard credit/D_g,1). The overall penalty is 100×(1−weighted success), weighting groups by unrounded T_g. It is not the simple average of the displayed group ratings.
Smart Targets
Smart Targets is the optional geographic reference used by Electoral Opportunity. Before scoring a plan, it greedily assembles nearby high-share precincts into hypothetical district-sized bundles. The resulting credits determine whether a group is included and what reference its opportunity rating uses.
Mosaic ranks distance between representative points inside precincts. It does not use adjacency, shared boundary, road access, or travel time. Longitude/latitude-like coordinates are flattened by multiplying x by cos(mean latitude); projected coordinates are used as supplied.
ideal = ΣU/k rounds = max(round(statewide group share × k), 1) queried neighbors = min(N, max(32, 4 × ideal/mean(U))) candidate centers = min(N, 600, max(100, 1200 // rounds))
- Choose the highest-share available precincts as candidate centers.
- For each center, take the nearest available precincts up to twice ideal population; skip a pool holding less than
0.999 × ideal. - Within the pool, add precincts in descending group-share order until group count reaches
solid × idealor total count reaches ideal. - Keep the highest-credit bundle, remove its precincts, and repeat through the proportional target.
candidate denominator = max(bundle total, ideal) candidate share = bundle group count / candidate denominator candidate credit = min(sigmoid((share−midpoint)/steepness) / solid reference, 1) applicable when first credit ≥ 0.10 reference credit = sum of greedy credits through the proportional target
When Smart Targets is off or coordinates are unavailable, Mosaic instead bundles precincts from a statewide descending group-share ranking. That fallback may combine distant places.
Limit: neither method enforces contiguity, the run's population tolerance, compactness, county boundaries, complete-plan construction, or legal constraints. Smart Targets is a heuristic comparison reference, not proof that a valid district can be drawn and not a maximum number of drawable districts.
Neighborhood Severance
For each real adjacency edge e=(u,v), group weight is the product of the endpoint group shares. Virtual edges receive weight zero.
q_gi = G_gi/max(U_i,1) w_ge = q_gu × q_gv A_g = Σ_real edges w_ge f_g = Σ_cut edges w_ge / A_g E(k,N) = 0.6972 × (k−1)^0.5150 / N^0.4091 r_g = f_g / E(k,N)
Applicable groups are pooled before calibration with mass √A_g and a weighted root-mean-square of r_g. The calibration is a monotone four-piece map anchored at penalties 5, 55, and 95; its district-count anchors are:
x = max(k−1,10⁻⁹) R5 = max(1 − 1.1362 × x^(-0.2447), 0.02) R95 = min(1 + 13.9170 × x^(-0.6368), 20) Rs = clamp(1, R5+0.05, R95−0.05)
The optimizer uses the calibrated pooled penalty. Each group chart shows 100−calibrated group penalty, so the overall line cannot be reconstructed by averaging group lines.
Community Dispersion
Mosaic identifies connected group-concentration cores at share thresholds 0.50, 0.35, and 0.20, using only real adjacency. Their multipliers are 1, 0.5, and 0.25. Cores with general population below 20,000 are discarded; qualifying nested cores remain separate records.
P_cd = general population of core c placed in district d effective pieces N_eff,c = core_pop_c² / Σ_d P_cd² forced pieces m_c = max(1, ceil(core_pop_c/ideal_pop − 10⁻⁹)) r_c = N_eff,c / m_c core weight = √core_pop_c × layer multiplier r_pool = weighted root-mean-square of r_c
The same four-piece calibration shape is used, with district-count anchors:
x = max(k−1,10⁻⁹) R5 = clamp(1 + 0.000074 × x^1.784031, 0.02, 3) Rs = max(1 + 0.259077 × x^0.267266, R5+0.05) R95 = min(max(3.923603 − 3.232672 × x^(-0.688527), Rs+0.05), 20)
The overall calibrated penalty is optimized; group charts show 100−group penalty. This calibration is provisional.
Shared demographic calibration function
Neighborhood Severance and Community Dispersion use the same map F(r) after calculating metric-specific anchors R5 < Rs < R95:
r ≤ 0: F = 0
r ≤ R5: q = min(18R5/max(R95−R5,10⁻⁹),12)
F = 5(r/R5)^q
r ≤ Rs: F = 5 + 50(r−R5)/(Rs−R5)
r ≤ R95: F = 55 + 40(r−Rs)/(R95−Rs)
r > R95: tail = (R95−Rs)/18
F = 100 − 5tail/(tail+r−R95)Therefore F(R5)=5, F(Rs)=55, and F(R95)=95; the upper tail approaches but never reaches 100.
Ensembles
Each run starts from a fresh partition or the loaded Hot Start and retains its final or lowest-scoring plan. With a nonzero base seed, successive runs increment the seed by one. These optimized plans are not uniform samples of valid district plans.
Summary metrics
Summaries measure available metrics using unclipped holistic scores and static efficiency gap, regardless of which scores the search optimizes. Hinge is measured only when enabled. The score column is the retained plan’s weighted objective.
Histograms and scatterplot statistics use all finite results; the scatterplot may display a subset of points.
Targeting (Beta)
Targeting varies run settings within adaptive bands to seek lower scores. It varies iterations and the n=3 mix, plus flip, temperature, and guide settings when their corresponding features are enabled. Scoring weights remain fixed; iterations are capped at 300,000 per run.
A regression over recent runs estimates how settings relate to score. The default fits the mean; Favor lower-tail scores fits the 20th percentile using all runs in a larger window. If the quantile solver fails, it falls back to least squares.
Fitting begins after 10 runs and repeats every five. The first 20 runs are labeled warm-up; adaptation continues throughout the ensemble. A setting’s center moves toward lower estimated scores when its 90% bootstrap interval excludes zero.
These beta estimates guide tuning; their intervals are not calibrated confidence guarantees for the adaptive search.
Reproducibility
A seed alone is not enough. To attempt an exact replay, set a nonzero seed, turn off Fast tree generation, and keep the input file and row order, every run setting and score weight, the starting plan, the Mosaic version, and the computing environment unchanged.
For the strongest control over the starting point, reuse the same Hot Start. Mosaic's automatic starting-map builder has a wall-clock cutoff and may restart at a different point on a faster or slower machine.
Fast tree generation uses a different randomization path and is not Mosaic's exact-replay mode. Changing a move type also changes how random values are consumed. Even with the reference tree method and the same Hot Start, a seed is not a portable identifier for a plan and does not guarantee bit-for-bit equality across releases or machines.
Attribution
Mosaic's recombination approach is derived from the family of methods developed by the Metric Geometry and Gerrymandering Group (MGGG). See Daryl DeFord, Moon Duchin, and Justin Solomon, “Recombination: A Family of Markov Chains for Redistricting”, and the MGGG sampler overview.
Mosaic makes its own implementation choices within that broader family. Attribution does not imply that Mosaic inherits every algorithm, guarantee, or recommended use described in the research literature.
Mosaic