Mosaic Master

Stitches multiple astrophotos into one seamless image by placing every panel on a shared celestial frame using its WCS, then blending the overlaps. Handles both standard WCS-based mosaics (the usual case) and a dedicated Seestar Mode for images from robot smart telescopes that arrive without plate solves. Includes two reprojection engines (exact SIP-aware per-pixel inverse mapping, and a fast single-homography shortcut), a two-stage brightness normalization system (sky pedestal match + overlap gain fit with sky pivot), a mixed-tone-scale detector that catches when linear and stretched panels have been mixed by mistake, and overlap-relative distance-transform seam blending.

Original work for SetiAstro Suite Pro. The entire mosaic pipeline is written from scratch by Franklin Marek: the exact SIP-aware per-pixel inverse mapping with tiled dispatch, forward-only footprint-bbox restriction, and quarter-pixel round-trip validation (so SIP non-convergence at the footprint edge is caught rather than silently miscomposited); the destination-WCS linearization decision (SIP is only valid inside its fit domain, so the mosaic canvas must be pure linear TAN while source panels keep their SIP); the pedestal coverage-preservation technique (add +1.0 before warping so the valid-pixel footprint survives Lanczos4 border fill, 12-px coverage erosion to clear interpolation ringing, strip pedestal before accumulation); the two-stage normalization (per-panel sky-level estimator with tiled sigma-clipping, then an overlap gain fit solving “reference ~ a×(source−p) + p + b” pivoted on the common sky level so gain only scales signal above sky, reduced to 16×16 block means to escape sky-noise OLS attenuation); the mixed-tone-scale detector (per-panel MAD ratio flagged against the Histogram tool's reference MAD algorithm); the panel ordering (center-first + max pairwise overlap, deliberately not union-box which would invent overlap in L-shaped layouts); the pre-blur distance-transform feathering with the raised-power sharpness control that converts a global coefficient into an overlap-relative blend ratio after accumulation; the SIP autodisable that inspects actual A/B polynomial coefficients rather than mere keyword presence; the Seestar Mode iterative pipeline with center-first base selection by star count, WCS-rough and physics-rough transform fallbacks, feathered sum-and-count accumulation, and brightness-ratio pixel rejection; the Add from View multi-pick with WCS tagging; the Reproject Mode dispatcher; the mosaic WCS merge policy; and the ASTAP+Astrometry.net plate-solve fallback for unsolved panels. The external tools (astroalign, ASTAP, Astrometry.net, photutils) are credited separately in their sections and in the final Credits box.
Workflow
Drop your panel files on the Panels list (or use + Files / + Views) — check the Sky map: every plate-solved panel appears where it will land, the reference panel outlined in gold — choose Brightness (Standard, or Advanced for big grids and multi-night mosaics) — press Build Mosaic — the finished mosaic replaces the sky map, with every panel's outline and every seam coloured by how well it matched — Push to New View.

The core of the normalization pipeline: once two panels have been placed on the common frame, their overlap pixels are modelled as a linear match on the common sky level p:

\mathbf{R} \approx a \cdot (\mathbf{S} - p) + p + b

Pivoting about the sky decorrelates a and b: the pedestal match earlier in the pipeline already set p to the reference frame's sky level, so what's left between the panels is a scale factor on signal above sky plus a tiny residual offset. §15.11 explains why that pivot matters and §15.12 explains why the fit runs on 16×16 block means instead of per-pixel.

Contents
1. The window
2. Adding panels
3. The reference panel
4. Sky map
5. Traditional Panels or Robotic Mosaic
6. Brightness
7. Placement (reprojection)
8. Star refine
9. Seams, preparation and output
10. Build Mosaic
11. The result and the panel map
12. SIP and star refinement
13. Plate solving fallback
14. Seestar and smart telescope frames
15. Technical details
15.1 Panel ordering
15.2 Mosaic WCS linearization
15.3 Output bounding box
15.4 Exact SIP-aware remap
15.5 Round-trip validation
15.6 Footprint-bbox restriction
15.7 Fast homography mode
15.8 Pedestal coverage preservation
15.9 Edge trim
15.10 Sky pedestal match
15.11 Overlap gain fit with sky pivot
15.12 Block-mean reduction
15.13 Robust iteration
15.14 Mixed tone-scale detection
15.15 Seam feathering
15.16 Star alignment refinement
15.17 Polynomial warp
15.18 SIP coefficient detection
15.19 ASTAP integration
15.20 Astrometry.net integration
15.21 Seestar frames: plate solving and placement
15.22 Seestar frames: averaging and outlier rejection
15.23 Advanced panel matching (global solve)

1. The window

Two sides and one button. On the left, the two mode cards at the top (§5), then the Panels list with the options below it; on the right, the Sky map, which shows where every plate-solved panel will land before you build, and the finished mosaic with its panel map afterwards. Along the bottom: help, the status line, and Build Mosaic, which runs everything in order. Rarely needed options sit in three sections that open with a click: Preparation, Star alignment details and Output. Every option is remembered between sessions.

2. Adding panels

Drop files from your file manager onto the Panels list, or use + Files… (FITS, XISF, TIFF, PNG, JPG and the common camera raws), + Folder… (every image file in a folder, the quick way to add a Seestar sub-frame folder) or + Views… to take images that are open in SASpro (a picker with All, None and Only solved; useful right after a batch of plate solves). A file that is already in the list is not added twice, and a file that can't be read is named in the status line.

Each row shows:

Select rows and press Remove or Delete to take panels out. Double-click a row to preview that panel (zoom, pan, auto-stretch toggle).

3. The reference panel

One panel anchors the mosaic: its plate solution defines the mosaic's sky frame, and its sky level is the one every other panel's brightness is matched to. By default SASpro picks the plate-solved panel with the most real data (so a large existing mosaic anchors a run instead of a small tile), and of equal ones the panel nearest the field centre (§15.1). The ★ shows the choice before you build. Click another row's ★ column to pin that panel as the reference; click it again to go back to the automatic choice.

4. Sky map

Every plate-solved panel is drawn as its real footprint, laid out in the reference panel's frame — the frame the mosaic is built in, so the map looks like the result will. Overlaps show where the panels' tints combine. The reference panel is outlined in gold with a ★; the panel selected in the list is outlined in white, and clicking a footprint selects its row. Arrows mark north and east, a bar gives the scale, and the line along the bottom gives the number of solved panels and the field size. Panels that aren't plate-solved yet can't be placed and are counted there instead.

5. Traditional Panels or Robotic Mosaic

The two cards at the top of the window choose what kind of mosaic you are building; the chosen card is outlined and ticked. Pick it first, since it decides how the panels you add are read.

6. Brightness

How panel brightness is matched:

If the sky can't be measured on the reference panel (rare: very few stars or heavy clipping), SASpro falls back to matching each panel's median to the reference.

7. Placement (reprojection)

How each panel is warped onto the mosaic's sky grid:

Exact — SIP-aware remap (recommended)

Per-pixel inverse mapping with full SIP support on the source panel: for every mosaic pixel, the mosaic WCS gives its (RA, Dec), and the panel's WCS inverse (with its SIP polynomial) gives the panel pixel to sample, with Lanczos resampling (§15.4–15.6).

Fast — Homography (Global H)

One 3×3 projective transform per panel, fitted from a WCS-derived control grid (§15.7). Exact for panels without SIP; with SIP present it can double stars near the panel edges.

8. Star refine

After a panel is placed by its plate solution, its stars can be matched to the mosaic in the overlap for a final correction. Choices: Affine (default; translation, rotation, scale and shear), Off — WCS placement only (use when overlaps are small, or when the panels' plate solutions are better than a star fit), Partial affine (no shear), Homography (full projective; needs well-spread stars) and Polynomial warp (§15.17; its degree is under Star alignment details). Panels with a SIP distortion solution are always placed by their plate solution alone (§12). The result's panel map shows, per panel, whether it was placed by its plate solution or by stars and how many stars matched.

9. Seams, preparation and output

Seams sets how sharply panels hand off across an overlap: the power p on the distance-transform feather (1.0–6.0, default 2.0, §15.15). Soft (1–2) gives a wide, gradual blend that hides small brightness differences but needs good registration; sharp (4–6) crosses over near the middle of the overlap, the safer choice when panels disagree slightly.

Preparation (click to open):

Star alignment details: Stars to detect for the star refinement (default 200; the detection threshold is chosen from it, §15.16), and the polynomial-warp degree. Not used by Robotic Mosaic.

Output: Plate solve the finished mosaic against the local Gaia DR3 catalogue (on by default) so its plate solution is tied to stars from every panel rather than to the reference panel's own; and Auto-stretch the full preview (the mosaic data stays linear either way).

10. Build Mosaic

Runs the whole pipeline, with a progress window you can cancel:

  1. Prepare — crop, if set.
  2. Plate-solve every panel without a solution (or all, with Re-solve), then SRGC if set (§13).
  3. Order panels — reference first, then each next panel by its overlap with those already placed (§15.1).
  4. Build the mosaic frame — the reference panel's WCS without SIP (§15.2), sized to cover every panel (§15.3).
  5. Measure the reference sky and check for mixed linear and stretched panels (§15.14).
  6. For each panel: sky level match, reprojection, star refinement, overlap fit, feathered accumulation.
  7. Advanced brightness: the joint solve and the second build (§15.23).
  8. Final blend, then the Gaia plate solve of the result if set.

The window stays open, and every option is still there: change one and press Build Mosaic again to rebuild with the same panels.

11. The result and the panel map

When the build finishes, the finished mosaic replaces the sky map, auto-stretched for display. With Panel map on, it shows:

Sky map switches back to the plan, and Result returns. Full Preview… (or double-click the mosaic) opens a zoomable window. Push to New View, beside Build Mosaic on the bottom row, is greyed out until a mosaic is built; then it turns green and becomes the main button, while Build Mosaic turns plain and reads Rebuild Mosaic (it turns blue again when you add or remove panels or change mode, since the mosaic no longer matches them). It opens the mosaic in SASpro as a linear 32-bit image, its plate solution attached under metadata['original_header'] (so plate-solve-aware tools find it) along with its coverage map; the window stays open.

12. SIP and star refinement

A panel whose plate solution carries real SIP distortion (actual non-zero polynomial coefficients, not just declared keywords, §15.18) is always placed by its plate solution: a single global star fit can't reproduce a per-pixel 4th-order SIP resample, and on a corner panel it trades one edge's registration for another's. When at least 80% of the panels carry SIP, Star refine defaults to Off, and the line under the options says so; otherwise it defaults to Affine. Once you pick a Star refine setting yourself, that choice stays for the session.

13. Plate solving

Panels without a usable plate solution (or every panel, with Re-solve every panel) are blind-solved when you build:

In-house Gaia solver (first)

SASpro's own blind solver: a quad-hash index over the Gaia DR3 catalogue you downloaded, then a catalogue refinement. No network needed.

Astrometry.net (fallback)

If the in-house solver fails, uploads to nova.astrometry.net via the web API (requires an API key from api/astrometry_key, prompted if missing). Login → upload → poll submission → poll calibration (up to ~15 minutes each). On success, builds a TAN WCS header from the returned RA/Dec/pixscale/orientation and merges it into the panel. The TAN construction, following the standard FITS WCS convention:

CD1_1 = -s cos(θ) CD1_2 = s sin(θ) CD2_1 = -s sin(θ) CD2_2 = -s cos(θ)

with s in degrees/pixel and θ the orientation in radians. For on-disk FITS panels, the file is updated in-place; views and non-FITS sources get the WCS attached in memory only.

14. Seestar and smart telescope frames

A Seestar mosaic is hundreds of 10–20 s frames from an alt-az mount: the scope steps between panel positions and the field rotates through the night. Choose the Robotic Mosaic card, add the sub-frame folder with + Folder… and press Build Mosaic.

  1. Sky map before solving — each frame is drawn from the pointing in its header (RA/DEC, with the pixel scale from FOCALLEN and XPIXSZ), dashed because its rotation isn't known yet, over a map of how many frames cover each spot. A banner says the layout is an estimate until the frames are solved. Some smart telescopes record the target's coordinates rather than each panel's, so every frame lands in one spot: the banner says so, and the real layout appears as the frames are solved.
  2. Plate solve every frame against your local Gaia DR3 catalogue, seeded by that header pointing: about 1–2 s a frame, several frames at once in worker processes. A frame whose seed is too far off gets a blind quad-index solve. The table shows each frame's state and the sky map fills in with the real, rotated footprints as frames are solved. Solutions are kept in SASpro's cache folder (your frames are never rewritten), so a rebuild doesn't solve again; Re-solve every panel under Preparation ignores the cache. Frames that can't be solved are marked ✗ and left out, and remembered: a rebuild doesn't spend a blind solve on them again (Re-solve every panel does, and so does changing the file). A failure is only remembered when other frames did solve, so a setup problem such as a missing Gaia library never marks good frames as bad.
  3. Lay out the canvas around every solved frame: a TAN projection at the mean pointing, the frames' pixel scale, north up and east left. It grows to whatever the frames cover.
  4. Place and average — each frame is debayered (the Stacking Suite's Debayer setting), its own sky level is subtracted, and it is mapped onto the canvas by the exact projective transform between its plate solution and the canvas (the shift and rotation between frames, plus the projection change across a wide mosaic), with the Stacking Suite's anti-ring Lanczos resampling. Frames are averaged with a feather at each frame edge so the change in depth at a frame boundary doesn't show as a step, and the median sky level is added back.
  5. Reject satellites and other outliers (on by default): while the frames are stacked, each spot keeps its three brightest and its faintest samples aside; at the end they are tested against the other frames there and the ones that don't belong (satellite and aircraft trails, hot pixels, cosmic rays) are taken out. One pass over the frames, so it costs almost no extra time (§15.22).

The result is plate-solved: it carries the canvas WCS, and its header records the frame count and total integration. The result view shows a heat map of how many frames cover each spot with every frame's outline; hover anywhere for the depth there, in frames and minutes. Crop every panel (Preparation) trims the same margins off every frame, for edge artefacts. In synthetic tests with frames rendered from real Gaia stars, stars on the result were a median 0.15 px from their catalogue positions.

15. Technical details

Panel ordering, reprojection, normalization and blending.

15.1 Panel ordering

Alignment is sequential — each panel is matched against the mosaic as it exists so far. The order matters: a panel with no overlap with any already-placed panel can't be star-aligned at all. SASpro orders panels so the first is near the field centre and each later one maximises overlap with the already-placed set.

For every panel, sample 64 points around the perimeter in pixel space, forward through the panel's WCS (via all_pix2world — forward SIP is a plain polynomial evaluation, no iteration), take the resulting (RA, Dec) set as a sky bounding box. Project all boxes onto a TAN tangent plane centred on the mean sky position (RA wrap handled via unit vectors, not raw differences):

\xi = \frac{\cos\delta \sin(\alpha - \alpha_0)}{\sin\delta_0 \sin\delta + \cos\delta_0 \cos\delta \cos(\alpha - \alpha_0)}
\eta = \frac{\cos\delta_0 \sin\delta - \sin\delta_0 \cos\delta \cos(\alpha - \alpha_0)}{\sin\delta_0 \sin\delta + \cos\delta_0 \cos\delta \cos(\alpha - \alpha_0)}

then compute 2D rectangles in (ξ, η) space and run the ordering:

  1. First panel: the one whose rectangle centre is closest to (0, 0).
  2. Each next panel: the one with the largest pairwise overlap fraction against any already-placed panel:
f_{\mathrm{ov}}(A, B) = \frac{\mathrm{area}(A \cap B)}{\min(\mathrm{area}(A),\;\mathrm{area}(B))}
i^{*} = \arg\max_{i \notin \mathrm{placed}} \;\max_{j \in \mathrm{placed}}\; f_{\mathrm{ov}}(B_i, B_j)

Taking max over placed panels (not union) is deliberate: in an L-shaped layout, the union bounding box would fill in the hollow and “see” overlap where there's actually no shared sky. Pairwise max only reports real overlap with real panels.

Panels that genuinely share no sky with any already-placed panel are placed last and logged (“shares no sky with any placed panel — WCS placement, pedestal-only sky match”). They still get added to the mosaic via WCS placement; they just can't be star-refined.

15.2 Mosaic WCS linearization

The mosaic's destination WCS is linear TAN with no SIP, even when the source panels carry SIP. The reason: SIP is a polynomial correction that's only valid inside the frame it was fit to. The mosaic canvas is much larger than any single panel, so extrapolating a panel's SIP polynomial out to the full mosaic frame would diverge badly in the corners.

SASpro linearizes the destination by setting wcs.sip = None on a deep-copied WCS object and stripping -SIP from the CTYPEs. Source panels keep their SIP intact — that's what makes the inverse mapping correct per-pixel. Only the destination coordinate frame is forced linear.

15.3 Output bounding box

With the reference WCS (first ordered panel, linearized) picked, every panel's four corners are transformed to the reference frame via SkyCoord → skycoord_to_pixel. The bounding box of all transformed corners gives the mosaic's extent. CRPIX of the mosaic WCS is shifted by (-min_x, -min_y) so the mosaic occupies [0, W]×[0, H]. The mosaic's final WCS header is then this shifted copy, which is also what gets attached to the output view.

15.4 Exact SIP-aware remap

Per-pixel inverse mapping, tiled 512×512. For each tile:

  1. Generate destination pixel coordinates (x_d, y_d) on the tile grid.
  2. Forward through the (linear) destination WCS: (α, δ) = wcs_dst.pix2world(x_d, y_d). Exact and cheap — no SIP to invert.
  3. Inverse through the (SIP-rich) source WCS: (x_s, y_s) = wcs_src.all_world2pix(α, δ). This is the iterative SIP inverse.
  4. Reject (x_s, y_s) outside the source panel bounds (with 1-pixel margin for Lanczos).
  5. Round-trip validate every surviving coordinate (§15.5).
  6. Resample the source panel at the surviving coordinates via cv2.remap with INTER_LANCZOS4 and borderValue=0.

Progress is reported per tile so the UI stays responsive. Astropy's non-convergence warning on all_world2pix is caught silently because the subsequent validation handles edge cases properly — the warning would otherwise fire noisily on every panel at footprint edges.

15.5 Round-trip validation

A diverged SIP inverse that happens to land back inside the source frame still produces nonsense — all_world2pix can return a “solution” that doesn't actually reproject back to the sky it was asked for. SASpro validates by forward-SIP evaluating every mapped pixel and comparing to the asked-for sky position:

\|(\alpha', \delta') - (\alpha, \delta)\| < 0.25 \cdot s_{\mathrm{px}}

with the comparison in angular units and s_px the source panel's pixel scale. The RA difference is cos(δ)-weighted so the metric is proper angular distance:

\Delta\alpha = (\alpha_2 - \alpha_1) \cdot \cos(\delta),\quad \Delta\delta = \delta_2 - \delta_1

Pixels failing the quarter-pixel tolerance are marked invalid and left black (border fill). On a well-solved mosaic, rejection is near zero in the panel interior and up to a few percent at the footprint edge, where SIP non-convergence is expected behaviour. The log reports the rejection rate per panel.

15.6 Footprint-bbox restriction

Running the exact remap over the entire mosaic canvas would call the SIP inverse on billions of coordinates that have no business touching the source panel. SASpro restricts the remap to a bounding box containing just the panel's footprint in the destination frame, computed forward-only (all_pix2world → wcs_world2pix) over 96 perimeter sample points:

Outside this box, the SIP inverse is never called, pixels stay at the border-fill value (zero), and the pedestal coverage test correctly reports them as uncovered.

15.7 Fast homography mode

For panels without SIP, a single 3×3 homography is enough to represent the full gnomonic composition between the two tangent-plane projections (source panel's TAN and mosaic's TAN). SASpro samples 9 control points — corners, edge midpoints, centre — and fits the homography via cv2.findHomography(method=RANSAC, ransacReprojThreshold=2.5):

  1. Source pixel coords (x, y) → sky (α, δ) via source WCS.
  2. Sky (α, δ) → destination pixel coords (x', y') via mosaic WCS.
  3. Fit the (x, y) → (x', y') homography.

Then cv2.warpPerspective with INTER_LANCZOS4 for the actual warp. The result is cached per source WCS so subsequent panels reusing the same WCS object skip the fit.

Correctness: exact for SIP-free TAN panels on small fields (where the tangent-plane approximation holds across the panel). For panels with real SIP distortion, the global homography collapses the per-pixel polynomial corrections into a single average linear warp, and stars near the edges can double by a few pixels.

15.8 Pedestal coverage preservation

A warp has to say which output pixels came from real data. A panel's own no-data (exact 0.0 or NaN) is filled with the panel's sky level before the warp, and the area outside the frame is filled with the same sky level by the warp itself, all on a +1.0 pedestal:

I' = I + P, \qquad I'_{\mathrm{outside}} = s + P

With no hard step anywhere, Lanczos has nothing to ring on. Which pixels are real data comes from the panel's validity mask, warped alongside the image:

\mathrm{coverage} = \{(x, y) : M'(x, y) \ge 0.999\}

A 0.0 pixel in a panel is left out at its own pixel (2×2 after the warp), and nothing around it is lost. After the edge trim (§15.9) the pedestal is stripped and anything outside the coverage is zeroed:

I_{\mathrm{out}} = (I_{\mathrm{warped}} - P) \cdot \mathbb{1}_{\mathrm{coverage}}

Astroalign and the brightness match see pedestal-free data. Ragged stacking edges are best removed with Crop every panel (Preparation).

15.9 Edge trim

Within Lanczos reach (4 px) of the frame's edge, an output pixel mixes in some of the sky fill from outside, so a 4 px band along the outside edge of the coverage is trimmed. Holes inside the coverage are not grown by this trim.

Earlier versions warped onto a zero border and eroded the whole coverage mask by 12 px to clear the ringing it caused; that also grew every isolated 0.0 pixel into a black dot 25–37 px across where only one panel covered the sky (GitHub issue #138).

15.10 Sky pedestal match

For each panel, the sky level is measured via estimate_background_level():

  1. Tile the panel into a 16×16 grid. Each tile must contain at least 60% finite valid pixels.
  2. Rank tiles by luminance median and keep the darkest 15%. Luminance ranking (not per-channel) means all channels sample the same patches of sky, preserving the panel's background colour.
  3. Sigma-clip the kept pixels: 3 iterations of σ = 1.4826 · MAD, hard upper threshold at 2.5σ (to kill stars and nebulosity), loose lower threshold at 6·2.5σ (to avoid clipping legitimate sky noise).
  4. The sky level μ_i is the per-channel median of the clipped set; the sky noise σ_i is 1.4826 · MAD.

Applied to every panel before reprojection, with the reference panel's sky μ_ref as the common target:

I'_i = I_i - \mu_i + \mu_{\mathrm{ref}}

After this step every panel has the same sky colour and the same sky level as the reference panel. Signal above sky is untouched.

15.11 Overlap gain fit with sky pivot

Pedestal match handles DC offset but doesn't address panels taken at slightly different gains or in slightly different filters. For every overlap between the current panel and the already-accumulated mosaic (where coverage from both exists and total overlap is at least 5000 pixels), SASpro solves a linear match pivoted on the sky:

\mathbf{R} \approx a \cdot (\mathbf{S} - p) + p + b

with R the running mosaic estimate at the overlap pixels, S the new panel's reprojected pixels, and p the common sky level (set to μ_ref because Stage 1 already shifted both to that pivot). Applied as:

\mathrm{out} = (\mathrm{src} - p) \cdot a + p + b

Why pivot on sky: in a non-pivoted R ≈ a·S + b fit, a and b are correlated. A gain error attributed to a leaks into b and vice versa. Pivoting on the sky level separates them: a acts only on signal above sky (where it belongs — linear detector gain), b acts only on residual sky offset (where it belongs — any imperfection left from the Stage 1 pedestal match).

The gain is clamped to prevent pathological fits:

a_{\mathrm{out}} = \mathrm{clip}(a,\;0.05,\;20)

If the gain gets clamped, SASpro logs it. A clamped gain is almost always a sign of insufficient overlap or heavy contamination in the overlap region, and the clamp prevents a wildly wrong fit from catastrophically dimming or brightening the panel.

15.12 Block-mean reduction

The overlap gain fit is not done per-pixel. A sky-dominated overlap has pathologically low signal variance — most of the pixel-to-pixel variation is read noise and sky noise, not actual signal. An OLS slope on per-pixel data is attenuated by:

a_fit = a_true · var(signal) / (var(signal) + var(noise))

and collapses toward zero when noise dominates signal.

SASpro reduces the overlap to 16×16 block means before fitting:

S_k = \frac{1}{|B_k|} \sum_{(x, y) \in B_k} I(x, y)

Noise averages down as 1/block (so by a factor of 16 at the pixel level, 256 in variance). Real signal doesn't average down — a star in the block stays bright, a galaxy arm stays an arm. After reduction, the signal-to-noise ratio in the fit input is improved by a factor of ~16, enough to make the fit well-conditioned.

Blocks with less than 90% valid coverage (i.e. where part of the block falls outside the overlap mask) are discarded.

15.13 Robust iteration

The block-mean fit is iterated 4 times with robust sigma-clipping on the residuals. Standard sigma clipping with the median absolute deviation estimator:

\mathrm{MAD} = \mathrm{median}(|x - \mathrm{median}(x)|)
\sigma \approx 1.4826 \cdot \mathrm{MAD}
\mathrm{keep} = \{i : |r_i - \mathrm{median}(r)| < k \cdot \sigma\}

with k = 2.5. Blocks whose residuals fall outside this envelope (typically contaminated by diffraction spikes, cosmic rays missed by rejection, galaxy structure extending into the sky, etc.) are dropped and the fit is redone. Iteration stops early when the inlier set stops changing or drops below 16 blocks.

15.14 Mixed tone-scale detection

Linear astronomical panels and stretched (display-scaled) panels can look the same at first glance but have wildly different pixel distributions: a linear panel's MAD is pathologically tiny (order 1e-3) because almost all pixels sit near the sky floor; a stretched panel's MAD is 1–2 orders of magnitude higher. Normalization cannot blend across those scales — a gain fit between a linear source and a stretched reference would produce a huge a that distorts stars.

SASpro computes per-panel MAD using the exact algorithm from the Histogram tool (median absolute deviation of finite-pixel values, subsampled to 5M pixels with a seeded RNG on very large panels, averaged across colour channels). If the max/min ratio across panels exceeds 8×:

\frac{\max_i(\mathrm{MAD}_i)}{\min_i(\mathrm{MAD}_i)} > 8

SASpro prompts the user with a plain-language warning (“Looks like you've mixed linear and stretched panels”), lists the panels' MAD values with the names, and asks whether to continue. The 8× threshold is a judgement call — consistently-stretched panel sets tend to have MADs within 2× of each other, so 8× is firmly in “something's off” territory.

15.15 Seam feathering

Overlapping panels are blended by a distance-transform feather. For each panel's coverage mask:

  1. Compute the Euclidean distance transform d(x, y) — distance from (x, y) to the nearest coverage boundary. Pixels at the centre of the panel are far from any edge; pixels right at the edge are near zero.
  2. Apply a 15×15 Gaussian blur to smooth tiny boundary irregularities.
  3. Normalize by dividing by 100 (keeps d^p in float32 range at high p).
  4. Raise to the blend sharpness power p (settings; default 2.0):
w_i(x, y) = d_i(x, y)^{\,p}

The weighted mosaic is accumulated as:

\mathrm{sum}(x, y) = \sum_i I_i(x, y) \cdot w_i(x, y)
W(x, y) = \sum_i w_i(x, y)

and the final mosaic is sum / W. The elegant consequence of raising the weights to a power before accumulation is that the ratio of weights, which is what sets the actual blend, becomes:

\frac{w_i}{\sum_j w_j} = \frac{d_i^{\,p}}{\sum_j d_j^{\,p}}

This ratio spans exactly the available overlap region — wide where the overlap is generous, tight where the overlap is thin. It auto-scales to the geometry of every seam without any seam-specific tuning. The power p controls how sharply the handoff happens within whatever overlap is available: p = 1 gives linear ramp, higher p concentrates the handoff near the seam midline.

15.16 Star alignment refinement

For panels without SIP (where WCS-only placement is accurate but not perfect), an optional star refinement runs after reprojection:

  1. Compute the overlap between the newly reprojected panel's coverage and the mosaic's existing weight map (coverage & (W > 0)).
  2. If the overlap is smaller than 2000 pixels, skip refinement (not enough stars for a reliable match).
  3. Otherwise, restrict both the panel and the mosaic estimate to the overlap bounding box.
  4. Call astroalign.find_transform on the restricted images with a sigma backoff ladder (120 → 50 → 15 → 5): higher sigma first for isolated bright stars, lower if that fails. Serialised by a module-level lock because SEP (the backend) isn't thread-safe.
  5. Astroalign returns a similarity transform (rotation + uniform scale + translation). SASpro extracts the 2×3 affine matrix.
  6. Decompose the matrix for sanity checking — log a warning if rotation > 0.5°, scale differs from 1 by > 1%, or translation > 25 px. These are large residuals for a WCS-placed panel and signal that astroalign may be fitting error that WCS didn't actually have.
  7. Warp the panel with the affine matrix using cv2.warpAffine(LANCZOS4).
  8. If the transform mode is Homography or Polynomial Warp, run a further refinement pass that re-detects stars in the overlap and fits the higher-DOF model.

That re-detection picks its threshold by star count rather than a fixed sigma: SEP measures the overlap's background once (the no-data part of the canvas masked out), then extracts at 100, 50, 25, 12, 7, 5, 4 and 3 σ and stops at the first threshold that finds at least Stars to detect stars. Hot pixels (FWHM under 1.2 px) and streaks (ellipticity over 0.6) don't count. The mosaic side and the panel side are then detected at the same threshold, the lower of the two each would pick on its own, so both lists reach the same depth and their brightness-normalized fluxes describe the same stars when they are matched. The 300 brightest on each side are matched.

Restricting the match to the overlap bounding box (not the whole canvas) is critical: feeding the whole canvas to astroalign spreads control points across regions that can't correspond, starving RANSAC of usable bright anchors.

15.17 Polynomial warp

Polynomial Warp fits two polynomials of degree n in (x, y) through the matched star correspondences:

u = \sum_{i+j \leq n} a_{ij} \cdot x^i y^j
v = \sum_{i+j \leq n} b_{ij} \cdot x^i y^j

Degree is set in Settings (1–6, default 3). The coefficients are solved by least squares (np.linalg.lstsq) over the matched points, then a dense displacement map is evaluated on the full image grid and the panel is remapped via cv2.remap(INTER_LANCZOS4). Useful for Seestar panels or any blind-solved mosaic where the per-panel distortion isn't captured by any linear or projective model.

15.18 SIP coefficient detection

The SIP auto-disable logic (§12) needs to distinguish real SIP solutions from declared-but-empty SIP (ASTAP occasionally writes A_ORDER keywords without actual coefficients, for example). SASpro checks for genuine SIP by inspecting the WCS object's SIP structure:

Only when all three conditions are met does SASpro consider the panel “has SIP” for the auto-disable fraction count. Declared SIP without coefficients is treated as no SIP.

15.19 ASTAP integration

Mosaic Master no longer calls ASTAP (the in-house Gaia solver replaced it, §13); this describes the retained integration code.

External process via Qt's QProcess. SASpro writes a normalized temporary FITS copy of the panel (stretched for star visibility, same approach as the plate solver's shared _normalize_for_astap), invokes ASTAP as:

astap -f <tmp.fit> -r 179 -fov 0 -z 0 -wcs -sip

and waits up to 5 minutes for completion. On success, both the FITS header ASTAP wrote and any .wcs sidecar are parsed and merged. Numeric WCS keys (CRPIX, CRVAL, CD, SIP coefficients, orders) are coerced to proper float/int types because ASTAP occasionally writes them as strings, which trips astropy's type checks later.

Required WCS keys (CTYPE1, CTYPE2, RADECSYS, WCSAXES) are added if missing with sensible defaults (RA---TAN, DEC--TAN, ICRS, 2). For on-disk FITS panels, the file is saved back through SASpro's shared image-I/O with the solved header; for views and non-FITS sources, the WCS is attached in memory only.

15.20 Astrometry.net integration

Via the Astrometry.net web API (nova.astrometry.net/api). The API key is read from api/astrometry_key and prompted via a dialog if missing. The sequence:

  1. Login — POST login with the API key, receive a session token.
  2. Upload — POST upload with the panel (FITS, converted via generate_minimal_fits_header if needed), receive a submission ID.
  3. Poll submission — GET submissions/<subid> every 10 seconds, up to 90 attempts (15 minutes), waiting for the job ID to appear.
  4. Poll calibration — GET jobs/<jobid>/calibration/ every 10 seconds, up to 90 attempts, waiting for the calibration dict with ra, dec, pixscale, orientation.
  5. Construct TAN WCS — build the CD matrix from scale and orientation (equations in §13), merge into the panel's header.

All HTTP requests are routed through robust_api_request, which raises HTTPError on bad status, parses JSON, and prompts the user to restart on network errors or invalid responses rather than silently failing. For on-disk FITS panels, the file is updated in-place with the new WCS keys.

15.21 Seestar frames: plate solving and placement

Each frame is solved by SASpro's Gaia solver with the user's plate-solver dialog settings deliberately bypassed (no manual seed, no forced blind solve): seeded by the header RA/DEC and the scale from FOCALLEN and XPIXSZ, then, if that fails, blind through the quad index. Colour frames are solved on their luminance (a raw Bayer frame is debayered quickly first). The canvas WCS is TAN at the unit-vector mean of all frame centres, at the median pixel scale, with CD = [[-s, 0], [0, -s]] so north is up and east left as displayed (row 0 at the top), and sized to every frame's outline.

A frame maps onto the canvas by a 3×3 projective transform fitted to a 7×7 grid sent through both plate solutions (SIP included). The map between two TAN projections with different tangent points is exactly projective, so without SIP the fit is exact, and with it the residual is far below a pixel. Each frame is warped only into its own canvas box, on a pedestal so the frame edge gives Lanczos no step to ring on, with _warp_antiring as in the Stacking Suite. Coverage is the warped valid-pixel mask, eroded 3 px; the weight ramps from 0 to 1 over 48 px from the frame edge.

15.22 Seestar frames: averaging and outlier rejection

One pass over the frames accumulates, per canvas pixel and channel, the weighted sum, the weighted sum of squares, the weight and the number of frames, and keeps the pixel's three brightest and one faintest samples with their weights (numba kernels; frames are read, debayered and warped in worker processes and added in order). A kσ clip would need every pixel's mean and spread before it could judge a sample, which means reading, debayering and warping every frame a second time, half the stacking time. The outliers that matter here are a few samples per pixel, so instead the kept samples go through a generalized ESD test (Rosner) at the end: repeatedly take the most extreme remaining candidate, measured against the mean and σ of the samples left without it (so a trail can't hide in the spread it inflates, the masking a plain clip suffers when only a handful of frames cover a spot), with the Bonferroni Student-t critical value Live Stacking's bootstrap uses (false-removal rate 10−3 per pixel, split between the bright and faint ends). The outliers are the longest run of that sequence that passes, and they are subtracted from the sums. It applies where at least 4 frames cover a spot and always leaves 3 samples to judge against. Ordinary samples are never trimmed, unlike a 3σ clip, which removes 0.27% of good samples on pure noise. Something that is bright in more than three frames at the same spot is kept. In tests a trail across one frame left no excess on the result; on 596 real 60 s frames it rejected 0.41% of samples and the stack matched the earlier two-pass clip to 3×10−6 rms in the sky, with the same star sizes, in about two thirds of the stacking time.

15.23 Advanced panel matching (global solve)

The first pass runs exactly as usual (the next panel's star alignment needs the mosaic built so far) and additionally stores every aligned panel, after the sky pedestal match and before the Stage 2 overlap fit, cropped to its footprint, with its coverage and feather weights. Then, per colour channel, every panel k gets

\mathrm{out}_k = (x - p)\,g_k + p + b_{0,k} + b_{1,k}\,u + b_{2,k}\,v

with p the reference sky level, g a gain about it, and an additive background plane in panel-centred coordinates u, v ∈ [−1, 1]. Additive because deep-sky sky glow adds to the image and differs from night to night (solar and lunar mosaics are the opposite case: there the sky is black and Surface Mosaic allows a gain only). For every pair of overlapping panels the overlap is reduced to block means (16 px blocks or larger, §15.12), and each block asks for outi = outj. All of these are solved together by weighted least squares, with the reference panel fixed at g = 1 and no plane.

The second pass rebuilds the mosaic from the stored panels with the solved corrections and the same feather weights. In synthetic 3×3 tests with different gains, offsets and tilts per panel, the large-scale error against the true sky was about 4× smaller than with the one-by-one Stage 2 match.

Credits. The exact SIP-aware per-pixel inverse mapping with tiled dispatch, forward-only footprint-bbox restriction, and quarter-pixel round-trip validation; the destination-WCS linearization decision; the pedestal coverage-preservation technique (+1.0 pedestal, 0.995 threshold, 12-px edge trim for Lanczos4 ringing); the two-stage normalization (per-panel tiled sigma-clipped sky estimator plus sky-pivoted overlap gain fit R ≈ a·(S−p) + p + b reduced to 16×16 block means with 4-iteration robust MAD sigma-clipping and [0.05, 20] gain clamp); the mixed tone-scale detector (per-panel MAD matched to the Histogram tool's algorithm, 8× spread trigger); the panel ordering (centre-first + max pairwise overlap, deliberately not union-box); the pre-blur raised-power distance-transform feathering with sharpness power that converts a global coefficient into an overlap-relative blend ratio; the SIP coefficient-based auto-disable for the star refinement path; the Seestar Mode iterative pipeline with centre-first base selection by star count, WCS-rough and physics-rough transform fallbacks, feathered sum-and-count accumulation with brightness-ratio pixel rejection, canvas-expanding warping, failed-panel retry pass; the Add-from-View multi-pick dialog with WCS tagging; the Reproject Mode dispatcher; and the ASTAP-first then Astrometry.net fallback plate-solve chain are all original work by Franklin Marek for SetiAstro Suite Pro.

External tools and libraries: Astroalign (Beroiz, Cabral & Sanchez 2020, A&C 32:100384) provides the star-match transform estimation, with its own triangle invariant matcher internally driven by SEP (Barbary 2016, JOSS 1:58) derived from Source Extractor (Bertin & Arnouts 1996, A&AS 117:393). ASTAP is Han Kleijn's standalone plate solver (external process). Astrometry.net is Lang et al. (2010, AJ 139:1782) via the web API at nova.astrometry.net. Star detection for Seestar base selection uses DAOStarFinder from photutils, implementing Stetson (1987, PASP 99:191)'s DAOPHOT. The Automatic Background Extraction sample-point generator used by the Seestar polynomial gradient removal is SASpro's own ABE implementation. FITS WCS standards: TAN gnomonic projection follows Greisen & Calabretta (2002, A&A 395:1061); SIP distortion polynomial follows Shupe et al. (2005, ADASS XIV). RANSAC (used by the Fast Homography fit and all downstream OpenCV robust estimators) is Fischler & Bolles (1981, Comm. ACM 24(6):381). OpenCV provides the warp (warpAffine, warpPerspective, remap), homography fit (findHomography), distance transform, Gaussian blur, erode, and resampling filters (Lanczos4, area, cubic, nearest). Astropy provides FITS I/O, the WCS and SIP classes, fit_wcs_from_points, SkyCoord, skycoord_to_pixel, and the sigma-clipped statistics used by the sky estimator and DAOStarFinder prep. NumPy provides the array engine. PyQt6 provides the UI framework (including QProcess for driving ASTAP). requests provides the HTTP transport for the Astrometry.net API.