Compare commits

...

6 commits
v1.1.1 ... main

Author SHA1 Message Date
c0ef081e4d Release 1.1.7: reject moderate thin cloud and confirmed star elongation
All checks were successful
Release AstroFrame / packages (push) Successful in 56s
Frames the sky-structure detector already flags become REJECT when
strong cloud texture is backed by two independent moderate dimming
measurements. Elongation confirmed on the same matched reference stars
(lower 3-sigma bound of the change >= 0.10) rejects as a roundness
outlier, following Siril's Seestar -filter-round practice. NGC 1432:
Review 36 -> 1; every Keep unchanged across the validation corpus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:48:07 -07:00
ef7805055c Release 1.1.6: reject corroborated thin cloud instead of reviewing it
All checks were successful
Release AstroFrame / packages (push) Successful in 1m17s
Add a quadratic-detrended, smoothed sky texture measurement scaled by
clear reference scatter, and corroborate it with same-exposure
differential forced photometry (stars inside vs. outside the texture,
normalized by nearby clear frames). Frames already routed to REVIEW
become REJECT only when both agree; otherwise-clean KEEPs are never
affected. NGC 1432: Review 48 -> 36, Reject 100 -> 112, Keep unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:19:33 -07:00
d8923ea85d Release 1.1.5: compare against the nearby or best frame
All checks were successful
Release AstroFrame / packages (push) Successful in 56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 18:30:11 -07:00
b8ffe97c46 Release 1.1.4: replace noisy preview modes with patch denoising and fixed stretch
All checks were successful
Release AstroFrame / packages (push) Successful in 59s
2026-10-04 14:27:04 -07:00
d3362c8341 Release 1.1.3: reveal faint nebula structure with human-readable preview modes
All checks were successful
Release AstroFrame / packages (push) Successful in 1m6s
2026-10-04 13:52:01 -07:00
5ad7a6a79e Release 1.1.2: improve processing status and inspect stellar elongation
All checks were successful
Release AstroFrame / packages (push) Successful in 1m9s
2026-10-04 12:54:24 -07:00
29 changed files with 635 additions and 101 deletions

View file

@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>1.1.1</Version> <Version>1.1.7</Version>
<Authors>Elijah Kuntz</Authors> <Authors>Elijah Kuntz</Authors>
<Product>AstroFrame</Product> <Product>AstroFrame</Product>
</PropertyGroup> </PropertyGroup>

View file

@ -22,12 +22,12 @@ To analyze another dataset, choose **Analyze lights**, select the folder contain
- Select a quality measurement and click the graph to inspect an exposure. One graph shows the selected metric, including stellar flux when selected. Capture order uses UTC timestamps; gaps between sessions are marked rather than drawn to elapsed-time scale. - Select a quality measurement and click the graph to inspect an exposure. One graph shows the selected metric, including stellar flux when selected. Capture order uses UTC timestamps; gaps between sessions are marked rather than drawn to elapsed-time scale.
- Filter **REVIEW** or **REJECT**, and sort by concern, star count, stellar flux, or FWHM. - Filter **REVIEW** or **REJECT**, and sort by concern, star count, stellar flux, or FWHM.
- Toggle **Compare nearby** and **Spatial overlay**. Red fill shows transient sky structure in the aligned reference grid. Region outlines show forced stellar flux loss. Previews have independent display stretches; use measured flux to compare transparency. - Toggle **Compare nearby** and **Spatial overlay**. Red fill shows transient sky structure in the aligned reference grid. Region outlines show forced stellar flux loss. Previews have independent display stretches; use measured flux to compare transparency.
- Use **Frame view** for an area-averaged exposure preview, or **Nebula view** for additional averaging of faint diffuse structure. Adjust **Stretch** to brighten the display. These controls never affect measurements, classifications or original files. - Use **Frame view** for the default area-averaged grayscale preview, or **Denoised** for an alternative that reduces noise using similar nearby image patches. Denoised keeps its stretch parameters from the original thumbnail and is slightly brighter by default. Adjust **Preview stretch** in either view. Both comparison panes use the same viewing mode. These controls never affect measurements, classifications or original files.
- Scroll the mouse wheel over either preview to zoom around the cursor, and hold the left mouse button to drag. Zoom and image position persist across frames and are shared with the nearby comparison. **Reset view** restores the fitted, centered image. These display controls do not alter source pixels or analysis. - Scroll the mouse wheel over either preview to zoom around the cursor, and hold the left mouse button to drag. Zoom and image position persist across frames and are shared with the nearby comparison. **Reset view** restores the fitted, centered image. These display controls do not alter source pixels or analysis.
- Press **1**, **2**, **3** for KEEP, REVIEW, REJECT. Decisions save and advance. **J/K** navigates. **Reset** restores the automatic decision. **Ctrl+Z** undoes a manual decision. - Press **1**, **2**, **3** for KEEP, REVIEW, REJECT. Decisions save and advance. **J/K** navigates. **Reset** restores the automatic decision. **Ctrl+Z** undoes a manual decision.
- Decision evidence and measurements remain visible below the quality graph. Hover over an evidence line to read its full technical detail, and scroll the panel for additional measurements. Preview stretch and manual decisions sit below the image. Existing notes remain in saved projects and exports; the note editor has been removed. Automatic decisions and human overrides remain separate. - Decision evidence and measurements remain visible below the quality graph. Hover over an evidence line to read its full technical detail, and scroll the panel for additional measurements. Preview stretch and manual decisions sit below the image. Existing notes remain in saved projects and exports; the note editor has been removed. Automatic decisions and human overrides remain separate.
KEEP means consistent measurements; it does not certify a perfect frame. REVIEW means a substantial deviation or measurement uncertainty. REJECT requires strong, coherent transient sky structure, agreement between cloud/flux/star-loss measurements, severe combined morphology degradation, or catastrophic star disappearance. Small ellipticity variations alone do not trigger review. KEEP means consistent measurements; it does not certify a perfect frame. REVIEW means a substantial deviation or measurement uncertainty. REJECT requires strong, coherent transient sky structure, agreement between cloud/flux/star-loss measurements, thin cloud texture on an already-flagged frame that dims the stars beneath it relative to the rest of the exposure, severe combined morphology degradation, stellar elongation confirmed on the same matched reference stars (the roundness outliers stacking filters discard), or catastrophic star disappearance. Small ellipticity variations alone do not trigger review.
The earlier engine missed obvious clouds and falsely reviewed a clear frame. Its rolling background baselines and detection-only flux measurements have been replaced. Analysis-version changes request reanalysis while preserving manual decisions. Display changes have their own cache version, so preview upgrades do not invalidate quality measurements. The earlier engine missed obvious clouds and falsely reviewed a clear frame. Its rolling background baselines and detection-only flux measurements have been replaced. Analysis-version changes request reanalysis while preserving manual decisions. Display changes have their own cache version, so preview upgrades do not invalidate quality measurements.

View file

@ -6,7 +6,7 @@ The supplied 1,920 originals cover four targets and five sessions, with 2160×38
The first algorithm failed real owner-reviewed examples: cloud structure inflated detected-star counts; flux only sampled surviving detections; rolling baselines absorbed prolonged cloud; a small ellipticity deviation reviewed a clear image. The v2 design replaces the cloud measurements, reference construction and classification policy. Rejection counts are not a target or a validation criterion. The first algorithm failed real owner-reviewed examples: cloud structure inflated detected-star counts; flux only sampled surviving detections; rolling baselines absorbed prolonged cloud; a small ellipticity deviation reviewed a clear image. The v2 design replaces the cloud measurements, reference construction and classification policy. Rejection counts are not a target or a validation criterion.
Version 1.1.1 refines this policy with geometric fit diagnostics, local cloud-aperture corroboration, and matched-star morphology checks. The original v2 results remain a baseline; see [the 1.1.1 comparison](algorithm-1.1.1-validation.md) for the measurements and limits of the new validation. Version 1.1.1 refines this policy with geometric fit diagnostics, local cloud-aperture corroboration, and matched-star morphology checks. Version 1.1.6 adds thin-cloud texture with same-exposure differential photometry; 1.1.7 adds moderate-cloud corroboration and confirmed-elongation rejection. The original v2 results remain a baseline; see [the 1.1.1 comparison](algorithm-1.1.1-validation.md) for the measurements and limits of the new validation.
## Components ## Components
@ -24,6 +24,7 @@ Additional detectors can add measurements independently. A future AI reviewer ca
4. Robustly remove each map's additive offset and planar gradient. Form an aligned median background map, measure transient residuals, and rebuild three times from the least transient 40% of exposures. This fraction constructs a reference; it is **not** a rejection quota. Persistent target nebulosity belongs to the reference. Smooth sky gradients and offsets are removed rather than interpreted as cloud. 4. Robustly remove each map's additive offset and planar gradient. Form an aligned median background map, measure transient residuals, and rebuild three times from the least transient 40% of exposures. This fraction constructs a reference; it is **not** a rejection quota. Persistent target nebulosity belongs to the reference. Smooth sky gradients and offsets are removed rather than interpreted as cloud.
5. Read each exposure once more, sequentially, for signed aperture photometry at up to 600 reference coordinates. A local annulus subtracts sky. Reference brightness establishes aperture eligibility; a star need not be detected in the tested exposure. Median fluxes from reference exposures normalize global and 3×4 regional transparency. This addresses survivor bias. Saturated apertures and positions outside the field are excluded explicitly. 5. Read each exposure once more, sequentially, for signed aperture photometry at up to 600 reference coordinates. A local annulus subtracts sky. Reference brightness establishes aperture eligibility; a star need not be detected in the tested exposure. Median fluxes from reference exposures normalize global and 3×4 regional transparency. This addresses survivor bias. Saturated apertures and positions outside the field are excluded explicitly.
6. Compare 960 aligned sky cells with the reference. Cell scatter comes from reference-frame residual MAD with a floor relative to measured image noise. Store a mask above five times that scatter, affected overlap fraction, largest connected component, 95th-percentile significance, residual ADU, aperture counts and reference overlap. These are named evidence, not an opaque combined score. 6. Compare 960 aligned sky cells with the reference. Cell scatter comes from reference-frame residual MAD with a floor relative to measured image noise. Store a mask above five times that scatter, affected overlap fraction, largest connected component, 95th-percentile significance, residual ADU, aperture counts and reference overlap. These are named evidence, not an opaque combined score.
7. Measure thin-cloud texture separately. Remove a robust quadratic surface, not only a plane, from each aligned residual, then average each cell with its 3×3 neighbors. Divide by the per-cell scatter that reference exposures show for the same smoothed statistic; the floor is half the median of those scatters. Cells above four times scatter form a texture mask. Store the 98th-percentile texture significance, affected and largest connected fraction. Compare the median forced flux of reference apertures inside the mask with apertures in clear cells (below twice scatter) of the same exposure. Normalize that inside/outside ratio by the same apertures in the nearest 40 reference exposures and divide its loss by their MAD, with a 1% floor. Global transparency, seeing and airmass changes cancel in this differential ratio; a sky-only gradient leaves it near one.
Grid background estimation and local aperture subtraction are standard image-analysis techniques; see [Photutils background documentation](https://photutils.readthedocs.io/en/stable/api/photutils.background.Background2D.html). This implementation is independent C#, using the supplied data to establish its comparison distributions. Grid background estimation and local aperture subtraction are standard image-analysis techniques; see [Photutils background documentation](https://photutils.readthedocs.io/en/stable/api/photutils.background.Background2D.html). This implementation is independent C#, using the supplied data to establish its comparison distributions.
@ -36,8 +37,11 @@ REJECT evidence routes are explicit:
- Strong spatial structure: at least 25× reference scatter at the 95th percentile, at least 8% affected overlap and a connected area of at least 3.5%. A lone sky signal must be overwhelming before discarding integration; weaker coherent structure needs stellar corroboration or routes to REVIEW. - Strong spatial structure: at least 25× reference scatter at the 95th percentile, at least 8% affected overlap and a connected area of at least 3.5%. A lone sky signal must be overwhelming before discarding integration; weaker coherent structure needs stellar corroboration or routes to REVIEW.
- Moderate coherent spatial structure plus substantial global flux loss, regional forced-flux loss or detected-star loss. - Moderate coherent spatial structure plus substantial global flux loss, regional forced-flux loss or detected-star loss.
- Coherent structure at least 8× reference scatter, at least 8% affected overlap, and a connected anomalous area of at least 3.5%, corroborated by positive excess-sky coverage of at least 8% and a positive connected area of at least 3.5%. At least 20 reference apertures in two regions inside that excess sky must show below 90% of nearby same-aperture flux, with at least three times the larger of reference scatter, a 3% floor, and propagated local photometry uncertainty. Affected-aperture comparisons use the nearest 40 reference members, excluding the tested exposure, and require at least 12 valid comparison frames. - Coherent structure at least 8× reference scatter, at least 8% affected overlap, and a connected anomalous area of at least 3.5%, corroborated by positive excess-sky coverage of at least 8% and a positive connected area of at least 3.5%. At least 20 reference apertures in two regions inside that excess sky must show below 90% of nearby same-aperture flux, with at least three times the larger of reference scatter, a 3% floor, and propagated local photometry uncertainty. Affected-aperture comparisons use the nearest 40 reference members, excluding the tested exposure, and require at least 12 valid comparison frames.
- Thin cloud on an exposure already routed to REVIEW by another measurement: texture significance at least 10, a connected textured area of at least 5%, at least 20 apertures both inside and outside the texture, and stars inside at most 98% of their clear-cell flux with a loss of at least 2.5 times nearby reference scatter. Applying real cloud masks to clear exposures put 0.4–0.6% of differential deviations at or above 2.5, and clear exposures do not reach the texture prerequisite. This route never rejects an otherwise clean KEEP.
- Moderate thin cloud on an exposure the planar structure detector already flags (at least 5× scatter over 2% of the overlap): texture significance at least 20 with the same connectivity and aperture requirements, inside/outside dimming of at least 1.5% and 1.5 times scatter, and independently at least 20 excess-sky apertures in two regions at or below 93% of nearby same-aperture flux with at least 2.5 times scatter.
- Severe global flux loss (below 60% of clear-frame baseline) with substantial detected-star loss. - Severe global flux loss (below 60% of clear-frame baseline) with substantial detected-star loss.
- Severe combined stellar width and ellipticity degradation, or almost complete star disappearance relative to a rich reference field. - Severe combined stellar width and ellipticity degradation, or almost complete star disappearance relative to a rich reference field.
- Confirmed elongation: an existing elongation flag (at least four scatters and 0.15 above the nearby ellipticity baseline) that the same matched reference stars confirm. This requires at least 50 matched stars and 12 nearby reference frames, uncertainty at most 0.025, and a median change whose lower three-standard-error bound is at least 0.10, the same limit below which a flag is dismissed. Changes between the two limits stay REVIEW. Stacking workflows discard such roundness outliers; for example, Siril's Seestar script applies `-filter-round=2.5k`. On both supplied NGC 1432 nights, 22 of 38 confirmed frames fall below Siril's own roundness cutoff and the rest lie near it. Every confirmed frame exceeds an eccentricity-equivalent of 0.6. Unconfirmed or imprecise flags remain REVIEW.
Automatic rejection requires enough comparable frames, valid time and adequate aligned overlap. Ordinary spatial rejection also requires verified geometry: at least 20 tight correspondences, at least 80% of correspondences within the width-scaled tight tolerance, three regions with at least three tight matches each, and a spread of at least 15% of the image width and height. The median residual must be at most the larger of 0.5 original pixels and 0.2× reference width; the 95th percentile must be at most the larger of one original pixel and 0.5× reference width. Transform scale must remain between 0.975 and 1.025. Missing stars alone no longer veto a cloud rejection when geometry and aperture coverage are verified; low star survival still cannot certify KEEP. Catalog-only classification retains its previous match-fraction safeguard. Automatic rejection requires enough comparable frames, valid time and adequate aligned overlap. Ordinary spatial rejection also requires verified geometry: at least 20 tight correspondences, at least 80% of correspondences within the width-scaled tight tolerance, three regions with at least three tight matches each, and a spread of at least 15% of the image width and height. The median residual must be at most the larger of 0.5 original pixels and 0.2× reference width; the 95th percentile must be at most the larger of one original pixel and 0.5× reference width. Transform scale must remain between 0.975 and 1.025. Missing stars alone no longer veto a cloud rejection when geometry and aperture coverage are verified; low star survival still cannot certify KEEP. Catalog-only classification retains its previous match-fraction safeguard.
@ -47,7 +51,7 @@ These significance and effect-size limits are **engineering policy, not calibrat
## Limits that need validation ## Limits that need validation
A wholly uniform, cloudy session may lack any internally observable clear reference. Clouds that resemble a smooth gradient and have little detectable attenuation are difficult. Dense nebulosity, alignment failures, crowded fields, large drift/rotation and changing PSFs can bias maps or fixed-aperture flux. The current model removes only a planar sky trend; a legitimate time-varying nonlinear sky pattern can require review. The red overlay identifies anomalous sky structure, not a pixel-accurate physical cloud segmentation. A wholly uniform, cloudy session may lack any internally observable clear reference. Clouds that resemble a smooth gradient and have little detectable attenuation are difficult. Dense nebulosity, alignment failures, crowded fields, large drift/rotation and changing PSFs can bias maps or fixed-aperture flux. The main structure model removes only a planar sky trend; a legitimate time-varying nonlinear sky pattern can require review. The thin-cloud texture also removes quadratic curvature, but requires stellar dimming beneath it before rejecting. Faint cirrus on an otherwise clean exposure remains KEEP: its effect on a stack has not been validated. The red overlay identifies anomalous sky structure, not a pixel-accurate physical cloud segmentation.
Small sessions and unreliable references cannot automatically reject. Reference stability also checks reference-map residuals against measured pixel noise; a wholly unstable comparison population routes to REVIEW. This does not detect a perfectly uniform, consistently attenuated session. Human overrides remain separate from automatic results. Do not claim the method matches manual Siril selection until independently processed stacks support that claim. Small sessions and unreliable references cannot automatically reject. Reference stability also checks reference-map residuals against measured pixel noise; a wholly unstable comparison population routes to REVIEW. This does not detect a perfectly uniform, consistently attenuated session. Human overrides remain separate from automatic results. Do not claim the method matches manual Siril selection until independently processed stacks support that claim.
@ -57,7 +61,11 @@ Version 1.1.0 selects up to 16 workers from CPU capacity, leaving two logical pr
Small JSON metadata stores decisions, notes, evidence and compact masks. Binary versioned caches hold stars, sky maps and forced photometry, validated against source size and modification time and reference identity. A new engine version invalidates analysis without losing human labels. Repeated analysis uses cached measurements and forced apertures when valid. Project writes replace a temporary file atomically. Cancellation leaves analysis incomplete and export disabled. Small JSON metadata stores decisions, notes, evidence and compact masks. Binary versioned caches hold stars, sky maps and forced photometry, validated against source size and modification time and reference identity. A new engine version invalidates analysis without losing human labels. Repeated analysis uses cached measurements and forced apertures when valid. Project writes replace a temporary file atomically. Cancellation leaves analysis incomplete and export disabled.
Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. The screen transfer uses a noise-aware black point and adjustable median brightness; **Nebula view** averages neighboring display samples further. This avoids nearest-pixel aliasing and the original excessively bright, noisy stretch. Prepared display statistics are cached in the viewer so slider changes remain responsive. Disk loading and first-time thumbnail creation run off the UI thread, with cancellation and a single preview-loading gate preventing queued FITS reads during rapid navigation. Old projects regenerate only requested displays on demand. Display caches have a separate version. They contain compressed, linear, area-averaged thumbnails rather than a permanently stretched byte image. **Frame view** retains its noise-aware black point and adjustable median brightness. **Denoised** is the only alternative. It performs non-local means on the linear thumbnail using 5×5 patches, a 13×13 search window, reflected borders, noise-bias subtraction and a filter strength of 0.8 times the estimated noise sigma. Its black point, white point and normalized median come from the original thumbnail; they are never recomputed from the denoised result. This prevents the stretch from amplifying residual noise after denoising. It adds 0.07 to the requested display median, matching the approved samples' default brightness of 0.25 at slider value 0.18.
The previous Nebula, Asinh and Color nebula modes are removed. The denoised result stays in the selected viewer's memory and is computed only when requested. It needs no new disk cache or FITS reader and works on monochrome and Bayer-derived grayscale thumbnails alike. Existing linear caches remain compatible, and existing color caches are simply unused. The analysis path, classifications and original FITS files are unaffected.
Prepared display statistics and the denoised plane are retained in the viewer so slider changes remain responsive. Loading and denoising run off the UI thread, with cancellation, atomic memory reservations and a single preview-loading gate preventing queued work during rapid navigation. The original Frame preview remains available while denoising runs. Both comparison panes use the selected mode and shared zoom/pan. Old projects regenerate only requested displays on demand. Denoising is a viewing aid and may soften weak detail; Frame view and source-star inspection remain available for judging unfiltered morphology.
The preview is not an input to classification. Source-star inspection reads two originals, maps identical stars through their stored alignment, and displays enlarged source superpixels without interpolation. Crops are independently normalized to judge morphology. See [Siril's screen-transfer discussion](https://siril.readthedocs.io/en/latest/processing/stretching.html) for the distinction between display stretching and linear image data. The preview is not an input to classification. Source-star inspection reads two originals, maps identical stars through their stored alignment, and displays enlarged source superpixels without interpolation. Crops are independently normalized to judge morphology. See [Siril's screen-transfer discussion](https://siril.readthedocs.io/en/latest/processing/stretching.html) for the distinction between display stretching and linear image data.

View file

@ -2,7 +2,7 @@
The owner selected the Graphite Studio palette and Plum Atlas layout from the standalone concepts. The application combines their charcoal backgrounds, silver accents, restrained decision colors, compact summaries and three-column workspace. The exposure queue is on the left, the largest column holds the preview, and the right column contains one selectable quality graph above permanently accessible evidence and measurements. A compact selector above the workspace switches sessions, including All sessions. Filtering, sorting, graph selection, keyboard review, saved overrides, undo and accepted-frame export remain available. The owner selected the Graphite Studio palette and Plum Atlas layout from the standalone concepts. The application combines their charcoal backgrounds, silver accents, restrained decision colors, compact summaries and three-column workspace. The exposure queue is on the left, the largest column holds the preview, and the right column contains one selectable quality graph above permanently accessible evidence and measurements. A compact selector above the workspace switches sessions, including All sessions. Filtering, sorting, graph selection, keyboard review, saved overrides, undo and accepted-frame export remain available.
Frame/Nebula view, cloud overlay and nearby comparison sit above the preview. Preview stretch has a dedicated 48-pixel row below it and a visible silver thumb. The single verdict/time caption, filename and decision buttons follow the stretch. Long evidence lines present a concise first clause, with their complete engine-generated message available on hover. The evidence panel scrolls when needed; no measurements or saved explanations are discarded. The Frame view / Denoised dropdown, cloud overlay and nearby comparison sit above the preview. Denoised uses the approved patch-based noise reduction with the original thumbnail's stretch parameters. Nebula, Asinh and Color nebula options are removed. Preview stretch has a dedicated 48-pixel row below it and a visible silver thumb. The single verdict/time caption, filename and decision buttons follow the stretch. Long evidence lines present a concise first clause, with their complete engine-generated message available on hover. The evidence panel scrolls when needed; no measurements or saved explanations are discarded.
The header now has a plain graphite background. Its height is reduced from 100 to 74 logical pixels: a 36-pixel native caption row and a 38-pixel project/action row. The project name and light/session counts sit on one line. Removing the photographic background also removes its display-bitmap allocation; the original asset remains preserved with the standalone design concepts. The header now has a plain graphite background. Its height is reduced from 100 to 74 logical pixels: a 36-pixel native caption row and a 38-pixel project/action row. The project name and light/session counts sit on one line. Removing the photographic background also removes its display-bitmap allocation; the original asset remains preserved with the standalone design concepts.

View file

@ -0,0 +1,9 @@
# AstroFrame 1.1.2
- Show live process memory usage in the bottom status bar during analysis and export, and hide it when processing ends.
- Give the processing progress bar a contrasting blue fill and a slightly thicker track.
- Use muted green, gold and rose colors in the quality graph to match the rest of the interface.
- Apply the spatial overlay to both selected and nearby frames when comparing, including after switching frames or reopening comparison.
- Add **Inspect elongation** beside **Reset view**. Enlarge strong source stars without smoothing, highlight their fitted ellipse and major/minor axes, and show crop ellipticity alongside the frame measurements. Shape guides can be hidden. A suitable aligned KEEP exposure supplies matching comparison stars; selected stars remain available when no comparison exists.
Validation: 87 engine checks, 23 updater checks, 10 mocked publisher checks, and isolated Windows desktop interaction/rendering checks at 96 and 144 DPI. Source reads, star matching, rotated elongation, missing comparisons, cancellation and changed-source refusal are covered. Development verification uses copied workspace caches and leaves the installed application untouched. The server release workflow builds Windows and Linux packages and checks the packaged Linux settings page.

View file

@ -0,0 +1,10 @@
# AstroFrame 1.1.3
- Rework **Nebula view** to reveal faint diffuse structure and thin filaments. Suppress small stars and noise at the existing preview resolution, then apply a background-aware stretch. NGC 6960's Veil filaments are now visible in the tested single exposures.
- Add **Asinh view**, an alternative adjustable stretch with softer highlights.
- Add **Color nebula** from recognized FITS Bayer channels. Neutralize the sky, smooth uncertain color and preserve neutral bright highlights. Monochrome and unknown Bayer layouts display the grayscale nebula preview instead of fabricated color.
- Apply every viewing mode to both comparison panes while preserving shared zoom and pan. Linear color previews are cached on demand without invalidating quality measurements.
These are display-only changes. Original FITS files, analysis, classifications and manual decisions are unaffected. Single exposures can remain noisy; color is a viewing aid rather than calibrated astrophotography.
Validation: 135 engine, 23 updater, 10 mocked publisher and 63 isolated Windows interaction checks, with rendering at 96 and 144 DPI. Covers faint-filament visibility, stretch brightness, Bayer patterns and offsets, color/cache integrity, monochrome fallback, rapid navigation, cancellation and source-file preservation. Visually inspected 18 real exposures across NGC 6960, NGC 7000, IC 1805, NGC 281, M33 and NGC 1432. Verification uses copied workspace caches and leaves the installed application untouched. The server workflow builds Windows and Linux packages and checks the packaged Linux settings page.

View file

@ -0,0 +1,9 @@
# AstroFrame 1.1.4
- Keep the preview dropdown with just **Frame view** and **Denoised**. Remove Nebula view, Asinh view and Color nebula.
- Add the approved patch-based denoising alternative. Keep the stretch parameters derived from the original thumbnail so residual noise is not amplified into blotches. The denoised preview is slightly brighter by default and still supports the Preview stretch slider.
- Apply the selected mode to both comparison panes, preserving zoom, pan and overlays. Compute denoising in the background only when requested, reuse it for brightness changes, and cancel obsolete work when switching exposures.
Frame view's rendering and existing linear caches are unchanged. Display processing never changes original FITS files, quality measurements, classifications or manual decisions.
Validation: 95 engine, 23 updater, 10 mocked publisher and 65 isolated Windows interaction checks, with rendering at 96 and 144 DPI. Covers noise reduction, retained stretch parameters, stars and diffuse signal, constant fields, reflected borders, input preservation and cancellation. Across 11 exposures from all seven sample targets, the production renderer matches the approved samples within one gray level out of 255; Frame outputs match their previous pixels exactly. Verification uses workspace fixtures and leaves the installed app untouched. The server workflow builds Windows and Linux packages and checks the packaged Linux settings page.

View file

@ -0,0 +1,9 @@
# AstroFrame 1.1.5
- Choose what **Compare** shows: **Nearby frame**, the exposure closest in capture time, or **Best frame**, the strongest kept exposure in the selected exposure's session. The dropdown appears next to Compare while comparison is on.
- Best frame picks the highest quality score among kept, measured exposures, then the sharpest stars (lowest FWHM), then the strongest stellar flux. If the selected exposure is itself the best, the next best is shown. The pane caption reads **Best**, and its tooltip lists the score and FWHM.
- Nearby frame is the default, and each launch starts on Nearby. Overlay, Denoised, stretch, zoom and pan apply to both choices.
Comparison choice is display-only: it never changes measurements, classifications or manual decisions.
Validation: 95 engine, 23 updater, 10 mocked publisher and 77 isolated Windows interaction checks (including 11 new comparison checks), with rendering at 96 and 144 DPI on a copied workspace fixture. Verification leaves the installed app untouched. The server workflow builds Windows and Linux packages and checks the packaged Linux settings page.

View file

@ -0,0 +1,11 @@
# AstroFrame 1.1.6
Resolves more thin-cloud exposures automatically instead of leaving them for manual review.
- Adds a thin-cloud texture measurement. Each aligned sky map has smooth curvature removed, neighboring cells averaged, and the result compared with the scatter of clear reference exposures. Faint cloud bands that previously fell below the sky-structure threshold now stand out clearly.
- Corroborates that texture with the stars beneath it. Forced photometry inside the texture is compared with clear parts of the same exposure and then with the same apertures in nearby clear frames. Global transparency, seeing and airmass changes cancel out; a sky gradient alone does not dim stars and cannot trigger rejection.
- An exposure already flagged for Review becomes Reject only when both measurements agree. The new route never rejects an exposure that would otherwise be Keep, and it adds no new Review triggers. Decision evidence explains the texture coverage and the measured dimming.
In the supplied 1,053-frame NGC 1432 project, Review decreases from 48 to 36 and Reject increases from 100 to 112. All 12 changed exposures show visible cloud bands. Every Keep is unchanged. Replays of eleven other saved projects (about 5,000 exposures, including the M31 sessions with manual decisions) changed 15 more Review exposures to Reject. All were inspected: cloud passages, plus one dawn-twilight exposure next to frames the existing rules already reject. No Keep and no manually labeled exposure changed. The remaining NGC 1432 Reviews are mostly stellar-elongation flags, which this release does not change.
Analysis time and memory use are essentially unchanged. Old automatic measurements require reanalysis; manual decisions are retained. Engine (100) and updater (23) checks pass on the versioned source. Windows and Linux update channels are included.

View file

@ -0,0 +1,10 @@
# AstroFrame 1.1.7
Resolves the remaining moderately clouded exposures and trailed-star exposures automatically, so very few frames are left for manual review.
- **Moderate thin cloud.** An exposure the sky-structure detector already flags becomes Reject when strong cloud texture is backed by two independent, moderate signs of dimming: stars inside the texture are fainter than stars in clear parts of the same exposure, and the excess-sky apertures are fainter than in nearby frames. A light flash or other sky-only artifact that dims no stars still stays Review.
- **Confirmed star elongation.** Elongation is now rejected when the same matched reference stars confirm it well beyond measurement uncertainty. This follows common stacking practice: Siril's Seestar preprocessing script discards roundness outliers (`-filter-round=2.5k`), and PixInsight users commonly treat eccentricity above 0.6 as unusable. On both supplied NGC 1432 nights, 22 of 38 confirmed frames fall below Siril's own roundness cutoff and the rest sit near it; all exceed an eccentricity-equivalent of 0.6. Elongation that is imprecise or only marginally confirmed still stays Review.
In the supplied 1,053-frame NGC 1432 project, Review decreases from 36 (1.1.6) to 1, an exposure with a full-width light flash, and from 48 in 1.1.5. Reject increases to 147. Every Keep is unchanged. Across eleven other saved projects (about 5,000 exposures), Review decreases from 337 to 153; every change is Review to Reject, and no Keep changed. Changed frames were checked against previews and matched star crops. Most of the remaining Reviews in one M33 session are high-background (twilight or moonlit) exposures, which this release does not change.
Analysis time and memory use are unchanged. Old automatic measurements require reanalysis; manual decisions are retained. Engine (102) and updater (23) checks pass on the versioned source. Windows and Linux update channels are included.

View file

@ -121,6 +121,14 @@ For later releases, use the automatic tag workflow above, or validate/build/publ
## Verification ## Verification
For preview and processing-status changes, build the source and run the isolated Windows diagnostic against a saved project analyzed by the current engine. The FITS sources must still be available. The helper copies its metadata and caches into a fresh workspace folder before exercising controls or saving test decisions:
```powershell
./tools/Verify-Preview.ps1 -FixtureProject 'path/to/saved-project' -Output artifacts/preview-verification
```
This checks comparison overlays, zoom/pan, Frame and Denoised in both panes, on-demand denoising, rapid frame/mode changes, monochrome sources, processing-memory visibility, elongation crops and guide toggling, absent comparisons, loading cancellation, and native window controls. It renders normal and minimum-size controls at 96 and 144 DPI. Inspect the PNG files in the output's `qa` directory. It launches only the source build in diagnostic mode, which bypasses installed settings and updates. Source `--capture` diagnostics accept `--preview=0` (Frame) or `--preview=1` (Denoised) for real-exposure visual checks against copied workspace projects.
`./tools/Verify-ReleaseAutomation.ps1` exercises version/tag mismatch, upload failure, draft resumption, conflicting assets, immutable published releases and package integrity with a mocked release API. It never publishes a real release. `./tools/Verify-ReleaseAutomation.ps1` exercises version/tag mismatch, upload failure, draft resumption, conflicting assets, immutable published releases and package integrity with a mocked release API. It never publishes a real release.
`tests/AstroFrame.Updates.Validation` covers settings recovery, network failures, concurrent checks, restart safety, save failure, real package checksums, corruption rejection and downgrade prevention. An optional release-feed argument adds real-package checks: `tests/AstroFrame.Updates.Validation` covers settings recovery, network failures, concurrent checks, restart safety, save failure, real package checksums, corruption rejection and downgrade prevention. An optional release-feed argument adds real-package checks:

View file

@ -21,11 +21,14 @@ public sealed partial class MainWindow
bitmap.Render(this);bitmap.Save(System.IO.Path.Combine(output,name+".png")); bitmap.Render(this);bitmap.Save(System.IO.Path.Combine(output,name+".png"));
} }
Check(project==null&&selected==null&&visible.Count==0,"ordinary startup starts a fresh session"); Check(project==null&&selected==null&&visible.Count==0,"ordinary startup starts a fresh session");
Check(compareTarget.SelectedIndex==0&&!compareTarget.IsVisible,"each launch starts comparing against the nearby exposure");
Check(!memoryUsage.IsVisible&&!memoryTimer.IsEnabled&&!progress.IsVisible&&!inspectElongation.IsEnabled,"idle startup hides processing stats and disables star inspection");
Check(Background==Palette.Background&&TransparencyBackgroundFallback==Palette.Background&&NativeWindowBackground.IsApplied(this),"managed and native startup backgrounds match the application grey"); Check(Background==Palette.Background&&TransparencyBackgroundFallback==Palette.Background&&NativeWindowBackground.IsApplied(this),"managed and native startup backgrounds match the application grey");
Capture("fresh-session"); Capture("fresh-session");
await updates.Check();Check(settingsButton.Background==Palette.Update&&settingsButton.Classes.Contains("update-available"),"available update turns Settings cerulean blue"); await updates.Check();Check(settingsButton.Background==Palette.Update&&settingsButton.Classes.Contains("update-available"),"available update turns Settings cerulean blue");
UpdateSettingsButton(false);Check(settingsButton.Background==Palette.Raised&&!settingsButton.Classes.Contains("update-available"),"no update restores the normal Settings color");UpdateSettingsButton(true); UpdateSettingsButton(false);Check(settingsButton.Background==Palette.Raised&&!settingsButton.Classes.Contains("update-available"),"no update restores the normal Settings color");UpdateSettingsButton(true);
LoadProject(System.IO.Path.GetFullPath(fixture));await WaitForPreviews();await Task.Delay(200);Check(preview.HasImage,"fixture preview loads"); LoadProject(System.IO.Path.GetFullPath(fixture));await WaitForPreviews();await Task.Delay(200);Check(preview.HasImage,"fixture preview loads");
Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&!preview.HasDenoised&&!comparison.HasDenoised,"Frame is the default and does not compute denoising before selection");
using var pointer=new Pointer(Pointer.GetNextFreeId(),PointerType.Mouse,true); using var pointer=new Pointer(Pointer.GetNextFreeId(),PointerType.Mouse,true);
var idle=new PointerPointProperties(RawInputModifiers.None,PointerUpdateKind.Other); var idle=new PointerPointProperties(RawInputModifiers.None,PointerUpdateKind.Other);
var held=new PointerPointProperties(RawInputModifiers.LeftMouseButton,PointerUpdateKind.LeftButtonPressed); var held=new PointerPointProperties(RawInputModifiers.LeftMouseButton,PointerUpdateKind.LeftButtonPressed);
@ -41,12 +44,72 @@ public sealed partial class MainWindow
double zoom=viewport.Zoom;var pan=viewport.Pan; double zoom=viewport.Zoom;var pan=viewport.Pan;
Select(visible.Skip(1).First());await WaitForPreviews();Check(viewport.Zoom==zoom&&viewport.Pan==pan,"zoom and position persist when switching frames"); Select(visible.Skip(1).First());await WaitForPreviews();Check(viewport.Zoom==zoom&&viewport.Pan==pan,"zoom and position persist when switching frames");
previewMode.SelectedIndex=1;displayStretch.Value=.26;spatial.IsChecked=true;compare.IsChecked=true;await WaitForPreviews();await Task.Delay(150); previewMode.SelectedIndex=1;displayStretch.Value=.26;spatial.IsChecked=true;compare.IsChecked=true;await WaitForPreviews();await Task.Delay(150);
Check(preview.Viewport==comparison.Viewport&&viewport.Zoom==zoom&&viewport.Pan==pan,"comparison, overlay and nebula view preserve the same viewport"); Check(preview.Viewport==comparison.Viewport&&viewport.Zoom==zoom&&viewport.Pan==pan,"comparison, overlay and denoised view preserve the same viewport");
Capture("comparison-overlay");
Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay applies to both loaded comparison frames");
Capture("zoom-overlay-update");Width=1120;Height=740;await Task.Delay(150);Capture("minimum-zoom",144); Capture("zoom-overlay-update");Width=1120;Height=740;await Task.Delay(150);Capture("minimum-zoom",144);
resetView.RaiseEvent(new RoutedEventArgs(Avalonia.Controls.Button.ClickEvent));Check(viewport.Zoom==1&&viewport.Pan==default,"Reset view resets both zoom and position"); resetView.RaiseEvent(new RoutedEventArgs(Avalonia.Controls.Button.ClickEvent));Check(viewport.Zoom==1&&viewport.Pan==default,"Reset view resets both zoom and position");
var bounds=resetView.TranslatePoint(default,this)!.Value; var bounds=resetView.TranslatePoint(default,this)!.Value;
Check(bounds.X>=0&&bounds.X+resetView.Bounds.Width<=Bounds.Width,"Reset view stays visible at minimum window width"); Check(bounds.X>=0&&bounds.X+resetView.Bounds.Width<=Bounds.Width,"Reset view stays visible at minimum window width");
Capture("minimum-reset",144); Capture("minimum-reset",144);
spatial.IsChecked=false;Check(!preview.Spatial&&!comparison.Spatial,"Overlay turns off on both frames");
spatial.IsChecked=true;compare.IsChecked=false;compare.IsChecked=true;Select(visible[0]);await WaitForPreviews();await Task.Delay(150);
Check(preview.Spatial&&comparison.Spatial&&comparison.HasImage,"Overlay persists on both panes after toggling comparison and changing frame");
Capture("comparison-fit",144);
Check(compareTarget.IsVisible&&compareTarget.Items.Cast<string>().SequenceEqual(new[]{"Nearby frame","Best frame"})&&compareTarget.SelectedIndex==0&&comparison.Caption=="Nearby","comparison target offers Nearby and Best and defaults to Nearby");
var nearest=project!.Frames.Where(f=>f.Session==selected!.Session&&f.Id!=selected.Id&&f.Timestamp.HasValue&&f.Error=="").MinBy(f=>Math.Abs((f.Timestamp!.Value-selected!.Timestamp!.Value).TotalSeconds));
Check(comparison.Frame==nearest,"Nearby compares the exposure closest in capture time");
compareTarget.SelectedIndex=1;await WaitForPreviews();await Task.Delay(150);var bestFrame=comparison.Frame;
var kept=project.Frames.Where(f=>f.Session==selected!.Session&&f.Id!=selected.Id&&f.Error==""&&f.Measured&&f.Effective==AstroFrame.Engine.Verdict.Keep&&f.Fwhm>0).ToArray();
Check(bestFrame!=null&&comparison.Caption=="Best","Best selects a comparison exposure ("+kept.Length+" kept candidates)");
Check(comparison.HasImage,"Best comparison preview loads");
Check(kept.Contains(bestFrame!)&&!kept.Any(f=>f.Score>bestFrame!.Score||f.Score==bestFrame!.Score&&f.Fwhm<bestFrame.Fwhm),"Best compares the highest-scoring, sharpest kept exposure in the session");
Check(preview.Spatial&&comparison.Spatial&&preview.Viewport==comparison.Viewport,"Best comparison keeps Overlay and the shared viewport");
Capture("best-comparison",144);Width=1120;Height=740;await Task.Delay(150);
var targetBounds=compareTarget.TranslatePoint(default,this)!.Value;
Check(targetBounds.X>=0&&targetBounds.X+compareTarget.Bounds.Width<=Bounds.Width&&compareTarget.Bounds.Width>0,"comparison target dropdown stays visible at minimum window width");Capture("best-comparison-minimum",144);
Select(bestFrame!);await WaitForPreviews();Check(comparison.Frame!=null&&comparison.Frame!=selected&&comparison.Caption=="Best","selecting the best exposure compares the next best instead of itself");
compare.IsChecked=false;Check(!compareTarget.IsVisible,"comparison target hides with Compare");compare.IsChecked=true;
Check(compareTarget.SelectedIndex==1&&comparison.Caption=="Best","comparison target persists while toggling Compare in a session");
compareTarget.SelectedIndex=0;Select(visible[0]);await WaitForPreviews();Check(comparison.Caption=="Nearby"&&comparison.Frame!=null&&comparison.Frame.Session==selected!.Session,"switching back restores the nearby comparison");
Check(previewMode.Items.Cast<string>().SequenceEqual(new[]{"Frame view","Denoised"}),"preview dropdown contains only Frame view and Denoised");
Check(preview.HasDenoised&&comparison.HasDenoised&&preview.Mode==AstroFrame.Engine.PreviewMode.Denoised&&comparison.Mode==preview.Mode,"Denoised applies to both comparison panes");Capture("denoised-comparison",144);
double retainedZoom=viewport.Zoom;var retainedPan=viewport.Pan;previewMode.SelectedIndex=0;previewMode.SelectedIndex=1;await WaitForPreviews();
Check(viewport.Zoom==retainedZoom&&viewport.Pan==retainedPan,"switching Frame and Denoised retains shared zoom and pan");
Select(visible[1]);await WaitForPreviews();Check(preview.HasDenoised&&comparison.HasDenoised,"denoised mode survives exposure changes");
foreach(var frame in visible.Take(6))Select(frame);previewMode.SelectedIndex=0;previewMode.SelectedIndex=1;await WaitForPreviews();
Check(preview.HasDenoised&&comparison.HasDenoised&&preview.Frame==selected,"rapid exposure and mode changes cancel stale denoising and retain the latest preview");
Select(visible[1]);await WaitForPreviews();
previewMode.SelectedIndex=0;Check(preview.Mode==AstroFrame.Engine.PreviewMode.Frame&&comparison.Mode==preview.Mode,"Frame view restores both original grayscale previews");
string monoPath=System.IO.Path.Combine(output,"mono-source.fit");var monoBytes=File.ReadAllBytes(selected!.Path);
using(var sourceStream=File.OpenRead(selected.Path))
{
var(_,headerBytes)=AstroFrame.Engine.Fits.ReadHeader(sourceStream);
for(int offset=0;offset<headerBytes;offset+=80)if(System.Text.Encoding.ASCII.GetString(monoBytes,offset,8)=="BAYERPAT")System.Text.Encoding.ASCII.GetBytes("COMMENT ").CopyTo(monoBytes,offset);
}
File.WriteAllBytes(monoPath,monoBytes);var monoFrame=AstroFrame.Engine.Fits.Inspect(monoPath);var monoView=new ExposureView();monoView.SetMode(AstroFrame.Engine.PreviewMode.Denoised);monoView.Load(output,monoFrame);await monoView.Loading;
Check(monoView.HasImage&&monoView.HasDenoised,"Denoised works with monochrome FITS sources");monoView.Dispose();previewMode.SelectedIndex=1;
Busy(true);progress.Value=57;status.Text="Analyzing lights · 57 / 100 · "+selected!.Name;await Task.Delay(1100);
Check(memoryUsage.IsVisible&&memoryTimer.IsEnabled&&memoryUsage.Text!.StartsWith("Memory: ")&&memoryUsage.Text.EndsWith(" MB"),"processing shows a live process memory statistic");
Check(!inspectElongation.IsEnabled,"star inspection is disabled during processing");
var memoryBounds=memoryUsage.TranslatePoint(default,this)!.Value;
Check(memoryBounds.X>=0&&memoryBounds.X+memoryUsage.Bounds.Width<=Bounds.Width&&status.Bounds.Right<=memoryBounds.X,"long processing filenames leave room for the memory statistic");
Capture("processing",144);Busy(false);
Check(!memoryUsage.IsVisible&&!memoryTimer.IsEnabled&&memoryUsage.Text==""&&!progress.IsVisible,"finishing processing stops the timer and removes the memory statistic");
Check(inspectElongation.IsEnabled,"selected measured frame enables star inspection");
inspectElongation.RaiseEvent(new RoutedEventArgs(Avalonia.Controls.Button.ClickEvent));var stars=starInspector!;await stars.Loading;await Task.Delay(150);
Check(stars.HasDetail&&stars.Crops.Count>0&&stars.Crops.Any(c=>c.Shape!=null),"Inspect elongation button opens enlarged source crops with fitted shape guides");
using(var starBitmap=new RenderTargetBitmap(new PixelSize((int)stars.Bounds.Width,(int)stars.Bounds.Height),new Vector(96,96))){starBitmap.Render(stars);starBitmap.Save(System.IO.Path.Combine(output,"elongation.png"));}
var guides=stars.GetVisualDescendants().OfType<CheckBox>().Single();guides.IsChecked=false;
Check(stars.Crops.All(c=>!c.ShowGuides),"shape guides can be hidden to inspect the original star pixels");
guides.IsChecked=true;stars.Width=660;stars.Height=520;await Task.Delay(150);
using(var starBitmap=new RenderTargetBitmap(new PixelSize((int)(stars.Bounds.Width*1.5),(int)(stars.Bounds.Height*1.5)),new Vector(144,144))){starBitmap.Render(stars);starBitmap.Save(System.IO.Path.Combine(output,"elongation-minimum.png"));}
stars.Close();Check(starInspector==null,"closing the elongation window releases it");
var single=new StarInspector(new AstroFrame.Engine.Project{Frames=[selected!]},projectDirectory,selected!);single.Show(this);await single.Loading;await Task.Delay(100);
Check(single.HasDetail&&single.Crops.Count>0&&single.Crops.Count<=8,"elongation window shows selected stars when no KEEP comparison exists");
using(var starBitmap=new RenderTargetBitmap(new PixelSize((int)single.Bounds.Width,(int)single.Bounds.Height),new Vector(96,96))){starBitmap.Render(single);starBitmap.Save(System.IO.Path.Combine(output,"elongation-single.png"));}
single.Close();inspectElongation.RaiseEvent(new RoutedEventArgs(Avalonia.Controls.Button.ClickEvent));var cancelledStars=starInspector!;cancelledStars.Close();await cancelledStars.Loading;
Check(starInspector==null&&!cancelledStars.HasDetail,"closing star inspection while loading cancels cleanly");
await SmokeTest(System.IO.Path.Combine(output,"smoke-checks.txt")); await SmokeTest(System.IO.Path.Combine(output,"smoke-checks.txt"));
File.WriteAllLines(System.IO.Path.Combine(output,"interaction-checks.txt"),results); File.WriteAllLines(System.IO.Path.Combine(output,"interaction-checks.txt"),results);
} }

View file

@ -26,8 +26,11 @@ public sealed partial class MainWindow:Window
readonly PreviewViewport viewport=new(); readonly PreviewViewport viewport=new();
readonly ExposureView preview,comparison; readonly ExposureView preview,comparison;
readonly Button resetView=Button("Reset view"); readonly Button resetView=Button("Reset view");
readonly Button inspectElongation=Button("Inspect elongation");
readonly DispatcherTimer memoryTimer=new(){Interval=TimeSpan.FromSeconds(1)};
StarInspector? starInspector;
readonly Border previewPanel,comparisonBorder,previewControls; readonly Border previewPanel,comparisonBorder,previewControls;
readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Nebula view"},SelectedIndex=0,MinWidth=150}; readonly ComboBox previewMode=new(){ItemsSource=new[]{"Frame view","Denoised"},SelectedIndex=0,MinWidth=150};
readonly Slider displayStretch=new(){Minimum=.08,Maximum=.40,Value=.18}; readonly Slider displayStretch=new(){Minimum=.08,Maximum=.40,Value=.18};
readonly StackPanel inspector=new(){Spacing=9}; readonly StackPanel inspector=new(){Spacing=9};
readonly Grid previewWorkspace=new(){ColumnDefinitions=new("*,0"),Margin=new(0,8,0,6)}; readonly Grid previewWorkspace=new(){ColumnDefinitions=new("*,0"),Margin=new(0,8,0,6)};
@ -36,11 +39,14 @@ public sealed partial class MainWindow:Window
readonly TextBlock exposureName=Palette.Label("",11,Palette.Muted),exposureStatus=Palette.Label("",12); readonly TextBlock exposureName=Palette.Label("",11,Palette.Muted),exposureStatus=Palette.Label("",12);
readonly TextBlock title=Palette.Label("Light frames",18),subtitle=Palette.Label("Choose a folder to begin",11,Palette.Muted); readonly TextBlock title=Palette.Label("Light frames",18),subtitle=Palette.Label("Choose a folder to begin",11,Palette.Muted);
readonly TextBlock status=Palette.Label("",11,Palette.Muted); readonly TextBlock status=Palette.Label("",11,Palette.Muted);
readonly TextBlock memoryUsage=Palette.Label("",11,Palette.Muted);
readonly TextBlock keep=Palette.Label("—",22,Palette.Keep),review=Palette.Label("—",22,Palette.Review),reject=Palette.Label("—",22,Palette.Reject),integration=Palette.Label("—",22); readonly TextBlock keep=Palette.Label("—",22,Palette.Keep),review=Palette.Label("—",22,Palette.Review),reject=Palette.Label("—",22,Palette.Reject),integration=Palette.Label("—",22);
readonly TextBlock keepTime=Palette.Label("",11,Palette.Muted),reviewTime=Palette.Label("",11,Palette.Muted),rejectTime=Palette.Label("",11,Palette.Muted),totalTime=Palette.Label("",11,Palette.Muted); readonly TextBlock keepTime=Palette.Label("",11,Palette.Muted),reviewTime=Palette.Label("",11,Palette.Muted),rejectTime=Palette.Label("",11,Palette.Muted),totalTime=Palette.Label("",11,Palette.Muted);
readonly ProgressBar progress=new(){Height=3,Minimum=0,Maximum=100,IsVisible=false}; readonly ProgressBar progress=new(){Height=5,Minimum=0,Maximum=100,IsVisible=false,Foreground=Palette.Progress,Background=Palette.Line};
readonly Button analyze=Button("Analyze lights",true),export=Button("Export accepted"),stop=Button("Cancel"); readonly Button analyze=Button("Analyze lights",true),export=Button("Export accepted"),stop=Button("Cancel");
readonly CheckBox spatial=new(){Content="Spatial overlay",FontSize=12},compare=new(){Content="Compare nearby",FontSize=12}; readonly CheckBox spatial=new(){Content="Spatial overlay",FontSize=12},compare=new(){Content="Compare nearby",FontSize=12};
// Not persisted: each launch starts comparing against the nearby exposure.
readonly ComboBox compareTarget=new(){ItemsSource=new[]{"Nearby frame","Best frame"},SelectedIndex=0,MinWidth=120,FontSize=11,IsVisible=false,Margin=new(10,0,0,0)};
Frame? selected;List<Frame> visible=[]; Frame? selected;List<Frame> visible=[];
readonly Stack<(Frame Frame,Verdict? Verdict,string Note,DateTime? At)> undo=[]; readonly Stack<(Frame Frame,Verdict? Verdict,string Note,DateTime? At)> undo=[];
public MainWindow() public MainWindow()
@ -54,7 +60,8 @@ public sealed partial class MainWindow:Window
var resetStretch=Button("Reset");resetStretch.Padding=new(9,5);resetStretch.FontSize=11;resetStretch.VerticalAlignment=VerticalAlignment.Center;resetStretch.Click+=(_,_)=>displayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel}; var resetStretch=Button("Reset");resetStretch.Padding=new(9,5);resetStretch.FontSize=11;resetStretch.VerticalAlignment=VerticalAlignment.Center;resetStretch.Click+=(_,_)=>displayStretch.Value=.18;Grid.SetColumn(resetStretch,1);stretchRow.Children.Add(resetStretch);Grid.SetRow(stretchRow,1);displayPanel.Children.Add(stretchRow);previewControls=new(){Child=displayPanel};
// Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle. // Keep the native slider's input behavior; give its thumb a visible silver face and room for the full circle.
Styles.Add(new Style(x=>x.OfType<Slider>().Template().OfType<Avalonia.Controls.Primitives.Thumb>()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate<Avalonia.Controls.Primitives.Thumb>((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}}); Styles.Add(new Style(x=>x.OfType<Slider>().Template().OfType<Avalonia.Controls.Primitives.Thumb>()){Setters={new Setter(Avalonia.Controls.Primitives.TemplatedControl.TemplateProperty,new FuncControlTemplate<Avalonia.Controls.Primitives.Thumb>((_,_)=>new Border{Width=20,Height=20,CornerRadius=new(10),Background=Palette.Accent,BorderBrush=Palette.Panel,BorderThickness=new(3),HorizontalAlignment=HorizontalAlignment.Center,VerticalAlignment=VerticalAlignment.Center}))}});
previewMode.SelectionChanged+=(_,_)=>{preview.Nebula=comparison.Nebula=previewMode.SelectedIndex==1;preview.RefreshDisplay();comparison.RefreshDisplay();}; previewMode.SelectionChanged+=(_,_)=>{preview.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));comparison.SetMode((PreviewMode)Math.Max(0,previewMode.SelectedIndex));};
ToolTip.SetTip(previewMode,"Frame: original grayscale preview. Denoised: reduce preview noise while keeping the original stretch parameters. Display options do not change analysis.");
displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}}; displayStretch.PropertyChanged+=(_,e)=>{if(e.Property==Slider.ValueProperty){stretchValue.Text=displayStretch.Value.ToString("0.00");preview.Stretch=comparison.Stretch=displayStretch.Value;preview.RefreshDisplay();comparison.RefreshDisplay();}};
Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13; Title="AstroFrame";Width=1450;Height=940;MinWidth=1120;MinHeight=740;Background=Palette.Background;FontFamily="Inter";FontSize=13;
ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36; ExtendClientAreaToDecorationsHint=true;ExtendClientAreaChromeHints=Avalonia.Platform.ExtendClientAreaChromeHints.PreferSystemChrome;ExtendClientAreaTitleBarHeightHint=36;
@ -84,9 +91,11 @@ public sealed partial class MainWindow:Window
var columns=new Grid{ColumnDefinitions=new("*,61,48,44"),Margin=new(14,8,14,8)};int ci=0;foreach(string label in new[]{"Time (UTC)","Decision","Stars","FWHM"}){var text=Palette.Label(label,10,Palette.Muted);if(ci>1)text.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(text,ci++);columns.Children.Add(text);}Grid.SetRow(columns,2);queue.Children.Add(columns); var columns=new Grid{ColumnDefinitions=new("*,61,48,44"),Margin=new(14,8,14,8)};int ci=0;foreach(string label in new[]{"Time (UTC)","Decision","Stars","FWHM"}){var text=Palette.Label(label,10,Palette.Muted);if(ci>1)text.HorizontalAlignment=HorizontalAlignment.Right;Grid.SetColumn(text,ci++);columns.Children.Add(text);}Grid.SetRow(columns,2);queue.Children.Add(columns);
frames.Background=Brushes.Transparent;frames.Padding=new(0);frames.ItemTemplate=new FuncDataTemplate<Frame>((f,_)=>f==null?new Border():FrameRow(f));frames.SelectionChanged+=(_,_)=>{if(!refreshing&&frames.SelectedItem is Frame f)Select(f);};Grid.SetRow(frames,3);queue.Children.Add(frames);var queuePanel=Panel(queue);queuePanel.Margin=new(0,0,16,0);body.Children.Add(queuePanel); frames.Background=Brushes.Transparent;frames.Padding=new(0);frames.ItemTemplate=new FuncDataTemplate<Frame>((f,_)=>f==null?new Border():FrameRow(f));frames.SelectionChanged+=(_,_)=>{if(!refreshing&&frames.SelectedItem is Frame f)Select(f);};Grid.SetRow(frames,3);queue.Children.Add(frames);var queuePanel=Panel(queue);queuePanel.Margin=new(0,0,16,0);body.Children.Add(queuePanel);
var center=new Grid{RowDefinitions=new("Auto,Auto,*,Auto,Auto,Auto"),Margin=new(0,0,16,0),MinWidth=310};Grid.SetColumn(center,1);body.Children.Add(center); var center=new Grid{RowDefinitions=new("Auto,Auto,*,Auto,Auto,Auto"),Margin=new(0,0,16,0),MinWidth=310};Grid.SetColumn(center,1);body.Children.Add(center);
var previewHeading=new Grid{ColumnDefinitions=new("*,Auto,Auto"),Margin=new(0,6,0,8)};previewHeading.Children.Add(Palette.Label("Exposure preview",14));position.HorizontalAlignment=HorizontalAlignment.Right;position.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(position,1);previewHeading.Children.Add(position); var previewHeading=new Grid{ColumnDefinitions=new("*,Auto"),RowDefinitions=new("Auto,Auto"),Margin=new(0,6,0,8)};previewHeading.Children.Add(Palette.Label("Exposure preview",14));position.HorizontalAlignment=HorizontalAlignment.Right;position.VerticalAlignment=VerticalAlignment.Center;Grid.SetColumn(position,1);previewHeading.Children.Add(position);
resetView.Padding=new(9,5);resetView.FontSize=11;resetView.Margin=new(10,0,0,0);resetView.Click+=(_,_)=>viewport.Reset();ToolTip.SetTip(resetView,"Reset image zoom and position");Grid.SetColumn(resetView,2);previewHeading.Children.Add(resetView);center.Children.Add(previewHeading); var previewActions=new WrapPanel{Margin=new(0,8,0,0)};
var viewRow=new Grid{ColumnDefinitions=new("Auto,*,Auto")};previewMode.MinWidth=125;previewMode.FontSize=11;viewRow.Children.Add(previewMode);var switches=new StackPanel{Orientation=Orientation.Horizontal,VerticalAlignment=VerticalAlignment.Center};spatial.Content="Overlay";compare.Content="Compare";spatial.Margin=new(0,0,12,0);switches.Children.Add(spatial);switches.Children.Add(compare);Grid.SetColumn(switches,2);viewRow.Children.Add(switches);Grid.SetRow(viewRow,1);center.Children.Add(viewRow); resetView.Padding=new(9,5);resetView.FontSize=11;resetView.Click+=(_,_)=>viewport.Reset();ToolTip.SetTip(resetView,"Reset image zoom and position");previewActions.Children.Add(resetView);
inspectElongation.Padding=new(9,5);inspectElongation.FontSize=11;inspectElongation.Margin=new(8,0,0,0);inspectElongation.IsEnabled=false;inspectElongation.Click+=(_,_)=>ShowElongation();ToolTip.SetTip(inspectElongation,"Enlarge source stars and highlight their shape, with a matched KEEP frame when available");previewActions.Children.Add(inspectElongation);Grid.SetRow(previewActions,1);Grid.SetColumnSpan(previewActions,2);previewHeading.Children.Add(previewActions);center.Children.Add(previewHeading);
var viewRow=new Grid{ColumnDefinitions=new("Auto,*,Auto")};previewMode.MinWidth=125;previewMode.FontSize=11;viewRow.Children.Add(previewMode);var switches=new StackPanel{Orientation=Orientation.Horizontal,VerticalAlignment=VerticalAlignment.Center};spatial.Content="Overlay";compare.Content="Compare";spatial.Margin=new(0,0,12,0);switches.Children.Add(spatial);switches.Children.Add(compare);switches.Children.Add(compareTarget);Grid.SetColumn(switches,2);viewRow.Children.Add(switches);Grid.SetRow(viewRow,1);center.Children.Add(viewRow);
previewWorkspace.Children.Add(previewPanel);Grid.SetColumn(comparisonBorder,1);previewWorkspace.Children.Add(comparisonBorder);comparisonBorder.IsVisible=false;Grid.SetRow(previewWorkspace,2);center.Children.Add(previewWorkspace); previewWorkspace.Children.Add(previewPanel);Grid.SetColumn(comparisonBorder,1);previewWorkspace.Children.Add(comparisonBorder);comparisonBorder.IsVisible=false;Grid.SetRow(previewWorkspace,2);center.Children.Add(previewWorkspace);
Grid.SetRow(previewControls,3);center.Children.Add(previewControls); Grid.SetRow(previewControls,3);center.Children.Add(previewControls);
var caption=new StackPanel{Spacing=4,Margin=new(0,0,0,12)};exposureName.TextTrimming=TextTrimming.CharacterEllipsis;caption.Children.Add(exposureName);caption.Children.Add(exposureStatus);Grid.SetRow(caption,4);center.Children.Add(caption); var caption=new StackPanel{Spacing=4,Margin=new(0,0,0,12)};exposureName.TextTrimming=TextTrimming.CharacterEllipsis;caption.Children.Add(exposureName);caption.Children.Add(exposureStatus);Grid.SetRow(caption,4);center.Children.Add(caption);
@ -95,11 +104,12 @@ public sealed partial class MainWindow:Window
var right=new Grid{RowDefinitions=new("2*,3*"),MinWidth=320};Grid.SetColumn(right,2);body.Children.Add(right); var right=new Grid{RowDefinitions=new("2*,3*"),MinWidth=320};Grid.SetColumn(right,2);body.Children.Add(right);
var graphs=new Grid{RowDefinitions=new("Auto,*"),Margin=new(12)};var graphHeader=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(0,0,0,8)};var graphTitle=Palette.Label("Quality",14);graphTitle.VerticalAlignment=VerticalAlignment.Center;graphHeader.Children.Add(graphTitle);metric.MaxWidth=205;metric.FontSize=11;Grid.SetColumn(metric,1);graphHeader.Children.Add(metric);graphs.Children.Add(graphHeader);Grid.SetRow(chart,1);graphs.Children.Add(chart);var graphPanel=Panel(graphs);graphPanel.Margin=new(0,0,0,14);right.Children.Add(graphPanel); var graphs=new Grid{RowDefinitions=new("Auto,*"),Margin=new(12)};var graphHeader=new Grid{ColumnDefinitions=new("*,Auto"),Margin=new(0,0,0,8)};var graphTitle=Palette.Label("Quality",14);graphTitle.VerticalAlignment=VerticalAlignment.Center;graphHeader.Children.Add(graphTitle);metric.MaxWidth=205;metric.FontSize=11;Grid.SetColumn(metric,1);graphHeader.Children.Add(metric);graphs.Children.Add(graphHeader);Grid.SetRow(chart,1);graphs.Children.Add(chart);var graphPanel=Panel(graphs);graphPanel.Margin=new(0,0,0,14);right.Children.Add(graphPanel);
inspector.Margin=new(14);details.Child=new ScrollViewer{Content=inspector,HorizontalScrollBarVisibility=Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled};details.Background=Palette.Panel;details.BorderBrush=Palette.Line;details.BorderThickness=new(.5);details.CornerRadius=new(2);Grid.SetRow(details,1);right.Children.Add(details);root.Children.Add(body); inspector.Margin=new(14);details.Child=new ScrollViewer{Content=inspector,HorizontalScrollBarVisibility=Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled};details.Background=Palette.Panel;details.BorderBrush=Palette.Line;details.BorderThickness=new(.5);details.CornerRadius=new(2);Grid.SetRow(details,1);right.Children.Add(details);root.Children.Add(body);
var footer=new Grid{RowDefinitions=new("Auto,Auto"),Margin=new(20,7,20,7)};footer.Children.Add(progress);var footerLine=new Grid{ColumnDefinitions=new("*,Auto")};footerLine.Children.Add(status);stop.IsVisible=false;Grid.SetColumn(stop,1);footerLine.Children.Add(stop);Grid.SetRow(footerLine,1);footer.Children.Add(footerLine);Grid.SetRow(footer,3);root.Children.Add(footer);Content=root; var footer=new Grid{RowDefinitions=new("Auto,Auto"),Margin=new(20,7,20,7)};footer.Children.Add(progress);var footerLine=new Grid{ColumnDefinitions=new("*,Auto,Auto")};status.TextTrimming=TextTrimming.CharacterEllipsis;status.VerticalAlignment=VerticalAlignment.Center;footerLine.Children.Add(status);memoryUsage.IsVisible=false;memoryUsage.Margin=new(14,0,14,0);memoryUsage.VerticalAlignment=VerticalAlignment.Center;ToolTip.SetTip(memoryUsage,"AstroFrame process RAM currently resident in physical memory");Grid.SetColumn(memoryUsage,1);footerLine.Children.Add(memoryUsage);stop.IsVisible=false;Grid.SetColumn(stop,2);footerLine.Children.Add(stop);Grid.SetRow(footerLine,1);footer.Children.Add(footerLine);Grid.SetRow(footer,3);root.Children.Add(footer);Content=root;
memoryTimer.Tick+=(_,_)=>UpdateMemoryUsage();
analyze.Click+=async(_,_)=>await Analyze();export.Click+=async(_,_)=>await ExportAccepted();stop.Click+=(_,_)=>cancellation?.Cancel(); analyze.Click+=async(_,_)=>await Analyze();export.Click+=async(_,_)=>await ExportAccepted();stop.Click+=(_,_)=>cancellation?.Cancel();
filter.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};sort.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};metric.SelectionChanged+=(_,_)=>{chart.Metric=QualityChart.Metrics[Math.Max(0,metric.SelectedIndex)];chart.InvalidateVisual();}; filter.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};sort.SelectionChanged+=(_,_)=>{if(!refreshing)RefreshFrames();};metric.SelectionChanged+=(_,_)=>{chart.Metric=QualityChart.Metrics[Math.Max(0,metric.SelectedIndex)];chart.InvalidateVisual();};
chart.FrameClicked+=f=>{if(!visible.Contains(f))filter.SelectedIndex=0;frames.SelectedItem=f;frames.ScrollIntoView(f);Select(f);}; chart.FrameClicked+=f=>{if(!visible.Contains(f))filter.SelectedIndex=0;frames.SelectedItem=f;frames.ScrollIntoView(f);Select(f);};
spatial.IsCheckedChanged+=(_,_)=>{preview.Spatial=spatial.IsChecked==true;preview.InvalidateVisual();};compare.IsCheckedChanged+=(_,_)=>UpdateComparison(); spatial.IsCheckedChanged+=(_,_)=>{preview.Spatial=comparison.Spatial=spatial.IsChecked==true;preview.InvalidateVisual();comparison.InvalidateVisual();};compare.IsCheckedChanged+=(_,_)=>UpdateComparison();compareTarget.SelectionChanged+=(_,_)=>UpdateComparison();
ToolTip.SetTip(spatial,"Pink shows the strongest excess sky brightness against the clean session reference, excluding weak background residuals. Grid colors show regional stellar flux. This is supporting evidence, not an exact cloud boundary."); ToolTip.SetTip(spatial,"Pink shows the strongest excess sky brightness against the clean session reference, excluding weak background residuals. Grid colors show regional stellar flux. This is supporting evidence, not an exact cloud boundary.");
KeyDown+=async(_,e)=> KeyDown+=async(_,e)=>
{ {
@ -109,7 +119,7 @@ public sealed partial class MainWindow:Window
if(e.Key==Key.Z&&e.KeyModifiers.HasFlag(KeyModifiers.Control)&&undo.Count>0){var item=undo.Pop();item.Frame.Override=item.Verdict;item.Frame.Note=item.Note;item.Frame.ReviewedAt=item.At;await Save();RefreshFrames(item.Frame);e.Handled=true;} if(e.Key==Key.Z&&e.KeyModifiers.HasFlag(KeyModifiers.Control)&&undo.Count>0){var item=undo.Pop();item.Frame.Override=item.Verdict;item.Frame.Note=item.Note;item.Frame.ReviewedAt=item.At;await Save();RefreshFrames(item.Frame);e.Handled=true;}
}; };
Closing+=(_,e)=>{if(busy){e.Cancel=true;cancellation?.Cancel();status.Text="Stopping safely; close again when finished";}}; Closing+=(_,e)=>{if(busy){e.Cancel=true;cancellation?.Cancel();status.Text="Stopping safely; close again when finished";}};
Closed+=(_,_)=>{preview.Dispose();comparison.Dispose();};ShowEmpty();InitializeUpdates(); Closed+=(_,_)=>{memoryTimer.Stop();starInspector?.Close();preview.Dispose();comparison.Dispose();};ShowEmpty();InitializeUpdates();
} }
static Button Button(string text,bool primary=false)=>new(){Content=text,Padding=new(12,7),CornerRadius=new(2),Background=primary?Palette.Accent:Palette.Raised,Foreground=primary?Palette.Background:Palette.Text}; static Button Button(string text,bool primary=false)=>new(){Content=text,Padding=new(12,7),CornerRadius=new(2),Background=primary?Palette.Accent:Palette.Raised,Foreground=primary?Palette.Background:Palette.Text};
static Border Panel(Control child)=>new(){Background=Palette.Panel,BorderBrush=Palette.Line,BorderThickness=new(.5),CornerRadius=new(2),ClipToBounds=true,Child=child}; static Border Panel(Control child)=>new(){Background=Palette.Panel,BorderBrush=Palette.Line,BorderThickness=new(.5),CornerRadius=new(2),ClipToBounds=true,Child=child};
@ -162,9 +172,9 @@ public sealed partial class MainWindow:Window
var f=rejected?project.Frames.FirstOrDefault(x=>x.Effective==Verdict.Reject):project.Frames.FirstOrDefault(x=>x.Target.Contains("1432")); var f=rejected?project.Frames.FirstOrDefault(x=>x.Effective==Verdict.Reject):project.Frames.FirstOrDefault(x=>x.Target.Contains("1432"));
if(f==null)return;sessions.SelectedItem=f.Session;filter.SelectedIndex=rejected?2:0;spatial.IsChecked=rejected;compare.IsChecked=rejected;frames.SelectedItem=f;Select(f); if(f==null)return;sessions.SelectedItem=f.Session;filter.SelectedIndex=rejected?2:0;spatial.IsChecked=rejected;compare.IsChecked=rejected;frames.SelectedItem=f;Select(f);
} }
public void CaptureExposure(string filename,bool nebula=false) public void CaptureExposure(string filename)
{ {
if(project==null)return;var f=project.Frames.First(x=>x.Name.Contains(filename,StringComparison.OrdinalIgnoreCase));sessions.SelectedItem=f.Session;filter.SelectedIndex=0;spatial.IsChecked=false;compare.IsChecked=false;previewMode.SelectedIndex=nebula?1:0;frames.SelectedItem=f;Select(f); if(project==null)return;var f=project.Frames.First(x=>x.Name.Contains(filename,StringComparison.OrdinalIgnoreCase));sessions.SelectedItem=f.Session;filter.SelectedIndex=0;spatial.IsChecked=false;compare.IsChecked=false;previewMode.SelectedIndex=0;frames.SelectedItem=f;Select(f);
} }
public Task WaitForPreviews()=>Task.WhenAll(preview.Loading,comparison.Loading); public Task WaitForPreviews()=>Task.WhenAll(preview.Loading,comparison.Loading);
public void CaptureMetric(string name) public void CaptureMetric(string name)
@ -172,6 +182,8 @@ public sealed partial class MainWindow:Window
int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name); int index=Array.FindIndex(QualityChart.Metrics,m=>m.Name==name);
if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index; if(index<0)throw new ArgumentException("Unknown quality metric",nameof(name));metric.SelectedIndex=index;
} }
public void CapturePreviewMode(int mode)
{if(mode<0||mode>1)throw new ArgumentOutOfRangeException(nameof(mode));previewMode.SelectedIndex=mode;}
public async Task SmokeTest(string report) public async Task SmokeTest(string report)
{ {
if(project==null)throw new InvalidOperationException("Project not loaded"); if(project==null)throw new InvalidOperationException("Project not loaded");
@ -192,7 +204,7 @@ public sealed partial class MainWindow:Window
filter.SelectedIndex=0;sort.SelectedIndex=2;Check(visible[0].StarCount==visible.Min(f=>f.StarCount),"metric sorting"); filter.SelectedIndex=0;sort.SelectedIndex=2;Check(visible[0].StarCount==visible.Min(f=>f.StarCount),"metric sorting");
metric.SelectedIndex=Array.FindIndex(QualityChart.Metrics,m=>m.Name=="Background");Check(chart.Metric.Name=="Background","graph metric switching"); metric.SelectedIndex=Array.FindIndex(QualityChart.Metrics,m=>m.Name=="Background");Check(chart.Metric.Name=="Background","graph metric switching");
await WaitForPreviews();Check(preview.HasImage,"latest preview loads after rapid exposure switching"); await WaitForPreviews();Check(preview.HasImage,"latest preview loads after rapid exposure switching");
previewMode.SelectedIndex=1;displayStretch.Value=.26;Check(preview.Nebula&&Math.Abs(preview.Stretch-.26)<.001,"nebula view and adjustable stretch render without changing classification"); previewMode.SelectedIndex=1;displayStretch.Value=.26;await WaitForPreviews();Check(preview.Mode==PreviewMode.Denoised&&Math.Abs(preview.Stretch-.26)<.001,"denoised view and adjustable stretch render without changing classification");
Width=1120;Height=740;await Task.Delay(100);Check(Bounds.Width>=1120,"minimum window size"); Width=1120;Height=740;await Task.Delay(100);Check(Bounds.Width>=1120,"minimum window size");
compare.IsChecked=false;await Task.Delay(100); compare.IsChecked=false;await Task.Delay(100);
Check(this.GetVisualDescendants().OfType<QualityChart>().Count()==1,"one selectable quality graph"); Check(this.GetVisualDescendants().OfType<QualityChart>().Count()==1,"one selectable quality graph");
@ -207,10 +219,11 @@ public sealed partial class MainWindow:Window
await NativeDesktopChecks.Verify(this,Check); await NativeDesktopChecks.Verify(this,Check);
File.WriteAllLines(report,results);projectDirectory=original; File.WriteAllLines(report,results);projectDirectory=original;
} }
void ShowNoSelection(){inspector.Children.Clear();position.Text="";exposureName.Text="No exposures match this filter";exposureStatus.Text="";details.IsVisible=false;preview.Load(projectDirectory,null);comparison.Load(projectDirectory,null);chart.Selected=null;} void ShowNoSelection(){selected=null;inspectElongation.IsEnabled=false;inspector.Children.Clear();position.Text="";exposureName.Text="No exposures match this filter";exposureStatus.Text="";details.IsVisible=false;preview.Load(projectDirectory,null);comparison.Load(projectDirectory,null);chart.Selected=null;}
void Select(Frame f) void Select(Frame f)
{ {
selected=f;chart.Selected=f;chart.InvalidateVisual();details.IsVisible=true;inspector.Children.Clear(); selected=f;chart.Selected=f;chart.InvalidateVisual();details.IsVisible=true;inspector.Children.Clear();
inspectElongation.IsEnabled=!busy&&f.Measured&&f.Error=="";
position.Text=$"{visible.IndexOf(f)+1:N0} / {visible.Count:N0}"; position.Text=$"{visible.IndexOf(f)+1:N0} / {visible.Count:N0}";
preview.Load(projectDirectory,f,project?.Frames);preview.Spatial=spatial.IsChecked==true;UpdateComparison(); preview.Load(projectDirectory,f,project?.Frames);preview.Spatial=spatial.IsChecked==true;UpdateComparison();
exposureName.Text=f.Name;ToolTip.SetTip(exposureName,f.Name);exposureStatus.Text=f.Status+" · "+f.Time+" UTC"+(f.Override.HasValue?" · Manual":"");exposureStatus.Foreground=Palette.Verdict(f.Effective); exposureName.Text=f.Name;ToolTip.SetTip(exposureName,f.Name);exposureStatus.Text=f.Status+" · "+f.Time+" UTC"+(f.Override.HasValue?" · Manual":"");exposureStatus.Foreground=Palette.Verdict(f.Effective);
@ -232,9 +245,18 @@ public sealed partial class MainWindow:Window
void UpdateComparison() void UpdateComparison()
{ {
bool show=compare.IsChecked==true;comparisonBorder.IsVisible=show;previewWorkspace.ColumnDefinitions[1].Width=show?new GridLength(1,GridUnitType.Star):new GridLength(0);previewPanel.Margin=show?new(0,0,6,0):new(0); bool show=compare.IsChecked==true;comparisonBorder.IsVisible=show;previewWorkspace.ColumnDefinitions[1].Width=show?new GridLength(1,GridUnitType.Star):new GridLength(0);previewPanel.Margin=show?new(0,0,6,0):new(0);
preview.Caption=show?"Selected":"";comparison.Caption=show?"Nearby":"";preview.InvalidateVisual(); bool best=compareTarget.SelectedIndex==1;compareTarget.IsVisible=show;
preview.Caption=show?"Selected":"";comparison.Caption=show?best?"Best":"Nearby":"";preview.InvalidateVisual();
comparison.Spatial=spatial.IsChecked==true;
if(selected==null||project==null||!show){comparison.Load(projectDirectory,null);return;} if(selected==null||project==null||!show){comparison.Load(projectDirectory,null);return;}
var nearby=project.Frames.Where(f=>f.Session==selected.Session&&f.Id!=selected.Id&&f.Timestamp.HasValue&&selected.Timestamp.HasValue&&f.Error=="").OrderBy(f=>Math.Abs((f.Timestamp!.Value-selected.Timestamp!.Value).TotalSeconds)).FirstOrDefault();comparison.Load(projectDirectory,nearby,project.Frames);ToolTip.SetTip(comparisonBorder,nearby==null?"No comparable nearby exposure":"Nearby · "+nearby.Time+" · "+nearby.Status); var other=best?BestFrame(project.Frames,selected):project.Frames.Where(f=>f.Session==selected.Session&&f.Id!=selected.Id&&f.Timestamp.HasValue&&selected.Timestamp.HasValue&&f.Error=="").OrderBy(f=>Math.Abs((f.Timestamp!.Value-selected.Timestamp!.Value).TotalSeconds)).FirstOrDefault();
comparison.Load(projectDirectory,other,project.Frames);ToolTip.SetTip(comparisonBorder,other==null?best?"No other kept, measured exposure in this session":"No comparable nearby exposure":(best?"Best":"Nearby")+" · "+other.Time+" · "+other.Status+(best?$" · score {other.Score:0} · FWHM {other.Fwhm:0.00}":""));
}
// Best kept exposure in the same session: highest quality score, then sharpest stars, then strongest stellar flux.
static Frame? BestFrame(IEnumerable<Frame> frames,Frame selected)
{
return frames.Where(f=>f.Session==selected.Session&&f.Id!=selected.Id&&f.Error==""&&f.Measured&&f.Effective==Verdict.Keep&&f.Fwhm>0)
.OrderByDescending(f=>f.Score).ThenBy(f=>f.Fwhm).ThenByDescending(f=>f.Transparency).ThenBy(f=>f.Timestamp).FirstOrDefault();
} }
void Move(int step){if(visible.Count==0)return;int index=selected==null?0:visible.IndexOf(selected);var f=visible[Math.Clamp(index+step,0,visible.Count-1)];frames.SelectedItem=f;frames.ScrollIntoView(f);} void Move(int step){if(visible.Count==0)return;int index=selected==null?0:visible.IndexOf(selected);var f=visible[Math.Clamp(index+step,0,visible.Count-1)];frames.SelectedItem=f;frames.ScrollIntoView(f);}
async Task Override(Verdict? verdict,bool advance=true) async Task Override(Verdict? verdict,bool advance=true)
@ -252,7 +274,21 @@ public sealed partial class MainWindow:Window
} }
async Task<string?> Folder(string title) async Task<string?> Folder(string title)
{var result=await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions{Title=title,AllowMultiple=false});return result.FirstOrDefault()?.TryGetLocalPath();} {var result=await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions{Title=title,AllowMultiple=false});return result.FirstOrDefault()?.TryGetLocalPath();}
void Busy(bool value){busy=value;analyze.IsEnabled=!value;export.IsEnabled=!value&&project?.Complete==true;frames.IsEnabled=sessions.IsEnabled=chart.IsEnabled=filter.IsEnabled=sort.IsEnabled=metric.IsEnabled=!value;inspector.IsEnabled=!value;stop.IsVisible=progress.IsVisible=value;} void Busy(bool value)
{
busy=value;analyze.IsEnabled=!value;export.IsEnabled=!value&&project?.Complete==true;frames.IsEnabled=sessions.IsEnabled=chart.IsEnabled=filter.IsEnabled=sort.IsEnabled=metric.IsEnabled=!value;inspector.IsEnabled=!value;stop.IsVisible=progress.IsVisible=memoryUsage.IsVisible=value;
inspectElongation.IsEnabled=!value&&selected?.Measured==true&&selected.Error=="";
if(value){starInspector?.Close();UpdateMemoryUsage();memoryTimer.Start();}else{memoryTimer.Stop();memoryUsage.Text="";}
}
void UpdateMemoryUsage()
{
if(!busy)return;using var process=System.Diagnostics.Process.GetCurrentProcess();memoryUsage.Text=$"Memory: {process.WorkingSet64/1048576.0:N0} MB";
}
void ShowElongation()
{
if(busy||saving||updates.Applying||project==null||selected?.Measured!=true||selected.Error!="")return;
starInspector?.Close();starInspector=new StarInspector(project,projectDirectory,selected);var opened=starInspector;opened.Closed+=(_,_)=>{if(starInspector==opened)starInspector=null;};opened.Show(this);
}
async Task Analyze() async Task Analyze()
{ {
if(busy||saving||updates.Applying)return; if(busy||saving||updates.Applying)return;

View file

@ -78,10 +78,11 @@ public sealed class App:Application
if(Program.Arguments[0]=="--smoke"){await window.SmokeTest(Program.Arguments[2]);desktop.Shutdown(0);return;} if(Program.Arguments[0]=="--smoke"){await window.SmokeTest(Program.Arguments[2]);desktop.Shutdown(0);return;}
if(Program.Arguments.Length>3) if(Program.Arguments.Length>3)
{ {
if(Program.Arguments[3].EndsWith(".fit",StringComparison.OrdinalIgnoreCase))window.CaptureExposure(Program.Arguments[3],Program.Arguments.Contains("nebula")); if(Program.Arguments[3].EndsWith(".fit",StringComparison.OrdinalIgnoreCase))window.CaptureExposure(Program.Arguments[3]);
else if(Program.Arguments[3]!="all")window.CaptureSelection(Program.Arguments[3]=="reject"); else if(Program.Arguments[3]!="all")window.CaptureSelection(Program.Arguments[3]=="reject");
} }
string? metricOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--metric="));if(metricOption!=null)window.CaptureMetric(metricOption[9..]); string? metricOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--metric="));if(metricOption!=null)window.CaptureMetric(metricOption[9..]);
string? previewOption=Program.Arguments.FirstOrDefault(a=>a.StartsWith("--preview="));if(previewOption!=null)window.CapturePreviewMode(int.Parse(previewOption[10..],System.Globalization.CultureInfo.InvariantCulture));
if(Program.Arguments.Length>4&&double.TryParse(Program.Arguments[4],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out double width)){window.Width=width;window.Height=740;} if(Program.Arguments.Length>4&&double.TryParse(Program.Arguments[4],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out double width)){window.Width=width;window.Height=740;}
await window.WaitForPreviews();await Task.Delay(400); await window.WaitForPreviews();await Task.Delay(400);
if(window.Content is Control content) if(window.Content is Control content)

View file

@ -13,39 +13,49 @@ public sealed class StarInspector:Window
{ {
readonly List<WriteableBitmap> bitmaps=[]; readonly List<WriteableBitmap> bitmaps=[];
readonly CancellationTokenSource cancellation=new(); readonly CancellationTokenSource cancellation=new();
public Task Loading {get;private set;}=Task.CompletedTask;
public bool HasDetail {get;private set;}
public List<StarCropView> Crops {get;}=[];
public StarInspector(Project project,string directory,Frame selected,string? capture=null) public StarInspector(Project project,string directory,Frame selected,string? capture=null)
{ {
Title="AstroFrame · Matched star detail";Width=900;Height=790;MinWidth=660;MinHeight=520;Background=Palette.Background;FontFamily="Inter";WindowStartupLocation=WindowStartupLocation.CenterOwner; var token=cancellation.Token;
Title="AstroFrame · Stellar elongation";Width=900;Height=790;MinWidth=660;MinHeight=520;Background=TransparencyBackgroundFallback=Palette.Background;FontFamily="Inter";WindowStartupLocation=WindowStartupLocation.CenterOwner;NativeWindowBackground.Apply(this);
var panel=new StackPanel{Margin=new(24),Spacing=12};Content=new Border{Background=Palette.Background,Child=new ScrollViewer{Content=panel}};var progress=Palette.Label("Reading matched source stars…",16);panel.Children.Add(progress); var panel=new StackPanel{Margin=new(24),Spacing=12};Content=new Border{Background=Palette.Background,Child=new ScrollViewer{Content=panel}};var progress=Palette.Label("Reading matched source stars…",16);panel.Children.Add(progress);
Opened+=async(_,_)=> Opened+=(_,_)=>Loading=LoadDetail();
async Task LoadDetail()
{ {
try try
{ {
var peer=StellarDetail.Comparison(project,selected)??throw new InvalidDataException("No comparable KEEP exposure in this session"); var peer=StellarDetail.Comparison(project,selected);
var detail=await Task.Run(async()=>{using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(selected.Width,selected.Height,selected.Bayer!=""?2:1)*2,cancellation.Token);return StellarDetail.Read(directory,selected,peer,cancellation.Token);},cancellation.Token); var detail=await Task.Run(async()=>{using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(selected.Width,selected.Height,selected.Bayer!=""?2:1)*(peer==null?1:2),token);return StellarDetail.Read(directory,selected,peer,token);},token);
cancellation.Token.ThrowIfCancellationRequested();panel.Children.Clear();panel.Children.Add(Palette.Label("Matched stars · original source samples",21)); token.ThrowIfCancellationRequested();panel.Children.Clear();panel.Children.Add(Palette.Label("Stellar elongation · enlarged source stars",21));
panel.Children.Add(new TextBlock{Text="Identical stars, aligned between exposures. Each crop has its own brightness normalization. Pixels are enlarged without smoothing; Bayer samples are combined 2×2. Judge shape here, and transparency from the flux measurements.",FontSize=12,Foreground=Palette.Muted,TextWrapping=TextWrapping.Wrap}); panel.Children.Add(new TextBlock{Text="Blue outlines and long axes highlight the star shape; gold lines mark the short axes. Ellipticity is 1 − b/a: 0 is round, higher values are more elongated. Guides and crop values use source core moments. Frame values below summarize the strong stars across the image.",FontSize=12,Foreground=Palette.Muted,TextWrapping=TextWrapping.Wrap});
panel.Children.Add(new TextBlock{Text="Pixels are enlarged without smoothing, with separate brightness normalization per crop. Bayer samples are combined 2×2. "+(peer==null?"No aligned KEEP exposure is available; showing the selected stars.":"Both columns show the same stars in aligned exposures. Judge transparency from the flux measurements."),FontSize=12,Foreground=Palette.Muted,TextWrapping=TextWrapping.Wrap});
var guides=new CheckBox{Content="Show shape guides",IsChecked=true,FontSize=12};guides.IsCheckedChanged+=(_,_)=>{foreach(var crop in Crops){crop.ShowGuides=guides.IsChecked==true;crop.InvalidateVisual();}};panel.Children.Add(guides);
var header=new Grid{ColumnDefinitions=new("45,*,*")}; var header=new Grid{ColumnDefinitions=new("45,*,*")};
TextBlock Label(string text)=>new(){Text=text,Foreground=Palette.Text,TextWrapping=TextWrapping.Wrap,FontSize=12,Margin=new(8,0)}; TextBlock Label(string text)=>new(){Text=text,Foreground=Palette.Text,TextWrapping=TextWrapping.Wrap,FontSize=12,Margin=new(8,0)};
var left=Label(selected.Status+" · "+selected.Time+" UTC\n"+selected.Name+$"\nFWHM {selected.Fwhm:0.00} px · ellipticity {selected.Ellipticity:0.00}");Grid.SetColumn(left,1);header.Children.Add(left); var left=Label(selected.Status+" · "+selected.Time+" UTC\n"+selected.Name+$"\nFWHM {selected.Fwhm:0.00} px · ellipticity {selected.Ellipticity:0.00}");Grid.SetColumn(left,1);header.Children.Add(left);
var right=Label(peer.Status+" · "+peer.Time+" UTC\n"+peer.Name+$"\nFWHM {peer.Fwhm:0.00} px · ellipticity {peer.Ellipticity:0.00}");Grid.SetColumn(right,2);header.Children.Add(right);panel.Children.Add(header); if(peer!=null){var right=Label(peer.Status+" · "+peer.Time+" UTC\n"+peer.Name+$"\nFWHM {peer.Fwhm:0.00} px · ellipticity {peer.Ellipticity:0.00}");Grid.SetColumn(right,2);header.Children.Add(right);}panel.Children.Add(header);
foreach(var star in detail.Stars) foreach(var star in detail.Stars)
{ {
var row=new Grid{ColumnDefinitions=new("45,*,*"),Margin=new(0,6)};row.Children.Add(Palette.Label(star.Number.ToString("00"),12,Palette.Muted)); var row=new Grid{ColumnDefinitions=new("45,*,*"),Margin=new(0,6)};row.Children.Add(Palette.Label(star.Number.ToString("00"),12,Palette.Muted));
foreach(var entry in new[]{(Pixels:star.Selected,Column:1),(Pixels:star.Comparison,Column:2)}) foreach(var entry in new[]{(Sample:star.Selected,Column:1),(Sample:star.Comparison,Column:2)})
{ {
var bitmap=Gray(entry.Pixels,detail.Size);bitmaps.Add(bitmap);var image=new Image{Source=bitmap,Width=130,Height=130,HorizontalAlignment=HorizontalAlignment.Left,Margin=new(8,0)};RenderOptions.SetBitmapInterpolationMode(image,BitmapInterpolationMode.None);Grid.SetColumn(image,entry.Column);row.Children.Add(image); if(entry.Sample==null)continue;
var bitmap=Gray(entry.Sample.Pixels,detail.Size);bitmaps.Add(bitmap);var crop=new StarCropView(bitmap,entry.Sample.Shape){Width=130,Height=130,HorizontalAlignment=HorizontalAlignment.Left};Crops.Add(crop);
var cell=new StackPanel{Spacing=5,Margin=new(8,0)};cell.Children.Add(crop);cell.Children.Add(Palette.Label(entry.Sample.Shape is {} shape?$"Ellipticity {shape.Ellipticity:0.00}":"Shape fit unavailable",11,Palette.Muted));Grid.SetColumn(cell,entry.Column);row.Children.Add(cell);
} }
panel.Children.Add(row); panel.Children.Add(row);
} }
HasDetail=true;
if(capture!=null) if(capture!=null)
{ {
await Task.Delay(200);if(Content is Control content){using var bitmap=new RenderTargetBitmap(new PixelSize((int)content.Bounds.Width,(int)content.Bounds.Height),new Vector(96,96));bitmap.Render(content);bitmap.Save(capture);}((IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!).Shutdown(0); await Task.Delay(200);if(Content is Control content){using var bitmap=new RenderTargetBitmap(new PixelSize((int)content.Bounds.Width,(int)content.Bounds.Height),new Vector(96,96));bitmap.Render(content);bitmap.Save(capture);}((IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!).Shutdown(0);
} }
} }
catch(OperationCanceledException){} catch(OperationCanceledException){}
catch(Exception e){progress.Text="Star detail unavailable: "+e.Message;if(capture!=null){File.WriteAllText(capture+".error",e.ToString());((IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!).Shutdown(1);}} catch(Exception e){panel.Children.Clear();panel.Children.Add(new TextBlock{Text="Star detail unavailable: "+e.Message,Foreground=Palette.Muted,TextWrapping=TextWrapping.Wrap});if(capture!=null){File.WriteAllText(capture+".error",e.ToString());((IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!).Shutdown(1);}}
}; }
Closing+=(_,_)=>cancellation.Cancel();Closed+=(_,_)=>{foreach(var bitmap in bitmaps)bitmap.Dispose();cancellation.Dispose();}; Closing+=(_,_)=>cancellation.Cancel();Closed+=(_,_)=>{foreach(var bitmap in bitmaps)bitmap.Dispose();cancellation.Dispose();};
} }
static WriteableBitmap Gray(byte[] pixels,int size) static WriteableBitmap Gray(byte[] pixels,int size)
@ -54,3 +64,24 @@ public sealed class StarInspector:Window
for(int y=0;y<size;y++){for(int x=0;x<size;x++){byte v=pixels[y*size+x];row[4*x]=row[4*x+1]=row[4*x+2]=v;row[4*x+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}return bitmap; for(int y=0;y<size;y++){for(int x=0;x<size;x++){byte v=pixels[y*size+x];row[4*x]=row[4*x+1]=row[4*x+2]=v;row[4*x+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}return bitmap;
} }
} }
public sealed class StarCropView:Control
{
readonly WriteableBitmap bitmap;
public StarShape? Shape {get;}
public bool ShowGuides {get;set;}=true;
public StarCropView(WriteableBitmap bitmap,StarShape? shape)
{this.bitmap=bitmap;Shape=shape;RenderOptions.SetBitmapInterpolationMode(this,BitmapInterpolationMode.None);ClipToBounds=true;}
public override void Render(DrawingContext context)
{
base.Render(context);context.DrawImage(bitmap,new Rect(bitmap.Size),new Rect(Bounds.Size));
if(!ShowGuides||Shape is not {} shape)return;
double scale=Bounds.Width/bitmap.Size.Width,c=Math.Cos(shape.Angle),s=Math.Sin(shape.Angle);
Point Map(double x,double y)=>new((shape.X+c*x-s*y)*scale,(shape.Y+s*x+c*y)*scale);
double a=shape.Major/2,b=shape.Minor/2;
var ellipse=new StreamGeometry();using(var path=ellipse.Open())
{path.BeginFigure(Map(a,0),false);for(int i=1;i<=64;i++){double t=i*Math.PI/32;path.LineTo(Map(a*Math.Cos(t),b*Math.Sin(t)));}path.EndFigure(true);}
context.DrawGeometry(null,new Pen(Palette.Progress,1.2),ellipse);
context.DrawLine(new Pen(Palette.Progress,1.2),Map(-a,0),Map(a,0));context.DrawLine(new Pen(Palette.Review,1),Map(0,-b),Map(0,b));
}
}

View file

@ -13,7 +13,7 @@ public static class Palette
public static readonly IBrush Background=Brush("#151617"),Panel=Brush("#1E2021"),Raised=Brush("#292B2D"),Muted=Brush("#A2A5A7"),Text=Brush("#E6E7E7"),Accent=Brush("#D3D5D4"),Keep=Brush("#A8BFB0"),Review=Brush("#D5BF91"),Reject=Brush("#DBA2A6"),Line=Brush("#3B3E40"); public static readonly IBrush Background=Brush("#151617"),Panel=Brush("#1E2021"),Raised=Brush("#292B2D"),Muted=Brush("#A2A5A7"),Text=Brush("#E6E7E7"),Accent=Brush("#D3D5D4"),Keep=Brush("#A8BFB0"),Review=Brush("#D5BF91"),Reject=Brush("#DBA2A6"),Line=Brush("#3B3E40");
public static IBrush Brush(string hex)=>new SolidColorBrush(Color.Parse(hex)); public static IBrush Brush(string hex)=>new SolidColorBrush(Color.Parse(hex));
public static IBrush Verdict(Verdict v)=>v switch{AstroFrame.Engine.Verdict.Keep=>Keep,AstroFrame.Engine.Verdict.Reject=>Reject,_=>Review}; public static IBrush Verdict(Verdict v)=>v switch{AstroFrame.Engine.Verdict.Keep=>Keep,AstroFrame.Engine.Verdict.Reject=>Reject,_=>Review};
public static readonly IBrush Update=Brush("#007BA7"),GraphKeep=Brush("#68DE96"),GraphReview=Brush("#F2C366"),GraphReject=Brush("#FF8794"); public static readonly IBrush Update=Brush("#007BA7"),Progress=Brush("#7CABC3"),GraphKeep=Keep,GraphReview=Review,GraphReject=Reject;
public static IBrush GraphVerdict(Verdict v)=>v switch{AstroFrame.Engine.Verdict.Keep=>GraphKeep,AstroFrame.Engine.Verdict.Reject=>GraphReject,_=>GraphReview}; public static IBrush GraphVerdict(Verdict v)=>v switch{AstroFrame.Engine.Verdict.Keep=>GraphKeep,AstroFrame.Engine.Verdict.Reject=>GraphReject,_=>GraphReview};
public static TextBlock Label(string text,double size=13,IBrush? color=null)=>new(){Text=text,FontSize=size,Foreground=color??Text}; public static TextBlock Label(string text,double size=13,IBrush? color=null)=>new(){Text=text,FontSize=size,Foreground=color??Text};
} }
@ -74,7 +74,8 @@ public sealed class ExposureView:Control,IDisposable
{ {
static readonly SemaphoreSlim LoadGate=new(1); static readonly SemaphoreSlim LoadGate=new(1);
WriteableBitmap? bitmap; WriteableBitmap? bitmap;
PreviewDisplay? frameDisplay,nebulaDisplay; PreviewDisplay? frameDisplay,denoisedDisplay;
bool denoiseAttempted;
byte[] overlayMask=[]; byte[] overlayMask=[];
CancellationTokenSource? request; CancellationTokenSource? request;
string message="Select an exposure"; string message="Select an exposure";
@ -82,12 +83,14 @@ public sealed class ExposureView:Control,IDisposable
public bool HasImage=>bitmap!=null; public bool HasImage=>bitmap!=null;
public Frame? Frame {get;private set;} public Frame? Frame {get;private set;}
public bool Spatial {get;set;} public bool Spatial {get;set;}
public bool Nebula {get;set;} public PreviewMode Mode {get;private set;}
public bool HasDenoised=>denoisedDisplay!=null;
public double Stretch {get;set;}=.18; public double Stretch {get;set;}=.18;
public string Caption {get;set;}=""; public string Caption {get;set;}="";
public PreviewViewport Viewport {get;} public PreviewViewport Viewport {get;}
Point? dragStart;IPointer? dragPointer; Point? dragStart;IPointer? dragPointer;
Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0))); string ModeNote=>Mode==PreviewMode.Denoised?(denoisedDisplay!=null?"Denoised preview":denoiseAttempted?"Denoising unavailable":"Denoising…"):"";
Rect ImageArea=>new(0,(Caption!=""?26:0)+(Spatial?22:0)+(ModeNote!=""?20:0),Math.Max(1,Bounds.Width),Math.Max(1,Bounds.Height-(Caption!=""?26:0)-(Spatial?22:0)-(ModeNote!=""?20:0)));
public ExposureView():this(new PreviewViewport()){} public ExposureView():this(new PreviewViewport()){}
public ExposureView(PreviewViewport viewport) public ExposureView(PreviewViewport viewport)
{ {
@ -112,7 +115,7 @@ public sealed class ExposureView:Control,IDisposable
try try
{ {
await LoadGate.WaitAsync(token); await LoadGate.WaitAsync(token);
(PreviewDisplay Frame,PreviewDisplay Nebula,byte[] Overlay) prepared; (PreviewDisplay Frame,byte[] Overlay) prepared;
try try
{ {
prepared=await Task.Run(async()=> prepared=await Task.Run(async()=>
@ -125,18 +128,47 @@ public sealed class ExposureView:Control,IDisposable
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token); using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token);
var image=Fits.Read(f.Path,token);token.ThrowIfCancellationRequested();Fits.Preview(image,path,f);plane=PreviewRenderer.Read(path,f); var image=Fits.Read(f.Path,token);token.ThrowIfCancellationRequested();Fits.Preview(image,path,f);plane=PreviewRenderer.Read(path,f);
} }
token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane),PreviewRenderer.Prepare(plane,true),SkyOverlay.LoadMask(directory,f,frames,token)); token.ThrowIfCancellationRequested();return(PreviewRenderer.Prepare(plane,token),SkyOverlay.LoadMask(directory,f,frames,token));
},token); },token);
} }
finally{LoadGate.Release();} finally{LoadGate.Release();}
token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;nebulaDisplay=prepared.Nebula;overlayMask=prepared.Overlay;RefreshDisplay(); token.ThrowIfCancellationRequested();frameDisplay=prepared.Frame;overlayMask=prepared.Overlay;RefreshDisplay();
if(Mode==PreviewMode.Denoised)await LoadDenoised(token);
} }
catch(OperationCanceledException){} catch(OperationCanceledException){}
catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}} catch(Exception e){if(!token.IsCancellationRequested){message="Preview unavailable: "+e.Message;InvalidateVisual();}}
} }
public void SetMode(PreviewMode mode)
{
Mode=mode;RefreshDisplay();InvalidateVisual();
if(mode==PreviewMode.Denoised&&!denoiseAttempted&&request is {} active)
{var previous=Loading;Loading=LoadDenoisedAfter(previous,active.Token);}
}
async Task LoadDenoisedAfter(Task previous,CancellationToken token)
{await previous;if(!token.IsCancellationRequested)await LoadDenoised(token);}
async Task LoadDenoised(CancellationToken token)
{
try
{
await LoadGate.WaitAsync(token);
try
{
if(denoiseAttempted||frameDisplay is not {} original)return;
var prepared=await Task.Run(async()=>
{
using var memory=await ResourcePolicy.Acquire(64L*1024*1024+original.Plane.Pixels.LongLength*40,token);
return DenoisedPreview.Prepare(original,token);
},token);
token.ThrowIfCancellationRequested();denoisedDisplay=prepared;denoiseAttempted=true;RefreshDisplay();InvalidateVisual();
}
finally{LoadGate.Release();}
}
catch(OperationCanceledException){}
catch(Exception){if(!token.IsCancellationRequested){denoiseAttempted=true;RefreshDisplay();InvalidateVisual();}}
}
public void RefreshDisplay() public void RefreshDisplay()
{ {
var display=Nebula?nebulaDisplay:frameDisplay;if(display==null)return; var display=Mode==PreviewMode.Denoised&&denoisedDisplay!=null?denoisedDisplay:frameDisplay;if(display==null)return;
byte[] pixels=PreviewRenderer.Render(display,Stretch);int w=display.Plane.Width,h=display.Plane.Height;bitmap?.Dispose(); byte[] pixels=PreviewRenderer.Render(display,Stretch);int w=display.Plane.Width,h=display.Plane.Height;bitmap?.Dispose();
bitmap=new WriteableBitmap(new PixelSize(w,h),new Vector(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque); bitmap=new WriteableBitmap(new PixelSize(w,h),new Vector(96,96),PixelFormat.Bgra8888,AlphaFormat.Opaque);
using var locked=bitmap.Lock();byte[] row=new byte[w*4];for(int y=0;y<h;y++){for(int x=0;x<w;x++){byte v=pixels[y*w+x];row[x*4]=v;row[x*4+1]=v;row[x*4+2]=v;row[x*4+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}InvalidateVisual(); using var locked=bitmap.Lock();byte[] row=new byte[w*4];for(int y=0;y<h;y++){for(int x=0;x<w;x++){byte v=pixels[y*w+x];row[x*4]=v;row[x*4+1]=v;row[x*4+2]=v;row[x*4+3]=255;}Marshal.Copy(row,0,locked.Address+y*locked.RowBytes,row.Length);}InvalidateVisual();
@ -148,6 +180,7 @@ public sealed class ExposureView:Control,IDisposable
double captionHeight=Caption!=""?26:0,header=captionHeight+(Spatial?22:0); double captionHeight=Caption!=""?26:0,header=captionHeight+(Spatial?22:0);
if(captionHeight>0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7)); if(captionHeight>0)c.DrawText(new FormattedText(Caption+" · "+Frame?.Time,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted),new(8,7));
if(Spatial)c.DrawText(new FormattedText(overlayMask.Length==SkyModel.Count?"Pink: excess sky · Grid: stellar flux":"Sky overlay unavailable · cached reference required",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,captionHeight+5)); if(Spatial)c.DrawText(new FormattedText(overlayMask.Length==SkyModel.Count?"Pink: excess sky · Grid: stellar flux":"Sky overlay unavailable · cached reference required",System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,captionHeight+5));
if(ModeNote!="")c.DrawText(new FormattedText(ModeNote,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),10,Palette.Muted){MaxTextWidth=Math.Max(1,Bounds.Width-16)},new(8,header+4));
using var imageClip=c.PushClip(ImageArea); using var imageClip=c.PushClip(ImageArea);
var rect=Viewport.ImageRect(ImageArea,bitmap.Size);double w=rect.Width,h=rect.Height;c.DrawImage(bitmap,new Rect(bitmap.Size),rect); var rect=Viewport.ImageRect(ImageArea,bitmap.Size);double w=rect.Width,h=rect.Height;c.DrawImage(bitmap,new Rect(bitmap.Size),rect);
if(Spatial&&Frame!=null&&Frame.Alignment.Length==4) if(Spatial&&Frame!=null&&Frame.Alignment.Length==4)
@ -169,5 +202,5 @@ public sealed class ExposureView:Control,IDisposable
} }
} }
} }
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;overlayMask=[];} public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=denoisedDisplay=null;denoiseAttempted=false;overlayMask=[];}
} }

View file

@ -40,6 +40,7 @@ public static class Classification
double countZ=Metric("Star count",x=>x.StarCount,true,.10),fluxZ=Metric("Stellar flux",x=>x.Transparency,true,.06),widthZ=Metric("FWHM",x=>x.Fwhm,false,.08),shapeZ=Metric("Ellipticity",x=>x.Ellipticity,false,.15),bgZ=Metric("Background",x=>x.Background,false,.06),noiseZ=Metric("Noise",x=>x.Noise,false,.08); double countZ=Metric("Star count",x=>x.StarCount,true,.10),fluxZ=Metric("Stellar flux",x=>x.Transparency,true,.06),widthZ=Metric("FWHM",x=>x.Fwhm,false,.08),shapeZ=Metric("Ellipticity",x=>x.Ellipticity,false,.15),bgZ=Metric("Background",x=>x.Background,false,.06),noiseZ=Metric("Noise",x=>x.Noise,false,.08);
Metric("Background variation",x=>x.BackgroundVariation,false,.20); Metric("Background variation",x=>x.BackgroundVariation,false,.20);
double Ratio(string key,double value)=>value/Math.Max(f.Baselines.GetValueOrDefault(key),.00001); double Ratio(string key,double value)=>value/Math.Max(f.Baselines.GetValueOrDefault(key),.00001);
double Measured(string key)=>f.AdditionalMeasurements.GetValueOrDefault(key);
double countRatio=Ratio("Star count",f.StarCount),fluxRatio=Ratio("Stellar flux",f.Transparency),widthRatio=Ratio("FWHM",f.Fwhm); double countRatio=Ratio("Star count",f.StarCount),fluxRatio=Ratio("Stellar flux",f.Transparency),widthRatio=Ratio("FWHM",f.Fwhm);
double connected=f.AdditionalMeasurements.GetValueOrDefault("Cloud connected coverage"); double connected=f.AdditionalMeasurements.GetValueOrDefault("Cloud connected coverage");
// A single sky detector must be overwhelming to discard integration on its own. // A single sky detector must be overwhelming to discard integration on its own.
@ -88,7 +89,15 @@ public static class Classification
} }
if(widthBad)f.Evidence.Add(new("FWHM",f.Fwhm,f.Baselines["FWHM"],widthZ,$"Stellar width {widthRatio:0.00} × clear-frame baseline")); if(widthBad)f.Evidence.Add(new("FWHM",f.Fwhm,f.Baselines["FWHM"],widthZ,$"Stellar width {widthRatio:0.00} × clear-frame baseline"));
if(shapeBad)f.Evidence.Add(new("Ellipticity",f.Ellipticity,f.Baselines["Ellipticity"],shapeZ,$"Substantial stellar elongation ({f.Ellipticity:0.00} vs {f.Baselines["Ellipticity"]:0.00})")); if(shapeBad)f.Evidence.Add(new("Ellipticity",f.Ellipticity,f.Baselines["Ellipticity"],shapeZ,$"Substantial stellar elongation ({f.Ellipticity:0.00} vs {f.Baselines["Ellipticity"]:0.00})"));
bool optics=widthBad&&shapeBad&&widthRatio>1.65; // Stacking workflows such as Siril's Seestar script discard roundness outliers rather than
// averaging trailed stars into the result. Reject elongation that the same matched reference
// stars confirm well beyond their measurement uncertainty; unconfirmed flags stay REVIEW.
bool confirmedElongation=shapeBad&&Measured("Matched shape samples")>=50&&Measured("Matched shape reference frames")>=12&&
Measured("Matched shape uncertainty")>0&&Measured("Matched shape uncertainty")<=.025&&
Measured("Matched shape change")-3*Measured("Matched shape uncertainty")>=.10;
if(confirmedElongation)f.Evidence.Add(new("Matched stellar shape",Measured("Matched shape change"),0,Measured("Matched shape change")/Measured("Matched shape uncertainty"),
$"The same {Measured("Matched shape samples"):0} reference stars are {Measured("Matched shape change"):0.00} more elongated than in nearby clear frames (±{Measured("Matched shape uncertainty"):0.000}); a roundness outlier that stacking filters discard"));
bool optics=widthBad&&shapeBad&&widthRatio>1.65||confirmedElongation;
bool catastrophic=f.StarCount<3&&f.Baselines["Star count"]>50; bool catastrophic=f.StarCount<3&&f.Baselines["Star count"]>50;
bool cloud=strongStructure||moderateStructure&&(fluxLoss||regionLoss||starLoss)||strongFlux||localCloudLoss; bool cloud=strongStructure||moderateStructure&&(fluxLoss||regionLoss||starLoss)||strongFlux||localCloudLoss;
bool lowMatches=f.MatchFraction<.35; bool lowMatches=f.MatchFraction<.35;
@ -97,6 +106,22 @@ public static class Classification
bool skyNoise=bgZ>5&&noiseZ>4&&Ratio("Background",f.Background)>1.4; bool skyNoise=bgZ>5&&noiseZ>4&&Ratio("Background",f.Background)>1.4;
if(skyNoise)f.Evidence.Add(new("Sky noise",f.Noise,f.Baselines["Noise"],noiseZ,"Background and sky noise are substantially above the clear-frame baseline")); if(skyNoise)f.Evidence.Add(new("Sky noise",f.Noise,f.Baselines["Noise"],noiseZ,"Background and sky noise are substantially above the clear-frame baseline"));
bool suspicious=moderateStructure||fluxLoss||regionLoss||widthBad||shapeBad||skyNoise||starLoss||lowMatches; bool suspicious=moderateStructure||fluxLoss||regionLoss||widthBad||shapeBad||skyNoise||starLoss||lowMatches;
// Thin cloud adds little residual glow, but it is coherent after smooth curvature is
// removed and dims the stars beneath it relative to clear parts of the same exposure.
// Requiring both keeps sky-only changes, such as gradients, out of this route. It only
// resolves frames other measurements already flag; it never rejects an otherwise clean KEEP.
bool texture=suspicious&&spatial&&Measured("Cloud texture significance")>=10&&Measured("Cloud texture connected coverage")>=.05&&
Measured("Cloud texture differential samples")>=20&&Measured("Cloud texture differential flux ratio")>0;
// Moderate dimming suffices when the plane-detrended structure detector also flags the frame,
// the texture is strong, and the excess-sky apertures independently lose flux against nearby frames.
bool thinCloud=texture&&(Measured("Cloud texture differential flux ratio")<=.98&&Measured("Cloud texture differential flux deviation")>=2.5||
moderateStructure&&Measured("Cloud texture significance")>=20&&
Measured("Cloud texture differential flux ratio")<=.985&&Measured("Cloud texture differential flux deviation")>=1.5&&
Measured("Cloud aperture samples")>=20&&Measured("Cloud aperture regions")>=2&&
Measured("Cloud aperture flux ratio")>0&&Measured("Cloud aperture flux ratio")<=.93&&Measured("Cloud aperture flux deviation")>=2.5);
if(thinCloud)f.Evidence.Add(new("Cloud texture",Measured("Cloud texture differential flux ratio"),1,Measured("Cloud texture differential flux deviation"),
$"Thin cloud texture covers {Measured("Cloud texture coverage"):P0} of the aligned overlap (largest connected area {Measured("Cloud texture connected coverage"):P0}, {Measured("Cloud texture significance"):0.0} × clear-frame scatter); stars beneath it are {1-Measured("Cloud texture differential flux ratio"):P1} fainter relative to clear parts of the same exposure ({Measured("Cloud texture differential flux deviation"):0.0} × nearby clear-frame scatter, {Measured("Cloud texture differential samples"):0} apertures)"));
cloud|=thinCloud;
f.Automatic=reliable&&(catastrophic||!weak&&(cloud||optics))?Verdict.Reject:!reliable||weak||suspicious||f.Warning!=""?Verdict.Review:Verdict.Keep; f.Automatic=reliable&&(catastrophic||!weak&&(cloud||optics))?Verdict.Reject:!reliable||weak||suspicious||f.Warning!=""?Verdict.Review:Verdict.Keep;
f.Cause=!reliable?"Insufficient reliable session reference":catastrophic?"Severe disappearance of reference stars":weak?"Uncertain alignment / reference photometry":cloud?"Likely cloud / transparency loss":optics?"Likely tracking or focus failure":suspicious?"Quality change needs review":"Consistent with the clean session reference"; f.Cause=!reliable?"Insufficient reliable session reference":catastrophic?"Severe disappearance of reference stars":weak?"Uncertain alignment / reference photometry":cloud?"Likely cloud / transparency loss":optics?"Likely tracking or focus failure":suspicious?"Quality change needs review":"Consistent with the clean session reference";
if(!reliable)f.Evidence.Add(new("Reference",local.Length,12,0,"Automatic rejection disabled: insufficient clear comparison frames, timestamp or aligned overlap")); if(!reliable)f.Evidence.Add(new("Reference",local.Length,12,0,"Automatic rejection disabled: insufficient clear comparison frames, timestamp or aligned overlap"));

View file

@ -0,0 +1,56 @@
namespace AstroFrame.Engine;
/// <summary>Display-only non-local means using 5x5 patches and a 13x13 search window.</summary>
public static class DenoisedPreview
{
public static PreviewDisplay Prepare(PreviewDisplay original,CancellationToken ct=default)
=>original with{Plane=Denoise(original.Plane,ct),Denoised=true};
public static PreviewPlane Denoise(PreviewPlane plane,CancellationToken ct=default)
{
ct.ThrowIfCancellationRequested();int w=plane.Width,h=plane.Height,count=plane.Pixels.Length;var input=plane.Pixels;
List<double> differences=[];for(int y=0;y<h;y++)for(int x=0;x<w-1;x++)differences.Add(Math.Abs((double)input[y*w+x]-input[y*w+x+1]));
float sigma=(float)(Robust.Median(differences)/.953872),variance=sigma*sigma,strength=.64f*variance;
if(!float.IsFinite(strength)||strength<=0)return new(w,h,(float[])input.Clone());
float[] output=(float[])input.Clone(),weights=Enumerable.Repeat(1f,count).ToArray(),distance=new float[count],horizontal=new float[count],local=new float[count];
// Keep offset and accumulation order consistent with the approved preview experiment.
for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)
{
if(dx==0&&dy==0)continue;
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();int row=y*w,otherRow=Reflect(y+dy,h)*w;
for(int x=0;x<w;x++){float delta=input[row+x]-input[otherRow+Reflect(x+dx,w)];distance[row+x]=delta*delta;}
}
Mean5(distance,horizontal,local,w,h,ct);
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();int row=y*w,otherRow=Reflect(y+dy,h)*w;
for(int x=0;x<w;x++)
{
int i=row+x;float weight=MathF.Exp(-Math.Max(0,local[i]-2*variance)/strength);
weights[i]+=weight;output[i]+=weight*input[otherRow+Reflect(x+dx,w)];
}
}
}
for(int i=0;i<count;i++)output[i]/=weights[i];return new(w,h,output);
}
static int Reflect(int position,int length)
{
if(length==1)return 0;
while(position<0||position>=length)position=position<0?-position:2*length-2-position;
return position;
}
static void Mean5(float[] input,float[] horizontal,float[] output,int w,int h,CancellationToken ct)
{
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();int row=y*w;
for(int x=0;x<w;x++){float sum=0;for(int k=-2;k<=2;k++)sum+=input[row+Reflect(x+k,w)];horizontal[row+x]=sum/5;}
}
for(int y=0;y<h;y++)
{
ct.ThrowIfCancellationRequested();for(int x=0;x<w;x++){float sum=0;for(int k=-2;k<=2;k++)sum+=horizontal[Reflect(y+k,h)*w+x];output[y*w+x]=sum/5;}
}
}
}

View file

@ -70,7 +70,7 @@ public sealed class Frame
} }
public sealed class Project public sealed class Project
{ {
public const string EngineVersion="0.2.1-spatial-reference-2"; public const string EngineVersion="0.2.3-spatial-reference-4";
public string Version {get;set;}=EngineVersion; public string Version {get;set;}=EngineVersion;
public string Name {get;set;}="Untitled"; public string Name {get;set;}="Untitled";
public string Source {get;set;}=""; public string Source {get;set;}="";

View file

@ -3,7 +3,8 @@ using System.Runtime.InteropServices;
namespace AstroFrame.Engine; namespace AstroFrame.Engine;
public sealed record PreviewPlane(int Width,int Height,float[] Pixels); public sealed record PreviewPlane(int Width,int Height,float[] Pixels);
public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid); public sealed record PreviewDisplay(PreviewPlane Plane,double Black,double White,double Mid,bool Denoised=false);
public enum PreviewMode { Frame, Denoised }
/// <summary>Display-only area reduction and screen transfer. Never used by a quality detector.</summary> /// <summary>Display-only area reduction and screen transfer. Never used by a quality detector.</summary>
public static class PreviewRenderer public static class PreviewRenderer
{ {
@ -19,11 +20,11 @@ public static class PreviewRenderer
} }
return new(w,h,pixels); return new(w,h,pixels);
} }
public static byte[] Render(PreviewPlane image,double target=.18,bool nebula=false) public static byte[] Render(PreviewPlane image,double target=.18)
=>Render(Prepare(image,nebula),target); =>Render(Prepare(image),target);
public static PreviewDisplay Prepare(PreviewPlane image,bool nebula=false) public static PreviewDisplay Prepare(PreviewPlane image,CancellationToken ct=default)
{ {
var plane=nebula?Reduce(new(image.Width,image.Height,image.Pixels,1),2):image; ct.ThrowIfCancellationRequested();var plane=image;
var values=plane.Pixels.Select(v=>(double)v).ToArray();double median=Robust.Median(values); var values=plane.Pixels.Select(v=>(double)v).ToArray();double median=Robust.Median(values);
List<double> differences=[];for(int y=0;y<plane.Height;y++)for(int x=0;x<plane.Width-1;x++)differences.Add(Math.Abs(plane.Pixels[y*plane.Width+x]-plane.Pixels[y*plane.Width+x+1])); List<double> differences=[];for(int y=0;y<plane.Height;y++)for(int x=0;x<plane.Width-1;x++)differences.Add(Math.Abs(plane.Pixels[y*plane.Width+x]-plane.Pixels[y*plane.Width+x+1]));
double noise=Math.Max(.001,Robust.Median(differences)/.953872),black=median-2.8*noise,white=Math.Max(Robust.Quantile(values,.9995),median+30*noise),span=white-black; double noise=Math.Max(.001,Robust.Median(differences)/.953872),black=median-2.8*noise,white=Math.Max(Robust.Quantile(values,.9995),median+30*noise),span=white-black;
@ -31,8 +32,8 @@ public static class PreviewRenderer
} }
public static byte[] Render(PreviewDisplay display,double target=.18) public static byte[] Render(PreviewDisplay display,double target=.18)
{ {
double mid=display.Mid,t=Math.Clamp(target,.06,.45),m=mid*(t-1)/((2*t-1)*mid-t),span=display.White-display.Black;byte[] output=new byte[display.Plane.Pixels.Length]; double mid=display.Mid,t=Math.Clamp(target+(display.Denoised?.07:0),.06,.48),m=mid*(t-1)/((2*t-1)*mid-t),span=display.White-display.Black;byte[] output=new byte[display.Plane.Pixels.Length];
for(int i=0;i<output.Length;i++){double v=Math.Clamp((display.Plane.Pixels[i]-display.Black)/span,0,1);output[i]=(byte)Math.Clamp(255*(m-1)*v/((2*m-1)*v-m),0,255);} for(int i=0;i<output.Length;i++){double v=Math.Clamp((display.Plane.Pixels[i]-display.Black)/span,0,1);double result=(m-1)*v/((2*m-1)*v-m);output[i]=(byte)Math.Clamp(255*result,0,255);}
return output; return output;
} }
public static void Write(ImagePlane image,string path,Frame? frame=null) public static void Write(ImagePlane image,string path,Frame? frame=null)

View file

@ -38,36 +38,59 @@ public static class SkyModel
} }
return map; return map;
} }
public static double[] Detrend(double[] values) public static double[] Detrend(double[] values)=>Detrend(values,false);
// Robust offset and gradient removal; quadratic terms also absorb smooth sky curvature.
public static double[] Detrend(double[] values,bool quadratic)
{ {
int terms=quadratic?6:3;
bool[] good=values.Select(double.IsFinite).ToArray();double[] residual=(double[])values.Clone(); bool[] good=values.Select(double.IsFinite).ToArray();double[] residual=(double[])values.Clone();
if(good.Count(v=>v)<12)return residual; if(good.Count(v=>v)<12)return residual;
for(int iteration=0;iteration<5;iteration++) for(int iteration=0;iteration<5;iteration++)
{ {
double[,] system=new double[3,4]; double[,] system=new double[terms,terms+1];
for(int i=0;i<Count;i++)if(good[i]) for(int i=0;i<Count;i++)if(good[i])
{ {
double[] v=[1,(i%Columns+.5)/Columns-.5,(i/Columns+.5)/Rows-.5]; double[] v=Basis(i,quadratic);
for(int r=0;r<3;r++){for(int c=0;c<3;c++)system[r,c]+=v[r]*v[c];system[r,3]+=v[r]*values[i];} for(int r=0;r<terms;r++){for(int c=0;c<terms;c++)system[r,c]+=v[r]*v[c];system[r,terms]+=v[r]*values[i];}
} }
double[] coefficients=Solve(system);for(int i=0;i<Count;i++)residual[i]=values[i]-coefficients[0]-coefficients[1]*((i%Columns+.5)/Columns-.5)-coefficients[2]*((i/Columns+.5)/Rows-.5); double[] coefficients=Solve(system);
for(int i=0;i<Count;i++){double[] v=Basis(i,quadratic);double r=values[i];for(int k=0;k<terms;k++)r-=coefficients[k]*v[k];residual[i]=r;}
double median=Robust.Median(residual.Where((_,i)=>good[i])),sigma=Math.Max(1,Robust.Mad(residual.Where((_,i)=>good[i]))); double median=Robust.Median(residual.Where((_,i)=>good[i])),sigma=Math.Max(1,Robust.Mad(residual.Where((_,i)=>good[i])));
for(int i=0;i<Count;i++)good[i]=double.IsFinite(residual[i])&&Math.Abs(residual[i]-median)<3*sigma; for(int i=0;i<Count;i++)good[i]=double.IsFinite(residual[i])&&Math.Abs(residual[i]-median)<3*sigma;
if(good.Count(v=>v)<12)break; if(good.Count(v=>v)<12)break;
} }
return residual; return residual;
} }
static double[] Basis(int i,bool quadratic)
{
double x=(i%Columns+.5)/Columns-.5,y=(i/Columns+.5)/Rows-.5;
return quadratic?[1,x,y,x*x,x*y,y*y]:[1,x,y];
}
/// <summary>Mean of each finite cell and its finite 3-by-3 neighbors.</summary>
public static double[] Smooth(double[] values)
{
double[] output=Enumerable.Repeat(double.NaN,Count).ToArray();
for(int row=0;row<Rows;row++)for(int col=0;col<Columns;col++)
{
if(!double.IsFinite(values[row*Columns+col]))continue;double sum=0;int n=0;
for(int dy=-1;dy<=1;dy++)for(int dx=-1;dx<=1;dx++)
{int r=row+dy,c=col+dx;if(r>=0&&r<Rows&&c>=0&&c<Columns&&double.IsFinite(values[r*Columns+c])){sum+=values[r*Columns+c];n++;}}
if(n>=3)output[row*Columns+col]=sum/n;
}
return output;
}
internal static double[] Solve(double[,] m) internal static double[] Solve(double[,] m)
{ {
for(int k=0;k<3;k++) int n=m.GetLength(0);
for(int k=0;k<n;k++)
{ {
int pivot=k;for(int r=k+1;r<3;r++)if(Math.Abs(m[r,k])>Math.Abs(m[pivot,k]))pivot=r; int pivot=k;for(int r=k+1;r<n;r++)if(Math.Abs(m[r,k])>Math.Abs(m[pivot,k]))pivot=r;
if(Math.Abs(m[pivot,k])<1e-8)return [Robust.Median([m[0,3]/Math.Max(m[0,0],1)]),0,0]; if(Math.Abs(m[pivot,k])<1e-8){double[] offset=new double[n];offset[0]=Robust.Median([m[0,n]/Math.Max(m[0,0],1)]);return offset;}
for(int c=k;c<4;c++)(m[k,c],m[pivot,c])=(m[pivot,c],m[k,c]); for(int c=k;c<=n;c++)(m[k,c],m[pivot,c])=(m[pivot,c],m[k,c]);
double divisor=m[k,k];for(int c=k;c<4;c++)m[k,c]/=divisor; double divisor=m[k,k];for(int c=k;c<=n;c++)m[k,c]/=divisor;
for(int r=0;r<3;r++)if(r!=k){double factor=m[r,k];for(int c=k;c<4;c++)m[r,c]-=factor*m[k,c];} for(int r=0;r<n;r++)if(r!=k){double factor=m[r,k];for(int c=k;c<=n;c++)m[r,c]-=factor*m[k,c];}
} }
return [m[0,3],m[1,3],m[2,3]]; return Enumerable.Range(0,n).Select(r=>m[r,n]).ToArray();
} }
public static int LargestComponent(bool[] mask) public static int LargestComponent(bool[] mask)
{ {

View file

@ -75,6 +75,13 @@ public static class SpatialReference
double floor=Math.Max(.1,referenceNoise*.08); double floor=Math.Max(.1,referenceNoise*.08);
double[] scatter=Enumerable.Range(0,SkyModel.Count).Select(j=>Math.Max(floor,Robust.Mad(residuals.Select(m=>m[j])))).ToArray(); double[] scatter=Enumerable.Range(0,SkyModel.Count).Select(j=>Math.Max(floor,Robust.Mad(residuals.Select(m=>m[j])))).ToArray();
var overlay=SkyOverlay.CreateReference(clean.Select(i=>a[i]),ct); var overlay=SkyOverlay.CreateReference(clean.Select(i=>a[i]),ct);
// Thin cloud can add only a few ADU of coherent glow per cell: below the
// fractional-noise floor above, but far above clear-frame scatter once smooth
// curvature is removed and neighboring cells are averaged. Scale that smoothed
// texture by the scatter clear reference frames show for the same statistic.
var textures=maps.Select(m=>SkyModel.Smooth(SkyModel.Detrend(m.Select((v,j)=>v-reference[j]).ToArray(),true))).ToArray();
double[] textureScatter=Enumerable.Range(0,SkyModel.Count).Select(j=>Robust.Mad(clean.Select(i=>textures[i][j]))).ToArray();
double textureFloor=Math.Max(Math.Max(referenceNoise*.002,1e-6),.5*Robust.Median(textureScatter.Where(v=>v>0)));
for(int i=0;i<a.Length;i++) for(int i=0;i<a.Length;i++)
{ {
ct.ThrowIfCancellationRequested();var f=a[i];var residual=Difference(maps[i],reference);int valid=residual.Count(double.IsFinite); ct.ThrowIfCancellationRequested();var f=a[i];var residual=Difference(maps[i],reference);int valid=residual.Count(double.IsFinite);
@ -85,7 +92,14 @@ public static class SpatialReference
bool[] positive=f.ExcessSkyMask.Select(v=>v>=128).ToArray(); bool[] positive=f.ExcessSkyMask.Select(v=>v>=128).ToArray();
f.AdditionalMeasurements["Cloud positive coverage"]=positive.Length==SkyModel.Count?(double)positive.Count(v=>v)/Math.Max(valid,1):0; f.AdditionalMeasurements["Cloud positive coverage"]=positive.Length==SkyModel.Count?(double)positive.Count(v=>v)/Math.Max(valid,1):0;
f.AdditionalMeasurements["Cloud positive connected coverage"]=positive.Length==SkyModel.Count?(double)SkyModel.LargestComponent(positive)/Math.Max(valid,1):0; f.AdditionalMeasurements["Cloud positive connected coverage"]=positive.Length==SkyModel.Count?(double)SkyModel.LargestComponent(positive)/Math.Max(valid,1):0;
MeasureCloudApertures(f,anchor,a,clean,normal,positive); MeasureCloudApertures(f,anchor,a,clean,normal,positive,"Cloud aperture");
double[] texture=textures[i].Select((v,j)=>v/Math.Max(textureFloor,textureScatter[j])).ToArray();
bool[] textured=texture.Select(v=>v>4).ToArray();int textureValid=texture.Count(double.IsFinite);
f.AdditionalMeasurements["Cloud texture significance"]=Robust.Quantile(texture,.98);
f.AdditionalMeasurements["Cloud texture coverage"]=(double)textured.Count(v=>v)/Math.Max(textureValid,1);
f.AdditionalMeasurements["Cloud texture connected coverage"]=(double)SkyModel.LargestComponent(textured)/Math.Max(textureValid,1);
MeasureCloudApertures(f,anchor,a,clean,normal,textured,"Cloud texture aperture");
MeasureDifferentialApertures(f,anchor,a,clean,normal,textured,texture.Select(v=>double.IsFinite(v)&&v<2).ToArray());
f.CloudMask=mask.Select(v=>(byte)(v?1:0)).ToArray();f.CloudCoverage=(double)mask.Count(v=>v)/Math.Max(valid,1);f.CloudSignificance=Robust.Quantile(z,.95); f.CloudMask=mask.Select(v=>(byte)(v?1:0)).ToArray();f.CloudCoverage=(double)mask.Count(v=>v)/Math.Max(valid,1);f.CloudSignificance=Robust.Quantile(z,.95);
f.ReferenceConfidence=stability*Math.Min(1,clean.Length/20.0)*(double)valid/SkyModel.Count; f.ReferenceConfidence=stability*Math.Min(1,clean.Length/20.0)*(double)valid/SkyModel.Count;
f.AdditionalMeasurements["Cloud connected coverage"]=(double)SkyModel.LargestComponent(mask)/Math.Max(valid,1); f.AdditionalMeasurements["Cloud connected coverage"]=(double)SkyModel.LargestComponent(mask)/Math.Max(valid,1);
@ -97,14 +111,14 @@ public static class SpatialReference
} }
} }
} }
static void MeasureCloudApertures(Frame frame,Frame anchor,Frame[] frames,int[] clean,double[] normal,bool[] positive) static void MeasureCloudApertures(Frame frame,Frame anchor,Frame[] frames,int[] clean,double[] normal,bool[] positive,string name)
{ {
var indices=Enumerable.Range(0,normal.Length).Where(j=>positive.Length==SkyModel.Count&& var indices=Enumerable.Range(0,normal.Length).Where(j=>positive.Length==SkyModel.Count&&
positive[Math.Clamp((int)(anchor.Stars[j].Y*SkyModel.Rows),0,SkyModel.Rows-1)*SkyModel.Columns+Math.Clamp((int)(anchor.Stars[j].X*SkyModel.Columns),0,SkyModel.Columns-1)]&& positive[Math.Clamp((int)(anchor.Stars[j].Y*SkyModel.Rows),0,SkyModel.Rows-1)*SkyModel.Columns+Math.Clamp((int)(anchor.Stars[j].X*SkyModel.Columns),0,SkyModel.Columns-1)]&&
normal[j]*anchor.Exposure>=30*anchor.Noise&&frame.ForcedFlux.Length==normal.Length&&double.IsFinite(frame.ForcedFlux[j])).ToArray(); normal[j]*anchor.Exposure>=30*anchor.Noise&&frame.ForcedFlux.Length==normal.Length&&double.IsFinite(frame.ForcedFlux[j])).ToArray();
frame.AdditionalMeasurements["Cloud aperture samples"]=indices.Length; frame.AdditionalMeasurements[name+" samples"]=indices.Length;
frame.AdditionalMeasurements["Cloud aperture regions"]=indices.Select(j=>Math.Clamp((int)(anchor.Stars[j].Y*4),0,3)*3+Math.Clamp((int)(anchor.Stars[j].X*3),0,2)).Distinct().Count(); frame.AdditionalMeasurements[name+" regions"]=indices.Select(j=>Math.Clamp((int)(anchor.Stars[j].Y*4),0,3)*3+Math.Clamp((int)(anchor.Stars[j].X*3),0,2)).Distinct().Count();
frame.AdditionalMeasurements["Cloud aperture flux ratio"]=0;frame.AdditionalMeasurements["Cloud aperture flux deviation"]=0; frame.AdditionalMeasurements[name+" flux ratio"]=0;frame.AdditionalMeasurements[name+" flux deviation"]=0;
if(indices.Length<20)return; if(indices.Length<20)return;
double Flux(Frame f)=>Robust.Median(indices.Where(j=>f.ForcedFlux.Length==normal.Length&&double.IsFinite(f.ForcedFlux[j])).Select(j=>f.ForcedFlux[j]/normal[j])); double Flux(Frame f)=>Robust.Median(indices.Where(j=>f.ForcedFlux.Length==normal.Length&&double.IsFinite(f.ForcedFlux[j])).Select(j=>f.ForcedFlux[j]/normal[j]));
var comparisons=Nearby(frames,clean,frame).Where(f=>f.ForcedFlux.Length==normal.Length&&indices.Count(j=>double.IsFinite(f.ForcedFlux[j]))>=indices.Length*.8).Select(Flux).ToArray(); var comparisons=Nearby(frames,clean,frame).Where(f=>f.ForcedFlux.Length==normal.Length&&indices.Count(j=>double.IsFinite(f.ForcedFlux[j]))>=indices.Length*.8).Select(Flux).ToArray();
@ -123,9 +137,28 @@ public static class SpatialReference
double uncertainty=1.253*Math.Sqrt(indices.Sum(j=>Math.Pow(LocalNoise(j)*Math.Sqrt(varianceFactor)/Math.Max(1,frame.Exposure)/normal[j],2)))/indices.Length; double uncertainty=1.253*Math.Sqrt(indices.Sum(j=>Math.Pow(LocalNoise(j)*Math.Sqrt(varianceFactor)/Math.Max(1,frame.Exposure)/normal[j],2)))/indices.Length;
double spread=Math.Max(baseline*.03,Math.Max(Robust.Mad(comparisons),uncertainty)); double spread=Math.Max(baseline*.03,Math.Max(Robust.Mad(comparisons),uncertainty));
double measured=Flux(frame); double measured=Flux(frame);
frame.AdditionalMeasurements["Cloud aperture flux ratio"]=measured/baseline; frame.AdditionalMeasurements[name+" flux ratio"]=measured/baseline;
frame.AdditionalMeasurements["Cloud aperture flux deviation"]=(baseline-measured)/spread; frame.AdditionalMeasurements[name+" flux deviation"]=(baseline-measured)/spread;
frame.AdditionalMeasurements["Cloud aperture flux uncertainty"]=uncertainty/baseline; frame.AdditionalMeasurements[name+" flux uncertainty"]=uncertainty/baseline;
}
// Stars away from the texture share global transparency, seeing and airmass changes.
// Compare the inside/outside flux ratio with the same apertures in nearby clear frames.
static void MeasureDifferentialApertures(Frame frame,Frame anchor,Frame[] frames,int[] clean,double[] normal,bool[] inside,bool[] outside)
{
int[] Select(bool[] mask)=>Enumerable.Range(0,normal.Length).Where(j=>mask[Math.Clamp((int)(anchor.Stars[j].Y*SkyModel.Rows),0,SkyModel.Rows-1)*SkyModel.Columns+Math.Clamp((int)(anchor.Stars[j].X*SkyModel.Columns),0,SkyModel.Columns-1)]&&
normal[j]*anchor.Exposure>=30*anchor.Noise&&frame.ForcedFlux.Length==normal.Length&&double.IsFinite(frame.ForcedFlux[j])).ToArray();
int[] a=Select(inside),b=Select(outside);
frame.AdditionalMeasurements["Cloud texture differential samples"]=Math.Min(a.Length,b.Length);
frame.AdditionalMeasurements["Cloud texture differential flux ratio"]=0;frame.AdditionalMeasurements["Cloud texture differential flux deviation"]=0;
if(a.Length<20||b.Length<20)return;
double Flux(Frame f,int[] indices)=>Robust.Median(indices.Where(j=>double.IsFinite(f.ForcedFlux[j])).Select(j=>f.ForcedFlux[j]/normal[j]));
double Ratio(Frame f)=>Flux(f,a)/Math.Max(Flux(f,b),1e-9);
var comparisons=Nearby(frames,clean,frame).Where(f=>f.ForcedFlux.Length==normal.Length&&a.Count(j=>double.IsFinite(f.ForcedFlux[j]))>=a.Length*.8&&b.Count(j=>double.IsFinite(f.ForcedFlux[j]))>=b.Length*.8).Select(Ratio).ToArray();
double baseline=Robust.Median(comparisons);if(comparisons.Length<12||baseline<=0)return;
double measured=Ratio(frame),spread=Math.Max(baseline*.01,Robust.Mad(comparisons));
frame.AdditionalMeasurements["Cloud texture differential flux ratio"]=measured/baseline;
frame.AdditionalMeasurements["Cloud texture differential flux deviation"]=(baseline-measured)/spread;
frame.AdditionalMeasurements["Cloud texture differential flux scatter"]=spread/baseline;
} }
static IEnumerable<Frame> Nearby(Frame[] frames,int[] clean,Frame selected)=>clean.Select(i=>frames[i]).Where(f=>f.Id!=selected.Id) static IEnumerable<Frame> Nearby(Frame[] frames,int[] clean,Frame selected)=>clean.Select(i=>frames[i]).Where(f=>f.Id!=selected.Id)
.OrderBy(f=>Math.Abs((f.Timestamp.GetValueOrDefault()-selected.Timestamp.GetValueOrDefault()).TotalSeconds)).Take(40); .OrderBy(f=>Math.Abs((f.Timestamp.GetValueOrDefault()-selected.Timestamp.GetValueOrDefault()).TotalSeconds)).Take(40);

View file

@ -1,44 +1,74 @@
namespace AstroFrame.Engine; namespace AstroFrame.Engine;
public sealed record StarSnippet(int Number,byte[] Selected,byte[] Comparison); public sealed record StarShape(double X,double Y,double Major,double Minor,double Angle)
public sealed record StarDetail(string SelectedName,string ComparisonName,List<StarSnippet> Stars,int Size=13); {
public double Ellipticity=>1-Minor/Major;
}
public sealed record StarSample(byte[] Pixels,StarShape? Shape);
public sealed record StarSnippet(int Number,StarSample Selected,StarSample? Comparison);
public sealed record StarDetail(string SelectedName,string? ComparisonName,List<StarSnippet> Stars,int Size=13);
/// <summary>Read-only matched source samples for human morphology review; no quality decisions.</summary> /// <summary>Read-only matched source samples for human morphology review; no quality decisions.</summary>
public static class StellarDetail public static class StellarDetail
{ {
public static Frame? Comparison(Project project,Frame selected) public static Frame? Comparison(Project project,Frame selected)
{ {
double normal=selected.Baselines.GetValueOrDefault("Ellipticity"),width=selected.Baselines.GetValueOrDefault("FWHM"); double normal=selected.Baselines.GetValueOrDefault("Ellipticity"),width=selected.Baselines.GetValueOrDefault("FWHM");
var available=project.Frames.Where(f=>f.Id!=selected.Id&&f.Session==selected.Session&&f.Effective==Verdict.Keep&&f.Error==""&&f.MatchFraction>.5); if(!Aligned(selected))return null;
var available=project.Frames.Where(f=>f.Id!=selected.Id&&f.Session==selected.Session&&f.Effective==Verdict.Keep&&f.Measured&&f.Error==""&&f.MatchFraction>.5&&f.ReferenceId==selected.ReferenceId&&f.Width==selected.Width&&f.Height==selected.Height&&Aligned(f));
var representative=available.Where(f=>(normal<=0||f.Ellipticity<normal+.06)&&(width<=0||f.Fwhm<width*1.15)).ToArray(); var representative=available.Where(f=>(normal<=0||f.Ellipticity<normal+.06)&&(width<=0||f.Fwhm<width*1.15)).ToArray();
return (representative.Length>0?representative:available).OrderBy(f=>Math.Abs((f.Timestamp.GetValueOrDefault()-selected.Timestamp.GetValueOrDefault()).TotalSeconds)).FirstOrDefault(); return (representative.Length>0?representative:available).OrderBy(f=>Math.Abs((f.Timestamp.GetValueOrDefault()-selected.Timestamp.GetValueOrDefault()).TotalSeconds)).FirstOrDefault();
} }
public static StarDetail Read(string directory,Frame selected,Frame comparison,CancellationToken ct=default) static bool Aligned(Frame f)=>f.ReferenceId!=""&&f.Alignment.Length==4&&f.Alignment.All(double.IsFinite)&&f.Alignment[0]*f.Alignment[0]+f.Alignment[1]*f.Alignment[1]>=.5;
public static StarDetail Read(string directory,Frame selected,Frame? comparison,CancellationToken ct=default)
{ {
ImagePlane Source(Frame f) ImagePlane Source(Frame f)
{var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified)throw new IOException("Source changed; reanalyze before inspecting");return Fits.Read(f.Path,ct);} {var info=new FileInfo(f.Path);if(!info.Exists||info.Length!=f.Length||info.LastWriteTimeUtc.Ticks!=f.Modified)throw new IOException("Source changed; reanalyze before inspecting");return Fits.Read(f.Path,ct);}
var a=Source(selected);var b=Source(comparison);List<Star> stars; var a=Source(selected);var b=comparison==null?null:Source(comparison);List<Star> stars;
if(ProjectStore.LoadCatalog(directory,selected))stars=selected.Stars; if(ProjectStore.LoadCatalog(directory,selected))stars=selected.Stars;
else{var measured=Fits.Inspect(selected.Path);new StellarDetector().Measure(measured,a,ct);stars=measured.Stars;} else{var measured=Fits.Inspect(selected.Path);new StellarDetector().Measure(measured,a,ct);stars=measured.Stars;}
if(selected.ReferenceId!=comparison.ReferenceId||selected.Alignment.Length!=4||comparison.Alignment.Length!=4)throw new InvalidDataException("Matched source comparison is unavailable: no shared reliable alignment"); if(comparison!=null&&(selected.ReferenceId!=comparison.ReferenceId||selected.Width!=comparison.Width||selected.Height!=comparison.Height||!Aligned(selected)||!Aligned(comparison)))throw new InvalidDataException("Matched source comparison is unavailable: no shared reliable alignment");
double aspect=(double)selected.Height/selected.Width;var from=selected.Alignment;var to=comparison.Alignment;List<Star> chosen=[];List<StarSnippet> snippets=[]; double aspect=(double)selected.Height/selected.Width;var from=selected.Alignment;List<Star> chosen=[];List<StarSnippet> snippets=[];
foreach(var s in stars) // Use the strong-star population that supplies the frame shape metric, spread across the field.
foreach(var s in stars.OrderByDescending(s=>s.Flux).Take(250))
{ {
ct.ThrowIfCancellationRequested();if(s.X<.04||s.X>.96||s.Y<.04||s.Y>.96||chosen.Any(t=>Math.Pow(t.X-s.X,2)+Math.Pow((t.Y-s.Y)*aspect,2)<.04*.04))continue; ct.ThrowIfCancellationRequested();if(!CanCrop(a,s.X,s.Y)||chosen.Any(t=>Math.Pow(t.X-s.X,2)+Math.Pow((t.Y-s.Y)*aspect,2)<.04*.04))continue;
double sx=s.X-from[2],sy=s.Y*aspect-from[3],d=from[0]*from[0]+from[1]*from[1];if(d<.5)throw new InvalidDataException("Unreliable image alignment"); StarSample? other=null;
if(comparison!=null&&b!=null)
{
var to=comparison.Alignment;double sx=s.X-from[2],sy=s.Y*aspect-from[3],d=from[0]*from[0]+from[1]*from[1];
double rx=(from[0]*sx+from[1]*sy)/d,ry=(-from[1]*sx+from[0]*sy)/d,x=to[0]*rx-to[1]*ry+to[2],y=(to[1]*rx+to[0]*ry+to[3])/aspect; double rx=(from[0]*sx+from[1]*sy)/d,ry=(-from[1]*sx+from[0]*sy)/d,x=to[0]*rx-to[1]*ry+to[2],y=(to[1]*rx+to[0]*ry+to[3])/aspect;
if(x<.04||x>.96||y<.04||y>.96)continue;chosen.Add(s); if(!CanCrop(b,x,y))continue;other=Crop(b,x,y,Noise(comparison,x,y));
snippets.Add(new(snippets.Count+1,Crop(a,s.X,s.Y),Crop(b,x,y)));if(snippets.Count==8)break; }
chosen.Add(s);snippets.Add(new(snippets.Count+1,Crop(a,s.X,s.Y,Noise(selected,s.X,s.Y)),other));if(snippets.Count==8)break;
} }
if(snippets.Count==0)throw new InvalidDataException("No suitable matched stars in the overlapping field"); if(snippets.Count==0)throw new InvalidDataException("No suitable matched stars in the overlapping field");
return new(selected.Name,comparison.Name,snippets); return new(selected.Name,comparison?.Name,snippets);
} }
static byte[] Crop(ImagePlane image,double px,double py) static bool CanCrop(ImagePlane image,double x,double y)=>double.IsFinite(x)&&double.IsFinite(y)&&Math.Round(x*image.Width)>=9&&Math.Round(x*image.Width)<image.Width-9&&Math.Round(y*image.Height)>=9&&Math.Round(y*image.Height)<image.Height-9;
static double Noise(Frame f,double x,double y)
{int tile=Math.Clamp((int)(y*4),0,3)*3+Math.Clamp((int)(x*3),0,2);return f.Regions.Count==12?f.Regions[tile].Noise:f.Noise;}
static StarSample Crop(ImagePlane image,double px,double py,double noise)
{ {
int x=(int)Math.Round(px*image.Width),y=(int)Math.Round(py*image.Height);double peak=double.MinValue;int bestX=x,bestY=y; int x=(int)Math.Round(px*image.Width),y=(int)Math.Round(py*image.Height);double peak=double.MinValue;int bestX=x,bestY=y;
for(int dy=-2;dy<=2;dy++)for(int dx=-2;dx<=2;dx++)if(image.Pixels[(y+dy)*image.Width+x+dx]>peak){peak=image.Pixels[(y+dy)*image.Width+x+dx];bestX=x+dx;bestY=y+dy;} for(int dy=-2;dy<=2;dy++)for(int dx=-2;dx<=2;dx++)if(image.Pixels[(y+dy)*image.Width+x+dx]>peak){peak=image.Pixels[(y+dy)*image.Width+x+dx];bestX=x+dx;bestY=y+dy;}
List<double> edge=[];for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)if(dx*dx+dy*dy>=25)edge.Add(image.Pixels[(bestY+dy)*image.Width+bestX+dx]); double[] samples=new double[169];for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)samples[(dy+6)*13+dx+6]=image.Pixels[(bestY+dy)*image.Width+bestX+dx];
double sky=Robust.Median(edge),range=Math.Max(1,peak-sky);byte[] pixels=new byte[169]; double sky=Sky(samples),range=Math.Max(1,peak-sky);byte[] pixels=samples.Select(v=>(byte)Math.Clamp(255*(v-sky)/range,0,255)).ToArray();
for(int dy=-6;dy<=6;dy++)for(int dx=-6;dx<=6;dx++)pixels[(dy+6)*13+dx+6]=(byte)Math.Clamp(255*(image.Pixels[(bestY+dy)*image.Width+bestX+dx]-sky)/range,0,255); return new(pixels,Describe(samples,noise));
return pixels; }
static double Sky(IReadOnlyList<double> samples)=>Robust.Median(Enumerable.Range(0,169).Where(i=>{int x=i%13-6,y=i/13-6;return x*x+y*y>=25&&x*x+y*y<=36;}).Select(i=>samples[i]));
/// <summary>Core second moments in source-sample coordinates; guides do not change classification.</summary>
public static StarShape? Describe(IReadOnlyList<double> samples,double noise=0)
{
if(samples.Count!=169||samples.Any(v=>!double.IsFinite(v))||!double.IsFinite(noise))return null;
double sky=Sky(samples),sum=0,mx=0,my=0,xx=0,yy=0,xy=0;
for(int y=-4;y<=4;y++)for(int x=-4;x<=4;x++)
{
if(x*x+y*y>16)continue;double weight=Math.Max(0,samples[(y+6)*13+x+6]-sky-Math.Max(0,noise));
sum+=weight;mx+=x*weight;my+=y*weight;xx+=x*x*weight;yy+=y*y*weight;xy+=x*y*weight;
}
if(sum<=0)return null;mx/=sum;my/=sum;xx=xx/sum-mx*mx;yy=yy/sum-my*my;xy=xy/sum-mx*my;
double d=Math.Sqrt((xx-yy)*(xx-yy)+4*xy*xy),major=(xx+yy+d)/2,minor=(xx+yy-d)/2;
if(minor<.18||major>12||Math.Abs(mx)>2||Math.Abs(my)>2)return null;
return new(mx+6.5,my+6.5,2.35482*Math.Sqrt(major),2.35482*Math.Sqrt(minor),.5*Math.Atan2(2*xy,xx-yy));
} }
} }

View file

@ -60,7 +60,7 @@ static class ImageRegression
} }
finally{Directory.Delete(directory,true);} finally{Directory.Delete(directory,true);}
} }
static void WriteFits(string path,float[] pixels,int width,int height,int n) internal static void WriteFits(string path,float[] pixels,int width,int height,int n)
{ {
string Card(string key,string value)=>(key.PadRight(8)+"= "+value).PadRight(80); string Card(string key,string value)=>(key.PadRight(8)+"= "+value).PadRight(80);
string date=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30).ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture); string date=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30).ToString("yyyy-MM-ddTHH:mm:ss",CultureInfo.InvariantCulture);

View file

@ -7,11 +7,25 @@ static class PreviewRegression
const int w=360,h=640;var random=new Random(839);float[] pixels=new float[w*h]; const int w=360,h=640;var random=new Random(839);float[] pixels=new float[w*h];
for(int y=0;y<h;y++)for(int x=0;x<w;x++)pixels[y*w+x]=(float)(1000+40*Math.Exp(-Math.Pow((x-190)/90.0,2)-Math.Pow((y-300)/200.0,2))+(random.NextDouble()-.5)*100); for(int y=0;y<h;y++)for(int x=0;x<w;x++)pixels[y*w+x]=(float)(1000+40*Math.Exp(-Math.Pow((x-190)/90.0,2)-Math.Pow((y-300)/200.0,2))+(random.NextDouble()-.5)*100);
pixels[290*w+172]=5000;var image=new ImagePlane(w,h,pixels,1);float[] untouched=(float[])pixels.Clone(); pixels[290*w+172]=5000;var image=new ImagePlane(w,h,pixels,1);float[] untouched=(float[])pixels.Clone();
var reduced=PreviewRenderer.Reduce(image,3);var frame=PreviewRenderer.Render(reduced);var diffuse=PreviewRenderer.Render(reduced,.18,true); var reduced=PreviewRenderer.Reduce(image,3);var frame=PreviewRenderer.Render(reduced);
List<double> diff=[];for(int y=0;y<reduced.Height;y++)for(int x=0;x<reduced.Width-1;x++)diff.Add(Math.Abs(frame[y*reduced.Width+x]-frame[y*reduced.Width+x+1])/255.0); List<double> diff=[];for(int y=0;y<reduced.Height;y++)for(int x=0;x<reduced.Width-1;x++)diff.Add(Math.Abs(frame[y*reduced.Width+x]-frame[y*reduced.Width+x+1])/255.0);
check(Robust.Median(diff)<.06&&Robust.Median(frame.Select(v=>v/255.0))<.25,"preview transfer keeps background grain subordinate to the image"); check(Robust.Median(diff)<.06&&Robust.Median(frame.Select(v=>v/255.0))<.25,"preview transfer keeps background grain subordinate to the image");
check(untouched.SequenceEqual(pixels),"preview reduction, stretching and nebula mode never alter analysis pixels"); check(untouched.SequenceEqual(pixels),"preview reduction and stretching never alter analysis pixels");
check(frame.Max()>frame[0]+80&&diffuse.Length<frame.Length,"preview preserves conspicuous stars and exposes a distinct diffuse-detail view"); check(frame.Max()>frame[0]+80,"frame preview preserves conspicuous stars");
const int side=96;random=new Random(7461);float[] sky=new float[side*side];for(int i=0;i<sky.Length;i++)sky[i]=(float)(1000+(random.NextDouble()-.5)*60);
float[] original=(float[])sky.Clone();var standard=PreviewRenderer.Prepare(new(side,side,sky));var denoised=DenoisedPreview.Prepare(standard);
double Spread(byte[] values){double mean=values.Average(v=>(double)v);return Math.Sqrt(values.Average(v=>Math.Pow(v-mean,2)));}
check(Spread(PreviewRenderer.Render(denoised))<Spread(PreviewRenderer.Render(standard))*.5,"denoised view reduces displayed empty-sky noise instead of amplifying residual blotches");
check(denoised.Black==standard.Black&&denoised.White==standard.White&&denoised.Mid==standard.Mid,"denoising retains the original screen-transfer parameters");
check(sky.SequenceEqual(original)&&denoised.Plane.Width==side&&denoised.Plane.Height==side,"denoising preserves input pixels and preview geometry");
var dim=PreviewRenderer.Render(denoised,.10);var bright=PreviewRenderer.Render(denoised,.30);
check(dim.Zip(bright).All(pair=>pair.Second>=pair.First),"denoised brightness adjustments remain monotonic");
sky[48*side+48]=3000;for(int y=0;y<side;y++)for(int x=0;x<side;x++)sky[y*side+x]+=(float)(20*Math.Exp(-Math.Pow((x-30)/10.0,2)-Math.Pow((y-30)/14.0,2)));
var detail=DenoisedPreview.Denoise(new(side,side,sky));
check(detail.Pixels[48*side+48]>2900&&detail.Pixels[30*side+30]>1010,"patch denoising preserves bright stars and diffuse signal");
var flat=Enumerable.Repeat(1000f,1024).ToArray();check(DenoisedPreview.Denoise(new(32,32,flat)).Pixels.SequenceEqual(flat),"denoising a constant field invents no structure");
check(DenoisedPreview.Denoise(new(1,3,[1000,1001,999])).Pixels.All(float.IsFinite),"small preview dimensions use safe reflected borders");
using(var cancel=new CancellationTokenSource()){cancel.Cancel();bool cancelled=false;try{DenoisedPreview.Denoise(new(side,side,sky),cancel.Token);}catch(OperationCanceledException){cancelled=true;}check(cancelled,"denoised preview preparation respects cancellation");}
string path=Path.Combine(Path.GetTempPath(),"AstroFrame-preview-"+Guid.NewGuid()+".bin");var f=new Frame{Length=7654,Modified=4321}; string path=Path.Combine(Path.GetTempPath(),"AstroFrame-preview-"+Guid.NewGuid()+".bin");var f=new Frame{Length=7654,Modified=4321};
try try
{ {

View file

@ -129,4 +129,5 @@ await ImageRegression.Run(Check);
QualityRegression.Run(Check); QualityRegression.Run(Check);
OverlayRegression.Run(Check); OverlayRegression.Run(Check);
PreviewRegression.Run(Check); PreviewRegression.Run(Check);
StellarDetailRegression.Run(Check);
Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality."); Console.WriteLine($"{passed} checks passed. Synthetic tests validate mechanics, not astrophotography stack quality.");

View file

@ -16,7 +16,8 @@ static class QualityRegression
var opaque=Make(40);opaque.Stars=stars.Take(25).ToList();opaque.StarCount=25; var opaque=Make(40);opaque.Stars=stars.Take(25).ToList();opaque.StarCount=25;
var broad=Make(41);var gradient=Make(42);var uncertain=Make(43);var cohort=Make(44);var trailing=Make(45); var broad=Make(41);var gradient=Make(42);var uncertain=Make(43);var cohort=Make(44);var trailing=Make(45);
var subtleShape=Make(46);var insufficient=Make(47);var noisyFlux=Make(48); var subtleShape=Make(46);var insufficient=Make(47);var noisyFlux=Make(48);
frames.AddRange([opaque,broad,gradient,uncertain,cohort,trailing,subtleShape,insufficient,noisyFlux]); var thinFlagged=Make(49);var thinUndimmed=Make(50);var thinClean=Make(51);var unconfirmedShape=Make(52);var moderateCloud=Make(53);
frames.AddRange([opaque,broad,gradient,uncertain,cohort,trailing,subtleShape,insufficient,noisyFlux,thinFlagged,thinUndimmed,thinClean,unconfirmedShape,moderateCloud]);
foreach(var f in frames) foreach(var f in frames)
{ {
Matching.Measure(frames[0],f);f.Transparency=1;f.RegionFlux=Enumerable.Repeat(1.0,12).ToArray();f.RegionMatches=Enumerable.Repeat(8,12).ToArray(); Matching.Measure(frames[0],f);f.Transparency=1;f.RegionFlux=Enumerable.Repeat(1.0,12).ToArray();f.RegionMatches=Enumerable.Repeat(8,12).ToArray();
@ -42,15 +43,40 @@ static class QualityRegression
trailing.Ellipticity=.3;trailing.AdditionalMeasurements["Matched shape samples"]=100; trailing.Ellipticity=.3;trailing.AdditionalMeasurements["Matched shape samples"]=100;
trailing.AdditionalMeasurements["Matched shape change"]=.2;trailing.AdditionalMeasurements["Matched shape uncertainty"]=.01; trailing.AdditionalMeasurements["Matched shape change"]=.2;trailing.AdditionalMeasurements["Matched shape uncertainty"]=.01;
subtleShape.Ellipticity=.3;subtleShape.AdditionalMeasurements["Matched shape samples"]=100; subtleShape.Ellipticity=.3;subtleShape.AdditionalMeasurements["Matched shape samples"]=100;
subtleShape.AdditionalMeasurements["Matched shape change"]=.12;subtleShape.AdditionalMeasurements["Matched shape uncertainty"]=.005; subtleShape.AdditionalMeasurements["Matched shape change"]=.10;subtleShape.AdditionalMeasurements["Matched shape uncertainty"]=.005;
void Texture(Frame f,double ratio,double deviation,bool flagged)
{
f.AdditionalMeasurements["Clear reference member"]=0;
f.AdditionalMeasurements["Cloud texture significance"]=20;f.AdditionalMeasurements["Cloud texture coverage"]=.15;
f.AdditionalMeasurements["Cloud texture connected coverage"]=.10;f.AdditionalMeasurements["Cloud texture differential samples"]=60;
f.AdditionalMeasurements["Cloud texture differential flux ratio"]=ratio;f.AdditionalMeasurements["Cloud texture differential flux deviation"]=deviation;
if(!flagged)return;
// Weak, uncorroborated planar structure routes the frame to REVIEW.
Cloud(f,6,.05,1);
}
Texture(thinFlagged,.96,4,true);Texture(thinUndimmed,1,.3,true);Texture(thinClean,.96,4,false);
unconfirmedShape.Ellipticity=.3;unconfirmedShape.AdditionalMeasurements["Matched shape samples"]=30;
unconfirmedShape.AdditionalMeasurements["Matched shape change"]=.2;unconfirmedShape.AdditionalMeasurements["Matched shape uncertainty"]=.01;
// Flagged sky structure, strong texture, and two moderate, independent dimming measurements.
Texture(moderateCloud,.98,2,false);Cloud(moderateCloud,8,.10,.91);moderateCloud.AdditionalMeasurements["Cloud aperture flux deviation"]=2.9;
moderateCloud.AdditionalMeasurements["Cloud texture significance"]=30;moderateCloud.Transparency=1;
Classification.Run(frames); Classification.Run(frames);
check(thinFlagged.Automatic==Verdict.Reject&&thinFlagged.Evidence.Any(e=>e.Metric=="Cloud texture"),"flagged frame with thin cloud texture that dims stars beneath it rejects");
check(thinUndimmed.Automatic==Verdict.Review,"thin texture without differential stellar dimming stays REVIEW");
check(thinClean.Automatic==Verdict.Keep,"thin cloud texture alone never rejects an otherwise clean KEEP");
check(moderateCloud.Automatic==Verdict.Reject&&moderateCloud.Evidence.Any(e=>e.Metric=="Cloud texture"),"flagged sky structure with strong texture and two moderate dimming measurements rejects");
double[] curved=Enumerable.Range(0,SkyModel.Count).Select(i=>{double x=(i%SkyModel.Columns+.5)/SkyModel.Columns-.5,y=(i/SkyModel.Columns+.5)/SkyModel.Rows-.5;return 1000+40*x-30*y+200*x*x-150*x*y+120*y*y;}).ToArray();
check(SkyModel.Detrend(curved,true).All(v=>Math.Abs(v)<.01)&&SkyModel.Detrend(curved).Max(Math.Abs)>5,"quadratic detrending removes smooth sky curvature that a plane leaves behind");
double[] spike=new double[SkyModel.Count];spike[10*SkyModel.Columns+10]=9;var smoothed=SkyModel.Smooth(spike);
check(Math.Abs(smoothed[10*SkyModel.Columns+10]-1)<1e-9&&Math.Abs(smoothed[11*SkyModel.Columns+11]-1)<1e-9&&smoothed[12*SkyModel.Columns+12]==0,"texture smoothing averages each cell with its 3x3 neighbors");
check(opaque.Automatic==Verdict.Reject,"severe cloud with accurate geometry rejects despite missing reference stars"); check(opaque.Automatic==Verdict.Reject,"severe cloud with accurate geometry rejects despite missing reference stars");
check(broad.Automatic==Verdict.Reject,"broad coherent sky structure with local aperture attenuation rejects"); check(broad.Automatic==Verdict.Reject,"broad coherent sky structure with local aperture attenuation rejects");
check(gradient.Automatic==Verdict.Review,"uncorroborated sky structure stays REVIEW rather than rejecting a possible gradient"); check(gradient.Automatic==Verdict.Review,"uncorroborated sky structure stays REVIEW rather than rejecting a possible gradient");
check(uncertain.Automatic==Verdict.Review,"severe apparent cloud with unverified geometry stays REVIEW"); check(uncertain.Automatic==Verdict.Review,"severe apparent cloud with unverified geometry stays REVIEW");
check(cohort.Automatic==Verdict.Keep,"matched-star evidence can resolve an elongation flag caused by a changed detection cohort"); check(cohort.Automatic==Verdict.Keep,"matched-star evidence can resolve an elongation flag caused by a changed detection cohort");
check(trailing.Automatic==Verdict.Review,"matched-star elongation remains REVIEW when other measurements are normal"); check(trailing.Automatic==Verdict.Reject&&trailing.Cause=="Likely tracking or focus failure","elongation confirmed by the same matched reference stars rejects as a roundness outlier");
check(subtleShape.Automatic==Verdict.Review,"measurable sub-threshold matched elongation is not promoted to KEEP"); check(unconfirmedShape.Automatic==Verdict.Review,"elongation without enough matched reference stars stays REVIEW");
check(subtleShape.Automatic==Verdict.Review,"matched elongation between the dismissal and rejection limits stays REVIEW");
check(insufficient.Automatic==Verdict.Review&&noisyFlux.Automatic==Verdict.Review,"too few or noisy affected apertures cannot authorize cloud rejection"); check(insufficient.Automatic==Verdict.Review&&noisyFlux.Automatic==Verdict.Review,"too few or noisy affected apertures cannot authorize cloud rejection");
check(frames.Take(40).All(f=>f.Automatic==Verdict.Keep),"quality policy changes preserve unchanged clear comparisons"); check(frames.Take(40).All(f=>f.Automatic==Verdict.Keep),"quality policy changes preserve unchanged clear comparisons");
var options=new JsonSerializerOptions{PropertyNameCaseInsensitive=true,Converters={new JsonStringEnumConverter()}}; var options=new JsonSerializerOptions{PropertyNameCaseInsensitive=true,Converters={new JsonStringEnumConverter()}};

View file

@ -0,0 +1,51 @@
using AstroFrame.Engine;
using System.Security.Cryptography;
static class StellarDetailRegression
{
public static void Run(Action<bool,string> check)
{
double[] Gaussian(double major,double minor,double angle)=>Enumerable.Range(0,169).Select(i=>
{
double x=i%13-6,y=i/13-6,u=x*Math.Cos(angle)+y*Math.Sin(angle),v=-x*Math.Sin(angle)+y*Math.Cos(angle);
return 1000+3000*Math.Exp(-.5*(u*u/(major*major)+v*v/(minor*minor)));
}).ToArray();
var round=StellarDetail.Describe(Gaussian(1,1,0))!;
var stretched=StellarDetail.Describe(Gaussian(1.4,.7,.6))!;
check(round.Ellipticity<.001&&stretched.Ellipticity>.45&&Math.Abs(stretched.Angle-.6)<.03,"source-moment guides distinguish round stars from rotated elongation");
check(Math.Abs(stretched.X-6.5)<.01&&Math.Abs(stretched.Y-6.5)<.01,"shape guides remain centered on source pixel centers");
check(StellarDetail.Describe(Enumerable.Repeat(1000.0,169).ToArray())==null&&StellarDetail.Describe([double.NaN])==null,"empty or invalid stellar profiles do not invent shape guides");
string directory=Path.Combine(Path.GetTempPath(),"AstroFrame-stars-"+Guid.NewGuid());Directory.CreateDirectory(directory);
try
{
const int size=64;var positions=new[]{(X:14,Y:16),(X:40,Y:38),(X:18,Y:43)};List<Frame> frames=[];
for(int n=0;n<2;n++)
{
float[] pixels=Enumerable.Repeat(1000f,size*size).ToArray();
foreach(var p in positions)for(int y=0;y<size;y++)for(int x=0;x<size;x++)
{
double dx=x-p.X-(n==0?0:3),dy=y-p.Y+(n==0?0:2),u=dx*Math.Cos(.6)+dy*Math.Sin(.6),v=-dx*Math.Sin(.6)+dy*Math.Cos(.6),a=n==0?1.4:1,b=n==0?.7:1;
pixels[y*size+x]+=(float)(3000*Math.Exp(-.5*(u*u/(a*a)+v*v/(b*b))));
}
string path=Path.Combine(directory,$"star{n}.fit");ImageRegression.WriteFits(path,pixels,size,size,n);
var f=Fits.Inspect(path);f.Measured=true;f.Session="shared";f.Automatic=Verdict.Keep;f.MatchFraction=1;f.ReferenceId="reference";f.Alignment=[1,0,n==0?0:3.0/size,n==0?0:-2.0/size];
f.Stars=positions.Select(p=>new Star((double)p.X/size,(double)p.Y/size,100,3,n==0?.5:0)).ToList();frames.Add(f);
}
var project=new Project{Frames=frames};ProjectStore.Save(project,directory);
byte[] hash=SHA256.HashData(File.ReadAllBytes(frames[0].Path));
check(StellarDetail.Comparison(project,frames[0])==frames[1],"elongation inspector selects an aligned same-session KEEP comparison");
var detail=StellarDetail.Read(directory,frames[0],frames[1]);
check(detail.Stars.Count==3&&detail.Stars.All(s=>s.Selected.Shape!.Ellipticity>.45&&s.Comparison!.Shape!.Ellipticity<.01),"aligned shifted source crops compare the same elongated and round stars");
check(hash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(frames[0].Path)))&&frames[0].Automatic==Verdict.Keep,"source inspection preserves FITS bytes and frame decisions");
frames[1].Override=Verdict.Reject;
check(StellarDetail.Comparison(project,frames[0])==null&&StellarDetail.Read(directory,frames[0],null).Stars.All(s=>s.Comparison==null),"source elongation remains inspectable without a suitable KEEP exposure");
frames[1].Override=null;frames[1].ReferenceId="different";
check(StellarDetail.Comparison(project,frames[0])==null,"unrelated reference alignments are excluded from star comparison");
using var cancel=new CancellationTokenSource();cancel.Cancel();bool cancelled=false;try{StellarDetail.Read(directory,frames[0],null,cancel.Token);}catch(OperationCanceledException){cancelled=true;}
check(cancelled,"source star inspection cancels during read");
frames[0].Modified--;bool refused=false;try{StellarDetail.Read(directory,frames[0],null);}catch(IOException){refused=true;}
check(refused,"changed sources are refused by the elongation inspector");
}
finally{Directory.Delete(directory,true);}
}
}

36
tools/Verify-Preview.ps1 Normal file
View file

@ -0,0 +1,36 @@
param(
[Parameter(Mandatory)][string]$FixtureProject,
[string]$Output='artifacts/preview-verification'
)
$ErrorActionPreference='Stop'
$repository=Split-Path $PSScriptRoot
Set-Location $repository
if (![OperatingSystem]::IsWindows()) { throw 'This diagnostic checks the Windows desktop UI.' }
$fixture=(Resolve-Path -LiteralPath $FixtureProject).Path
if (!(Test-Path -LiteralPath (Join-Path $fixture 'project.json'))) { throw 'Supply a saved project with current analysis and available read-only FITS sources.' }
$destination=[IO.Path]::GetFullPath((Join-Path $repository $Output))
$artifactRoot=[IO.Path]::GetFullPath((Join-Path $repository 'artifacts'))+[IO.Path]::DirectorySeparatorChar
if (!$destination.StartsWith($artifactRoot,[StringComparison]::OrdinalIgnoreCase)) { throw 'Diagnostic output must stay inside workspace artifacts/.' }
if (Test-Path -LiteralPath $destination) { throw 'Choose a fresh output directory to preserve earlier verification results.' }
New-Item -ItemType Directory -Path $destination | Out-Null
Copy-Item -LiteralPath $fixture -Destination (Join-Path $destination 'fixture') -Recurse
New-Item -ItemType Directory -Force artifacts/test-temp, .tools/http-cache | Out-Null
$env:TEMP=Join-Path $repository 'artifacts/test-temp'
$env:TMP=$env:TEMP
$env:NUGET_HTTP_CACHE_PATH=Join-Path $repository '.tools/http-cache'
$env:AVALONIA_TELEMETRY_OPTOUT='1'
$env:DOTNET_ROOT=Join-Path $repository '.tools/dotnet'
$application=Join-Path $repository 'src/AstroFrame.Desktop/bin/Release/net8.0/AstroFrame.Desktop.exe'
if (!(Test-Path -LiteralPath $application)) { throw 'Build the source with ./Build.ps1 first.' }
$report=Join-Path $destination 'qa'
New-Item -ItemType Directory -Path $report | Out-Null
$process=Start-Process -FilePath $application -ArgumentList @('--verify-ui',('"'+(Join-Path $destination 'fixture')+'"'),('"'+$report+'"')) -WindowStyle Hidden -PassThru
if (!$process.WaitForExit(30000)) { Stop-Process -Id $process.Id -Force; throw 'Source desktop verification timed out.' }
if ($process.ExitCode -ne 0) {
$errorReport=Join-Path $report 'error.txt'
if (Test-Path -LiteralPath $errorReport) { Get-Content -LiteralPath $errorReport }
throw "Source desktop verification failed (exit $($process.ExitCode))."
}
Get-Content -LiteralPath (Join-Path $report 'interaction-checks.txt')
Get-Content -LiteralPath (Join-Path $report 'smoke-checks.txt')
Write-Host "Rendered preview, processing status and elongation captures: $report"