Compare commits
10 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c0ef081e4d | |||
| ef7805055c | |||
| d8923ea85d | |||
| b8ffe97c46 | |||
| d3362c8341 | |||
| 5ad7a6a79e | |||
| 65ded0b606 | |||
| a8e7a87b94 | |||
| 6b56c0b122 | |||
| 1e8e8c88fe |
52 changed files with 1839 additions and 189 deletions
114
AGENTS.md
Normal file
114
AGENTS.md
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
# AstroFrame agent instructions
|
||||||
|
|
||||||
|
Always ask clarifying questions before proceeding when you need more information.
|
||||||
|
|
||||||
|
## Scope and installed-app protection
|
||||||
|
|
||||||
|
- Work on the source code and workspace artifacts. The user explicitly requires that development and release verification leave their locally installed AstroFrame untouched.
|
||||||
|
- Do not run installers or uninstallers, launch the installed application, apply an update to it, or change its installed files, preferences, registry entries, Start Menu shortcuts, or taskbar pins. Earlier installer testing removed the user's installation and shortcuts.
|
||||||
|
- Do not run packaged `--verify-update ... --apply` probes against the user's installation. Use fake update locators and workspace fixtures for update tests. Any installed-app interaction needs explicit new user authorization.
|
||||||
|
- Keep test output and disposable tools under `artifacts/` and `.tools/`. For preview QA, copy saved-project caches into a workspace test folder before rendering; read source exposures without modifying them.
|
||||||
|
- Publish only when a release is requested or included in the authorized task. Documentation-only changes do not need a version bump or release tag.
|
||||||
|
|
||||||
|
## Repository and version source
|
||||||
|
|
||||||
|
- Public Forgejo repository: <https://git.elijahkuntz.com/Elijah/AstroFrame>.
|
||||||
|
- Main development branch: `main`. Use the configured `origin`; inspect it rather than replacing its URL.
|
||||||
|
- `Directory.Build.props` contains the application version. `packaging/Set-Version.ps1` updates that value; it does not commit, tag, or push.
|
||||||
|
- At the time these instructions were added, `1.0.2` was published successfully. Read the current props, tags, and published releases before choosing the next version; do not assume this baseline stays current.
|
||||||
|
- Use a new stable `major.minor.patch` version without leading zeros and an exactly matching `v<version>` tag. Never overwrite a published version, its assets, or its tag. The initial `v1.0.0` tag is unpublished from a failed run; `1.0.1` was the first published release.
|
||||||
|
- Put release notes in `docs/release-notes/<version>.md`. The publisher uses this file as the release description, with a generic fallback if absent.
|
||||||
|
|
||||||
|
### Version numbering
|
||||||
|
|
||||||
|
- Use `major.minor.patch` according to the scope of the release, rather than counting commits.
|
||||||
|
- Increment the patch component (`1.1.x`) for singular or minor changes, fixes, and focused improvements.
|
||||||
|
- Increment the minor component (`1.x.1`) for major fixes, major features, or extensive changes within a bounded part of the program.
|
||||||
|
- Increment the major component (`x.1.1`) for entire-program overhauls, extensive changes impacting much of the program, or codebase rewrites.
|
||||||
|
- The examples identify the component to increment. Normally reset lower components to zero when incrementing a higher component; an explicitly requested version takes precedence. This focused algorithm correction is requested as `1.1.1`.
|
||||||
|
|
||||||
|
## Build and validation
|
||||||
|
|
||||||
|
AstroFrame is an Avalonia/.NET 8 application, published self-contained for `win-x64` and `linux-x64`. Windows uses a per-user Velopack installer; Linux uses an AppImage and optional per-user menu installer, targeting Debian and Arch. ARM is not currently required. Packages are currently unsigned.
|
||||||
|
|
||||||
|
Use PowerShell 7 for packaging and publication. Velopack CLI and application integration are pinned to `1.2.161`; its CLI requires a .NET 10 SDK/runtime. Tests require the .NET 8 runtime. Keep those versions compatible when changing dependencies.
|
||||||
|
|
||||||
|
From the repository root, keep temporary files, NuGet HTTP cache, and telemetry handling within the development scope:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
New-Item -ItemType Directory -Force artifacts/test-temp, .tools/http-cache | Out-Null
|
||||||
|
$env:TEMP = Join-Path $PWD 'artifacts/test-temp'
|
||||||
|
$env:TMP = $env:TEMP
|
||||||
|
$env:NUGET_HTTP_CACHE_PATH = Join-Path $PWD '.tools/http-cache'
|
||||||
|
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
|
||||||
|
./Build.ps1 -Test
|
||||||
|
./tools/Verify-ReleaseAutomation.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
Set the temporary environment before starting test processes. `Build.ps1` also sets workspace .NET home and NuGet package directories. It prefers `.tools/dotnet/dotnet.exe` on Windows when available, otherwise `dotnet` on PATH.
|
||||||
|
|
||||||
|
- `Build.ps1 -Test` builds and runs engine and updater validation. `Verify-ReleaseAutomation.ps1` tests the publisher with a mocked API and does not publish a release.
|
||||||
|
- Render affected controls for visual changes and inspect the result; build/test success alone does not validate an overlay or layout. Use isolated source rendering that does not initialize the installed app's settings or updater.
|
||||||
|
- `Build.ps1 -Publish` means local `dotnet publish` into `artifacts/AstroFrame`; it does **not** publish a Forgejo release. `Build.ps1 -Package` invokes package creation.
|
||||||
|
- For optional local packages, use `./packaging/Release.ps1 -Platform Both`. Outputs default to `artifacts/releases/win-x64` and `artifacts/releases/linux-x64`. Existing versioned publish folders are rejected to prevent stale files. Use fresh `-PublishRoot` and `-Output` workspace paths for a rebuild.
|
||||||
|
- Linux packaging needs `mksquashfs` from `squashfs-tools`. `packaging/release.sh <version>` is the Linux-only alternative. Normal release packaging happens on the server, so a local installer build is not necessary.
|
||||||
|
|
||||||
|
## Preferred release workflow: server build and publish
|
||||||
|
|
||||||
|
Finish the change, verify it, and prepare release notes before pushing a release tag. Include all intended changes in the release commit, preserving unrelated user work. The publisher requires a clean checkout whose HEAD exists on the remote.
|
||||||
|
|
||||||
|
Example for the next release after the recorded baseline; substitute the actual new version:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
./packaging/Set-Version.ps1 -Version 1.0.3
|
||||||
|
# Create docs/release-notes/1.0.3.md and stage all intended source/test changes too.
|
||||||
|
git add Directory.Build.props docs/release-notes/1.0.3.md
|
||||||
|
git commit -m "Release 1.0.3"
|
||||||
|
git push origin main
|
||||||
|
git tag v1.0.3
|
||||||
|
git push origin v1.0.3
|
||||||
|
```
|
||||||
|
|
||||||
|
Run validation on the final versioned source before committing/tagging. Stage intended source/test files explicitly in addition to the two example files. Push the source commit before its tag. The tag must point at the committed source whose version matches it.
|
||||||
|
|
||||||
|
`.forgejo/workflows/release.yml` handles the rest:
|
||||||
|
|
||||||
|
1. A push to `main` builds and tests both platforms without publishing.
|
||||||
|
2. A push of `v<version>` builds, tests, and publishes that version. A manual workflow run on `main` is build-only; a manual run on a version tag publishes.
|
||||||
|
3. `packaging/Build-ServerRelease.ps1` checks the ref/version match, runs engine/updater/publisher validation, and cross-packages both platforms into `artifacts/server-release/packages`.
|
||||||
|
4. The job renders the packaged Linux settings page under Xvfb, using AppImage extraction mode.
|
||||||
|
5. `packaging/Publish.ps1 -Directory artifacts/server-release/packages -Publish -RequireTag` validates both channels, creates a draft, uploads all assets, and makes the release public only after every upload succeeds.
|
||||||
|
|
||||||
|
Known runner requirements that previously caused failures:
|
||||||
|
|
||||||
|
- Runner name: `unraid-runner`; advertised label: `ubuntu-latest`. `runs-on` selects the **label**, not the runner name. The `docker` label did not match this runner.
|
||||||
|
- Job container: `node:22-bookworm`. This Linux runner can create both the Windows Setup executable and Linux AppImage using Velopack cross-packaging.
|
||||||
|
- Checkout is pinned to `https://data.forgejo.org/actions/checkout@v4.4.0`. Runner v6.4.0 supports Node 20 actions; checkout v6 requires Node 24 and failed. Check runner compatibility before upgrading actions.
|
||||||
|
- The workflow installs the .NET 10 SDK, .NET 8 runtime, PowerShell 7.4.20, `squashfs-tools`, and Linux desktop/Xvfb dependencies. Preserve these prerequisites.
|
||||||
|
- The publisher uses Forgejo's repository-scoped `${{ github.token }}` as `ASTROFRAME_RELEASE_TOKEN`; no personal token is needed for the server workflow.
|
||||||
|
- Server Linux smoke tests do not establish Windows UI acceptance or separate Arch/Debian desktop acceptance. Report validation accurately and respect the installed-app protection rule.
|
||||||
|
|
||||||
|
## Assets required for automatic updates
|
||||||
|
|
||||||
|
Installed applications use Velopack's public Gitea release source, with separate `win-x64` and `linux-x64` channels. They check published stable releases, not Git commits, and never pull source code or need a Git client. No repository write token belongs in the application.
|
||||||
|
|
||||||
|
Each public release must include **both** platforms. Uploading only an installer breaks the automatic-update workflow. Normal builds produce 13 assets:
|
||||||
|
|
||||||
|
- For each channel: `releases.<channel>.json`, `RELEASES-<channel>`, `assets.<channel>.json`, and `AstroFrame-<version>-<channel>-full.nupkg`.
|
||||||
|
- Windows: `AstroFrame-win-x64-Setup.exe`.
|
||||||
|
- Linux: `AstroFrame-linux-x64.AppImage`, `install-linux.sh`, `astroframe.png`, and `AstroFrame-<version>-linux-x64.zip`.
|
||||||
|
- Include any generated delta packages referenced by the feed. Full packages support updates from older versions without deltas. Keep older published releases available.
|
||||||
|
|
||||||
|
After pushing the tag, check the **tagged** Actions run through successful publication, then verify the public release is stable, not a draft, contains both channels and expected assets, and both feeds reference the new full package with matching size/checksum. A green `main` build is not proof of publication. Inspect the public API/assets or use an isolated fake locator; do not update the user's installed copy as a test.
|
||||||
|
|
||||||
|
The agreed user experience is: check on launch and every six hours, notify when a newer stable release exists, then download/install/restart only when the user clicks **Install update and restart**. Settings shows version/status, automatic-check preference, and manual check. Installation is blocked during processing or saving and saves the project before restart. Source-tree builds are not self-updating. Preserve this behavior when modifying updates.
|
||||||
|
|
||||||
|
## Publisher recovery and local fallback
|
||||||
|
|
||||||
|
- `packaging/Publish.ps1` verifies version, clean source, remote commit, matching tag when required, package sizes, and SHA256 before publication. The correct commit API route is `/api/v1/repos/Elijah/AstroFrame/git/commits/<sha>`; `/commits/<sha>` returned 404.
|
||||||
|
- A failed upload leaves a draft, invisible to installed apps. Resuming is safe only with identical package bytes; existing uploads are downloaded and compared by SHA256. A fresh rebuild may differ and cause a conflict.
|
||||||
|
- Do not delete published releases or force-move tags to fix publication. Ask before deleting conflicting draft assets/releases or moving an unpublished tag; prefer a new version when requested by the user.
|
||||||
|
- Local fallback: supply a repository-write token through the process environment as `ASTROFRAME_RELEASE_TOKEN`, then run `./packaging/Publish.ps1 -Directory <package-root> -RequireTag` to create/resume a draft. Add `-Publish` only when immediate publication is authorized. Use the matching tagged checkout and both channel folders.
|
||||||
|
- Never commit, print, embed, or persist a release token in scripts or application files.
|
||||||
|
|
||||||
|
See [docs/releases.md](docs/releases.md) and the scripts/workflow above for implementation details. Treat those files as the current authority if these instructions become stale, and update this runbook when changing the workflow.
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
<Project>
|
<Project>
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<Version>1.0.1</Version>
|
<Version>1.1.7</Version>
|
||||||
<Authors>Elijah Kuntz</Authors>
|
<Authors>Elijah Kuntz</Authors>
|
||||||
<Product>AstroFrame</Product>
|
<Product>AstroFrame</Product>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
|
||||||
15
README.md
15
README.md
|
|
@ -6,13 +6,13 @@ An independent Windows/Linux desktop application for selecting astrophotography
|
||||||
|
|
||||||
For packaged installations, run `AstroFrame-win-x64-Setup.exe`. Linux users can use `AstroFrame-linux-x64.AppImage` and the accompanying `install-linux.sh` for an application-menu entry. Both target x64 PCs. See [installation and releases](docs/releases.md) for Debian/Arch prerequisites and package-building instructions.
|
For packaged installations, run `AstroFrame-win-x64-Setup.exe`. Linux users can use `AstroFrame-linux-x64.AppImage` and the accompanying `install-linux.sh` for an application-menu entry. Both target x64 PCs. See [installation and releases](docs/releases.md) for Debian/Arch prerequisites and package-building instructions.
|
||||||
|
|
||||||
**Settings → Updates** shows the installed version and update status, with automatic and manual checks. Installed packages check the [public repository releases](https://git.elijahkuntz.com/Elijah/AstroFrame/releases) on startup and every six hours. A newer stable release adds an update indicator to Settings. **Install update and restart** downloads the release package and restarts after saving; active analysis/export must finish first. Preferences and projects survive updates. Git pushes become app updates only after a versioned release and its packages are published.
|
**Settings → Updates** shows the installed version and update status, with automatic and manual checks. Installed packages check the [public repository releases](https://git.elijahkuntz.com/Elijah/AstroFrame/releases) on startup and every six hours. A newer stable release turns Settings cerulean blue and adds an update indicator. **Install update and restart** downloads the release package and restarts after saving; active analysis/export must finish first. Preferences and projects survive updates. Git pushes become app updates only after a versioned release and its packages are published.
|
||||||
|
|
||||||
Open `artifacts/AstroFrame/AstroFrame.Desktop.exe`. This self-contained build does not require Python, a GPU, or a separate .NET installation. Keep the entire application folder together.
|
Open `artifacts/AstroFrame/AstroFrame.Desktop.exe`. This self-contained build does not require Python, a GPU, or a separate .NET installation. Keep the entire application folder together.
|
||||||
|
|
||||||
Windows enforces a **6 GiB process allocation limit** and a **3 GiB managed-heap limit**. Only one desktop instance can run at a time. Analysis uses up to four workers, leaving at least two logical processors unused where available. It rejects images exceeding a 256 MiB per-frame budget and pauses when it cannot leave roughly 25% of physical RAM free (up to 8 GiB). If pressure persists for 20 seconds, completed measurements are saved for resuming. The page file is not counted as available physical RAM. Windows software rendering is used during this release. The larger limit provides headroom; it does not allocate 6 GiB in advance.
|
Analysis scales its memory budget with physical RAM and samples available headroom before admitting each frame. It reserves one quarter of RAM (up to 8 GiB) for the OS and other applications, counts concurrent frame reservations atomically, and stops safely after 20 seconds of sustained pressure once active frames finish. Windows enforces a process ceiling of physical RAM minus that reserve; the old fixed process, heap and per-frame caps have been removed. Per-frame estimates include working buffers and are bounded by half the machine budget, with the existing 100 MP FITS limit retained. Up to 16 workers are selected from CPU capacity, leaving two logical processors unused where possible. Only one ordinary desktop instance runs at a time. The page file is not treated as available physical RAM. Windows uses software rendering.
|
||||||
|
|
||||||
`Open Sample Survey.cmd` opens all supplied datasets, including NGC 7000. `Open NGC 7000.cmd` opens its separate project. Normal launches reopen the last project automatically. Reopening a completed project uses saved measurements. New display caches are generated on demand for older projects without recomputing classifications; subsequent previews use cached linear thumbnails. An explicit project can also be opened with `AstroFrame.Desktop.exe --project "project folder"`.
|
`Open Sample Survey.cmd` opens all supplied datasets, including NGC 7000. `Open NGC 7000.cmd` opens its separate project. Normal launches start with an empty session. Saved projects and decisions remain available when explicitly reopened or when their source folder is selected again. Reopening a completed project uses saved measurements. New display caches are generated on demand for older projects without recomputing classifications; subsequent previews use cached linear thumbnails. An explicit project can also be opened with `AstroFrame.Desktop.exe --project "project folder"`.
|
||||||
|
|
||||||
To analyze another dataset, choose **Analyze lights**, select the folder containing original `.fit`, `.fits`, or `.fts` files, and wait for analysis. Subfolders are included. New projects are saved separately under `%LOCALAPPDATA%/AstroFrame/Projects/` on Windows (the equivalent local application-data location on Linux). The input folder is not used for project storage.
|
To analyze another dataset, choose **Analyze lights**, select the folder containing original `.fit`, `.fits`, or `.fts` files, and wait for analysis. Subfolders are included. New projects are saved separately under `%LOCALAPPDATA%/AstroFrame/Projects/` on Windows (the equivalent local application-data location on Linux). The input folder is not used for project storage.
|
||||||
|
|
||||||
|
|
@ -22,11 +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.
|
||||||
- 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.
|
||||||
|
|
||||||
|
|
@ -42,7 +43,7 @@ Exports include `accepted.txt` with accepted output paths and `decisions.csv` wi
|
||||||
|
|
||||||
## Build and validate
|
## Build and validate
|
||||||
|
|
||||||
The [server release workflow](.forgejo/workflows/release.yml) builds and publishes both platforms when a stable version tag such as `v1.0.1` is pushed. Set the matching version with `./packaging/Set-Version.ps1 -Version 1.0.1`, commit/push the source, then push the tag. It uses the existing Docker runner and automatically supplied Forgejo token. Pushes and manual Actions runs on `main` check the build without publishing. See [automatic releases](docs/releases.md#automatic-server-releases).
|
The [server release workflow](.forgejo/workflows/release.yml) builds and publishes both platforms when a stable version tag such as `v1.0.3` is pushed. Set the matching version with `./packaging/Set-Version.ps1 -Version 1.0.3`, commit/push the source, then push the tag. It uses the existing Docker runner and automatically supplied Forgejo token. Pushes and manual Actions runs on `main` check the build without publishing. Version 1.0.2 fixes the spatial preview overlay; see [release notes](docs/release-notes/1.0.2.md) and [automatic releases](docs/releases.md#automatic-server-releases).
|
||||||
|
|
||||||
Requires a .NET 8 SDK. `Build.ps1` uses the workspace-local SDK if present, otherwise `dotnet` from PATH:
|
Requires a .NET 8 SDK. `Build.ps1` uses the workspace-local SDK if present, otherwise `dotnet` from PATH:
|
||||||
|
|
||||||
|
|
@ -62,7 +63,7 @@ dotnet publish src/AstroFrame.Desktop -c Release -r linux-x64 --self-contained t
|
||||||
|
|
||||||
The Windows build and rendered layout were tested here. Linux uses Avalonia's X11 backend and bundled Skia/Harfbuzz binaries; packaged Linux startup, settings rendering, installation and self-updates were also exercised under Ubuntu WSL. Debian/Arch desktop acceptance remains to be checked directly. A Linux desktop with the usual X11/font/ICU libraries is required; see [installation and releases](docs/releases.md).
|
The Windows build and rendered layout were tested here. Linux uses Avalonia's X11 backend and bundled Skia/Harfbuzz binaries; packaged Linux startup, settings rendering, installation and self-updates were also exercised under Ubuntu WSL. Debian/Arch desktop acceptance remains to be checked directly. A Linux desktop with the usual X11/font/ICU libraries is required; see [installation and releases](docs/releases.md).
|
||||||
|
|
||||||
Prebuilt Linux files are in `artifacts/AstroFrame-linux`. On Linux, run `chmod +x AstroFrame.Desktop` before launching if executable permissions were lost during transfer. The managed-heap limit and RAM-pressure monitoring also apply on Linux; the Windows kernel job limit does not.
|
Prebuilt Linux files are in `artifacts/AstroFrame-linux`. On Linux, run `chmod +x AstroFrame.Desktop` before launching if executable permissions were lost during transfer. RAM admission and physical headroom monitoring also apply on Linux; the Windows kernel job ceiling does not.
|
||||||
|
|
||||||
Batch analysis and review-label summaries:
|
Batch analysis and review-label summaries:
|
||||||
|
|
||||||
|
|
|
||||||
65
docs/algorithm-1.1.1-validation.md
Normal file
65
docs/algorithm-1.1.1-validation.md
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
# Algorithm comparison for 1.1.1
|
||||||
|
|
||||||
|
Validation performed October 4, 2026. The baseline is the unchanged source at `a8e7a87` (1.1.0), with its validation executable preserved before changing the engine. Both algorithms processed original Sample Data FITS files into separate workspace artifact directories. Source files and the installed application were untouched.
|
||||||
|
|
||||||
|
## Results
|
||||||
|
|
||||||
|
| Session | Frames | 1.1.0 Keep / Review / Reject | 1.1.1 Keep / Review / Reject |
|
||||||
|
|---|---:|---|---|
|
||||||
|
| NGC 1432, September 20 | 490 | 358 / 55 / 77 | **358 / 32 / 100** |
|
||||||
|
| NGC 1432, October 2 | 563 | 547 / 16 / 0 | **547 / 16 / 0** |
|
||||||
|
| NGC 7000, August 17 | 147 | 141 / 6 / 0 | **141 / 6 / 0** |
|
||||||
|
| IC 1805, August 26 | 309 | 301 / 3 / 5 | **301 / 2 / 6** |
|
||||||
|
| Total | 1,509 | 1,347 / 80 / 82 | **1,347 / 56 / 106** |
|
||||||
|
|
||||||
|
All 24 differences are Review → Reject: 23 in the requested NGC 1432 session and one in IC 1805. No Keep or existing Reject changed verdict; no new Keep was introduced. The requested session's review workload falls by 23 frames (41.8%). All four supplied cloud examples now Reject. The two supplied clear-looking morphology examples remain Review because original-source stellar crops show shape differences and the matched-star evidence remains near the practical tolerance.
|
||||||
|
|
||||||
|
## What changed
|
||||||
|
|
||||||
|
- Missing reference stars are distinguished from failed geometry. Tight-match count, residuals and spatial distribution can validate the surviving star field. The nearly opaque example has 164 tight correspondences and a median residual of 0.423 original pixels, despite a detected-star match fraction of only 0.297.
|
||||||
|
- Broad coherent sky anomalies can be corroborated by attenuation measured specifically at reference apertures under positive excess-sky cells. Nearby comparisons use the same apertures, with reference scatter and local sky/background photometry uncertainty. This avoids dilution by unaffected stars or coarse whole-image regions.
|
||||||
|
- Matched bright stars cross-check elongation, with enough nearby reference frames and a conservative effect/uncertainty margin. An initial candidate Keep was not retained after original-source crops showed measurable elongation. The final comparison preserves every prior Keep/Reject membership.
|
||||||
|
- The analysis-version identifier changed, invalidating old automatic measurements while retaining human decisions. Display and binary-cache formats are unchanged; reanalysis generates the new diagnostics.
|
||||||
|
|
||||||
|
## Inspection of the differences
|
||||||
|
|
||||||
|
Every final changed exposure was inspected in source-derived previews and against its measured local attenuation. Each NGC 1432 difference shows a cloud band or patch, including the four supplied examples. A positive cloud structure and a consistent loss in the affected stellar apertures support these rejections. The changed IC 1805 frame (`20260826-012414`) shows cloud entering the lower part of the field; subsequent frames show that cloud moving across the right side. Its affected-aperture flux is approximately 73% of nearby reference flux. Adjacent preceding clear frames preserve the persistent nebula and remain Keep. This is transient cloud evidence rather than the nebula itself being rejected.
|
||||||
|
|
||||||
|
Additional visual controls include nine fixed-time samples in each nebula session, the nine weakest pre-existing NGC 1432 rejects, and the strongest remaining cloud Review frames. NGC 7000 has **zero decision changes across all 147 exposures**. All 301 IC 1805 Keeps and five existing Rejects are unchanged. The second NGC 1432 night also has zero changes across 563 exposures.
|
||||||
|
|
||||||
|
These inspections are an assistant assessment supported by measurements, not independent owner labels for the entire dataset. They support this focused improvement and found no incorrect new rejection in the audited differences. They do not establish a zero-error guarantee on future targets or substitute for controlled stacks. We retain Review where geometry, attenuation, or morphology is uncertain.
|
||||||
|
|
||||||
|
## Regression and release checks
|
||||||
|
|
||||||
|
- The focused regression loop initially failed three checks on the old policy and passes on the new policy: accurate geometry despite star disappearance; broad sky structure with local attenuation; and detection-cohort morphology corroboration.
|
||||||
|
- The full engine suite passes **77 checks**, including persistent nebulosity and gradients, prolonged moving cloud, no stable clear reference, low geometry confidence, insufficient/noisy apertures, measurable elongation, source-safe export, preview independence, and upgrade preservation of human decisions.
|
||||||
|
- A checked-in 46-frame measured fixture preserves four owner cloud examples and two owner-confirmed clear controls, without requiring the original FITS files in CI.
|
||||||
|
- All **9/9 owner-labeled real examples** pass. The **40/40 previously screened cloud-only samples available in these tested sessions** also pass. Those samples were previously used in tuning, so they are not an independent accuracy estimate.
|
||||||
|
- The updater and mocked publisher suites run on the final versioned source before publication. The publisher tests do not publish or interact with the installed app.
|
||||||
|
|
||||||
|
## Additional spatial and trail experiments
|
||||||
|
|
||||||
|
The three suggested topics were evaluated before publication. They are promising directions, but the tested prototypes did not establish a further safe verdict improvement, so they are not additional production rejection rules in 1.1.1.
|
||||||
|
|
||||||
|
**Cloud-scale smoothing and multiple scales.** All 1,509 cached aligned sky maps were evaluated at the existing cell scale and with 3×3 and 7×7 box filters. Each scale used scatter measured from equally filtered clear-reference residuals, retaining the original noise floor and overlap mask; uncertainty was not reduced by assuming neighboring cells were independent. These are bounded box-filter experiments, not an exhaustive evaluation of Gaussian, wavelet, or adaptive filters. The existing significance, coverage and connected-area gates were applied for comparison.
|
||||||
|
|
||||||
|
- No previously nonsuspicious Keep acquired a cloud candidate at either added scale.
|
||||||
|
- A 3×3 filter reduced suspicious sky Review candidates from 15 to 14 in NGC 1432, without introducing a new candidate; the removed candidate is from the otherwise unchanged October night.
|
||||||
|
- A 7×7 filter reduced NGC 1432 candidates from 15 to 11, and IC 1805 Review candidates from two to one. It also removed the sky-candidate gate from two existing IC 1805 Rejects (`20260826-012650` and `20260826-012721`), whose source-derived previews show cloud entering at the edge. Their affected-aperture flux ratios are approximately 60% and 59%.
|
||||||
|
- Requiring agreement at all scales could suppress real partial clouds. Taking their union retained the original candidate membership, giving no additional verified accuracy gain. Connected regions and affected-star corroboration were therefore retained without replacing the fine-scale evidence or promoting smoothed-away warnings to Keep.
|
||||||
|
|
||||||
|
Filtering a background mesh is an established measurement technique, but does not itself establish a safe frame rejection policy; [Photutils Background2D](https://photutils.readthedocs.io/en/latest/api/photutils.background.Background2D.html) documents mesh filtering independently of this classifier.
|
||||||
|
|
||||||
|
**Directional trails.** Original FITS stellar cores were measured for 104 selected exposures: morphology Review frames, nearby representative Keeps, and nine fixed-time Keep controls in each target. The exploratory measurement reused positive core moments, excluded detected close neighbors within ten superpixels, and computed the ellipticity-weighted double-angle resultant for isolated stars with ellipticity at least 0.15. This measures directional consistency from zero to one; it is not a calibrated PSF fit or an independent tracking-error label.
|
||||||
|
|
||||||
|
The median resultant was 0.987 for 33 NGC 1432 Reviews versus 0.874 for 41 Keeps, and 0.963 for six NGC 7000 Reviews versus 0.653 for 15 Keeps. However, nine IC 1805 Keep controls already had a median resultant of 0.930 and median isolated-star ellipticity of 0.280. Thus a high directional consistency alone does not distinguish tracking failure from the session's normal optics/sampling. The Reviews are already captured by elongation; there are no independently labeled trail acceptance boundaries in these samples to justify automatically discarding them. A future rule should compare matched-star shape tensors after accounting for frame rotation, spatial optical patterns, sampling and fit uncertainty, then validate against explicit acceptable/unacceptable tracking labels. This release retains conservative matched-star elongation corroboration and Review for unresolved shape changes.
|
||||||
|
|
||||||
|
[Siril's Dynamic PSF documentation](https://siril.readthedocs.io/en/latest/Dynamic-PSF.html) describes rotation-angle fitting and notes that elliptical stars can arise from optical aberrations, tracking, or blended stars. Its fitted Gaussian/Moffat profiles are more sophisticated than AstroFrame's core moments; we do not claim identical measurement accuracy or that the suggested cloud classifier is documented as a Siril feature.
|
||||||
|
|
||||||
|
Workspace experiment sources/results are `SpatialTopics.cs`, `spatial-topics.json`, `DirectionTopics.cs`, and `direction-topics.json` under `artifacts/algorithm-1.1.1/`; `smoothed-loss-1.png` contains the seven sky-candidate losses at the largest scale. These research experiments do not modify production measurements, the source FITS files, or the comparison verdicts above.
|
||||||
|
|
||||||
|
## Reproduction and artifacts
|
||||||
|
|
||||||
|
Baseline/new analysis uses the validation executable's `analyze <source> <output> --fresh` mode, with temporary/cache environment variables confined to the workspace as prescribed in AGENTS.md. The baseline executable is preserved at `artifacts/algorithm-1.1.1/baseline-cli/`; baseline and final projects, catalog caches, previews, manifests and reports are under `baseline-*` and `new-*` sibling folders. Final policy refinements reused identical stellar/sky/aperture measurements and rebuilt their reference diagnostics. All 1,509 source size/modification-time fingerprints remain unchanged.
|
||||||
|
|
||||||
|
`artifacts/algorithm-1.1.1/comparison.json` records the full per-exposure differences. `changes-1.png` through `changes-3.png` show every final changed frame; `nebula-controls-*.png` and `nebula-cloud-transition-1.png` show the nebula controls and the IC 1805 transition. `keep-stars.png` documents why the exploratory new Keep was retained as Review in the final policy. Compact session counts and per-change measurements are checked in as [quality-1.1.1-validation.json](diagnostics/quality-1.1.1-validation.json).
|
||||||
|
|
@ -6,6 +6,8 @@ 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. 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
|
||||||
|
|
||||||
- **Engine:** FITS reader, independent `IFrameDetector` measurements, background reference construction, aperture photometry, named decision rules, persistence and export. No GUI, Python runtime, AI or GPU dependency.
|
- **Engine:** FITS reader, independent `IFrameDetector` measurements, background reference construction, aperture photometry, named decision rules, persistence and export. No GUI, Python runtime, AI or GPU dependency.
|
||||||
|
|
@ -22,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.
|
||||||
|
|
||||||
|
|
@ -33,26 +36,36 @@ 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.
|
||||||
|
- 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 rejection also requires reliable matching/aperture measurements. Ambiguous structure, moderate flux loss, substantial single-metric morphology changes and uncertain measurements route to REVIEW. Minor ellipticity fluctuations and a high global background alone do not trigger 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.
|
||||||
|
|
||||||
|
An existing elongation flag can be dismissed only when at least 50 matched bright reference stars and 12 nearby reference frames provide a precise, small shape change. Its median change plus three estimated standard errors must be below 0.10, and the uncertainty must not exceed 0.025. Missing pairs cannot dismiss a warning. Matched stars use the same reference identities rather than independently selected detection populations. This remains moment-based photometry, not a new PSF-fitting implementation. Ambiguous structure, moderate flux loss, substantial single-metric morphology changes and uncertain measurements route to REVIEW. Minor ellipticity fluctuations and a high global background alone do not trigger review.
|
||||||
|
|
||||||
These significance and effect-size limits are **engineering policy, not calibrated probabilities or guarantees**. Reference scatter, noise, star population, flux, seeing and background are measured separately per session. No fixed acceptable star count or absolute sky brightness is used. The score exists only for sorting.
|
These significance and effect-size limits are **engineering policy, not calibrated probabilities or guarantees**. Reference scatter, noise, star population, flux, seeing and background are measured separately per session. No fixed acceptable star count or absolute sky brightness is used. The score exists only for sorting.
|
||||||
|
|
||||||
## 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.
|
||||||
|
|
||||||
## Memory, caching and safety
|
## Memory, caching and safety
|
||||||
|
|
||||||
Up to four workers are now selected automatically, leaving two logical processors unused where possible. A 48-frame NGC 7000 measurement benchmark took 9.04/4.99/2.94 seconds with one/two/four workers, with identical star counts and four-worker peak RAM of 250 MiB. This measures the stellar/background stage, not whole-project speedup. No full-resolution image collection or stack is held in RAM. Reference maps are only 960 values per frame. Windows enforces a verified 6 GiB process allocation cap; both executables use a 3 GiB managed-heap cap. A 256 MiB estimated per-frame budget rejects oversized allocations. Analysis checks physical memory before both image passes, reserving up to 8 GiB or one quarter of physical RAM. The page file does not satisfy this reserve. Sustained pressure stops safely and saves measurements.
|
Version 1.1.0 selects up to 16 workers from CPU capacity, leaving two logical processors unused where possible. A 48-frame measurement run on a 16-logical-processor machine took 2.93 seconds with four workers and 1.32 seconds with fourteen, with identical star counts (peak working sets 251 and 762 MiB). This measures stellar/background processing, not whole-project speedup. No full-resolution image collection or stack is held in RAM. Windows uses a verified process ceiling based on physical RAM minus its reserve, rounded to an allocation boundary. Fixed 6 GiB process, 3 GiB heap and 256 MiB frame caps have been removed. Per-frame estimates include a 64 MiB working margin and are limited to half the machine budget. Both image passes, previews and star detail acquire atomic memory reservations, sampling physical headroom for every frame. The OS/desktop reserve remains one quarter of RAM up to 8 GiB; page-file capacity does not satisfy it. Sustained external pressure stops safely after active frames finish and saves completed measurements.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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.
|
||||||
|
|
||||||
|
|
|
||||||
360
docs/diagnostics/quality-1.1.1-validation.json
Normal file
360
docs/diagnostics/quality-1.1.1-validation.json
Normal file
|
|
@ -0,0 +1,360 @@
|
||||||
|
{
|
||||||
|
"date": "2026-10-04",
|
||||||
|
"baselineCommit": "a8e7a87b94d0f8046209e9c937bd83bf4b811f10",
|
||||||
|
"baselineEngine": "0.2.0-spatial-reference-1",
|
||||||
|
"newEngine": "0.2.1-spatial-reference-2",
|
||||||
|
"sessions": [
|
||||||
|
{
|
||||||
|
"session": "NGC 1432 \u00b7 2026-09-20 06:50 \u00b7 1 \u00b7 IRCUT",
|
||||||
|
"frames": 490,
|
||||||
|
"old": {
|
||||||
|
"Keep": 358,
|
||||||
|
"Review": 55,
|
||||||
|
"Reject": 77
|
||||||
|
},
|
||||||
|
"new": {
|
||||||
|
"Keep": 358,
|
||||||
|
"Review": 32,
|
||||||
|
"Reject": 100
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"session": "NGC 1432 \u00b7 2026-10-02 06:00 \u00b7 2 \u00b7 IRCUT",
|
||||||
|
"frames": 563,
|
||||||
|
"old": {
|
||||||
|
"Keep": 547,
|
||||||
|
"Review": 16,
|
||||||
|
"Reject": 0
|
||||||
|
},
|
||||||
|
"new": {
|
||||||
|
"Keep": 547,
|
||||||
|
"Review": 16,
|
||||||
|
"Reject": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"session": "NGC 7000 \u00b7 2026-08-17 04:33 \u00b7 1 \u00b7 LP",
|
||||||
|
"frames": 147,
|
||||||
|
"old": {
|
||||||
|
"Keep": 141,
|
||||||
|
"Review": 6,
|
||||||
|
"Reject": 0
|
||||||
|
},
|
||||||
|
"new": {
|
||||||
|
"Keep": 141,
|
||||||
|
"Review": 6,
|
||||||
|
"Reject": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"session": "IC 1805 \u00b7 2026-08-26 08:00 \u00b7 1 \u00b7 LP",
|
||||||
|
"frames": 309,
|
||||||
|
"old": {
|
||||||
|
"Keep": 301,
|
||||||
|
"Review": 3,
|
||||||
|
"Reject": 5
|
||||||
|
},
|
||||||
|
"new": {
|
||||||
|
"Keep": 301,
|
||||||
|
"Review": 2,
|
||||||
|
"Reject": 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"changes": [
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260919-235506.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 21.93785621095097,
|
||||||
|
"affectedFluxRatio": 0.8636848120909967,
|
||||||
|
"affectedFluxDeviation": 4.543839596966776,
|
||||||
|
"alignmentMedianPixels": 0.2631228145939164,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260919-235537.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 14.205363402591354,
|
||||||
|
"affectedFluxRatio": 0.8845403044429598,
|
||||||
|
"affectedFluxDeviation": 3.848656518568007,
|
||||||
|
"alignmentMedianPixels": 0.25334731221934753,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260919-235608.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 19.304613846485182,
|
||||||
|
"affectedFluxRatio": 0.8423382721761337,
|
||||||
|
"affectedFluxDeviation": 5.255390927462213,
|
||||||
|
"alignmentMedianPixels": 0.25116491416396974,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-000300.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 21.99244300903803,
|
||||||
|
"affectedFluxRatio": 0.83036711072136,
|
||||||
|
"affectedFluxDeviation": 5.6544296426213325,
|
||||||
|
"alignmentMedianPixels": 0.23723050615616165,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-000331.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 18.008937347417586,
|
||||||
|
"affectedFluxRatio": 0.8425858408547843,
|
||||||
|
"affectedFluxDeviation": 5.247138638173857,
|
||||||
|
"alignmentMedianPixels": 0.23176112388221165,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-001125.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 8.238866042072468,
|
||||||
|
"affectedFluxRatio": 0.8453711916213303,
|
||||||
|
"affectedFluxDeviation": 5.154293612622321,
|
||||||
|
"alignmentMedianPixels": 0.2004272687660229,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-001156.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 14.060493454157665,
|
||||||
|
"affectedFluxRatio": 0.873622460980021,
|
||||||
|
"affectedFluxDeviation": 4.2125846339993,
|
||||||
|
"alignmentMedianPixels": 0.21057367839555907,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-002817.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 19.741168661451677,
|
||||||
|
"affectedFluxRatio": 0.8912902562183401,
|
||||||
|
"affectedFluxDeviation": 3.6236581260553278,
|
||||||
|
"alignmentMedianPixels": 0.18335484479463354,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-003713.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 231.33479320777224,
|
||||||
|
"affectedFluxRatio": 0.039192529060025114,
|
||||||
|
"affectedFluxDeviation": 32.026915697999165,
|
||||||
|
"alignmentMedianPixels": 0.4229262918099691,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-004304.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 15.49719600393806,
|
||||||
|
"affectedFluxRatio": 0.8461550650098837,
|
||||||
|
"affectedFluxDeviation": 5.128164499670544,
|
||||||
|
"alignmentMedianPixels": 0.16358180745346368,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-004624.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 15.391777248244273,
|
||||||
|
"affectedFluxRatio": 0.8897937985360267,
|
||||||
|
"affectedFluxDeviation": 3.6735400487991123,
|
||||||
|
"alignmentMedianPixels": 0.17600984075984275,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-004726.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 18.57963411527099,
|
||||||
|
"affectedFluxRatio": 0.8705488825072726,
|
||||||
|
"affectedFluxDeviation": 4.315037249757581,
|
||||||
|
"alignmentMedianPixels": 0.17524893834549105,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-005235.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 24.15637588387764,
|
||||||
|
"affectedFluxRatio": 0.8709361884911153,
|
||||||
|
"affectedFluxDeviation": 4.302127050296157,
|
||||||
|
"alignmentMedianPixels": 0.14926813111727083,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-005421.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 8.17568631153736,
|
||||||
|
"affectedFluxRatio": 0.8956752750757109,
|
||||||
|
"affectedFluxDeviation": 3.477490830809639,
|
||||||
|
"alignmentMedianPixels": 0.14261613075981966,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-010318.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 13.187685772318256,
|
||||||
|
"affectedFluxRatio": 0.8887345385372606,
|
||||||
|
"affectedFluxDeviation": 3.708848715424648,
|
||||||
|
"alignmentMedianPixels": 0.16306293375502223,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-011113.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 18.169921576052825,
|
||||||
|
"affectedFluxRatio": 0.8396524330778192,
|
||||||
|
"affectedFluxDeviation": 5.344918897406026,
|
||||||
|
"alignmentMedianPixels": 0.16379873442258716,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-012632.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 19.52391631691044,
|
||||||
|
"affectedFluxRatio": 0.8490009027116143,
|
||||||
|
"affectedFluxDeviation": 5.033303242946189,
|
||||||
|
"alignmentMedianPixels": 0.12881799374449404,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-012818.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 17.723635511036186,
|
||||||
|
"affectedFluxRatio": 0.8455906425280958,
|
||||||
|
"affectedFluxDeviation": 5.146978582396807,
|
||||||
|
"alignmentMedianPixels": 0.15677678144061136,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-013137.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 10.824700198303587,
|
||||||
|
"affectedFluxRatio": 0.8297659241686153,
|
||||||
|
"affectedFluxDeviation": 5.674469194379491,
|
||||||
|
"alignmentMedianPixels": 0.13213426121083371,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-013310.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 9.551977498073267,
|
||||||
|
"affectedFluxRatio": 0.8809177425716295,
|
||||||
|
"affectedFluxDeviation": 3.969408580945685,
|
||||||
|
"alignmentMedianPixels": 0.137763541386481,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-013746.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 19.91122796256937,
|
||||||
|
"affectedFluxRatio": 0.7445523676711074,
|
||||||
|
"affectedFluxDeviation": 8.51492107762975,
|
||||||
|
"alignmentMedianPixels": 0.13331108959050958,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-013817.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 21.69705495844935,
|
||||||
|
"affectedFluxRatio": 0.8457382705969594,
|
||||||
|
"affectedFluxDeviation": 5.14205764676802,
|
||||||
|
"alignmentMedianPixels": 0.16633085057987979,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_NGC 1432_30.0s_IRCUT_20260920-023920.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 13.414930894720293,
|
||||||
|
"affectedFluxRatio": 0.867893857149813,
|
||||||
|
"affectedFluxDeviation": 4.403538095006232,
|
||||||
|
"alignmentMedianPixels": 0.1296821468757567,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "Light_IC 1805_30.0s_LP_20260826-012414.fit",
|
||||||
|
"before": "Review",
|
||||||
|
"after": "Reject",
|
||||||
|
"skySignificance": 9.482428788618922,
|
||||||
|
"affectedFluxRatio": 0.7321572057985136,
|
||||||
|
"affectedFluxDeviation": 7.7859449008662605,
|
||||||
|
"alignmentMedianPixels": 0.34200350430379745,
|
||||||
|
"visualAssessment": "Transient cloud structure corroborated by affected-aperture attenuation"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"ownerExamples": {
|
||||||
|
"passes": 9,
|
||||||
|
"total": 9
|
||||||
|
},
|
||||||
|
"previouslyScreenedExamples": {
|
||||||
|
"passes": 40,
|
||||||
|
"total": 40,
|
||||||
|
"independent": false
|
||||||
|
},
|
||||||
|
"newKeeps": 0,
|
||||||
|
"keepToReject": 0,
|
||||||
|
"rejectToKeep": 0,
|
||||||
|
"sourceFingerprints": 1509,
|
||||||
|
"limitation": "Assistant inspection of all differences; no independently owner-labeled full session or controlled stack comparison.",
|
||||||
|
"checks": {
|
||||||
|
"engine": 77,
|
||||||
|
"updater": 23,
|
||||||
|
"mockedPublisher": 10
|
||||||
|
},
|
||||||
|
"additionalExperiments": {
|
||||||
|
"productionRulesAdded": false,
|
||||||
|
"spatial": {
|
||||||
|
"frames": 1509,
|
||||||
|
"cellScales": [
|
||||||
|
1,
|
||||||
|
3,
|
||||||
|
7
|
||||||
|
],
|
||||||
|
"newKeepCloudCandidates": 0,
|
||||||
|
"ngc1432SkyReviewCandidates": [
|
||||||
|
15,
|
||||||
|
14,
|
||||||
|
11
|
||||||
|
],
|
||||||
|
"ic1805SkyReviewCandidates": [
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"ic1805ExistingRejectSkyCandidatesLostAtLargestScale": 2,
|
||||||
|
"decision": "Retain existing connected-cell evidence; smoothing did not establish additional safe verdict improvements."
|
||||||
|
},
|
||||||
|
"directional": {
|
||||||
|
"frames": 104,
|
||||||
|
"coherenceMedian": {
|
||||||
|
"ngc1432Review": 0.987,
|
||||||
|
"ngc1432Keep": 0.874,
|
||||||
|
"ngc7000Review": 0.963,
|
||||||
|
"ngc7000Keep": 0.653,
|
||||||
|
"ic1805Keep": 0.93
|
||||||
|
},
|
||||||
|
"decision": "Retain morphology review and matched-star corroboration; high coherence also exists in normal controls and trail acceptance labels are unavailable."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
9
docs/release-notes/1.0.2.md
Normal file
9
docs/release-notes/1.0.2.md
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
AstroFrame 1.0.2 fixes the spatial preview overlay.
|
||||||
|
|
||||||
|
- Pink now highlights positive sky structure relative to the clean session reference, rather than both brighter and darker differences.
|
||||||
|
- A cloud-resistant background fit removes offset and gradient without creating false highlights in clear corners.
|
||||||
|
- Strong and moderately bright cloud patches remain visible; weak background residuals are excluded.
|
||||||
|
- A legend explains the pink fill and the regional stellar-flux grid.
|
||||||
|
- Existing projects reconstruct the corrected display from cached measurements without requiring a full reanalysis. Classification metrics, decisions, notes and source images are preserved.
|
||||||
|
|
||||||
|
Verified on the reported NGC 1432 exposures ending in 235115, 235146 and 235248, with regressions for visible cloud cores, dark comparison regions and read-only project reconstruction.
|
||||||
9
docs/release-notes/1.1.0.md
Normal file
9
docs/release-notes/1.1.0.md
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
# AstroFrame 1.1.0
|
||||||
|
|
||||||
|
- Processing uses more available RAM and CPU capacity. Fixed memory caps have been replaced with a physical-RAM budget and atomic reservations for concurrent frames, retaining headroom for the operating system and other applications. Processing pauses under RAM pressure and preserves completed work if pressure persists.
|
||||||
|
- Scroll over a preview to zoom around the cursor and drag with the left mouse button to pan. Zoom and position carry across frames and the nearby comparison. **Reset view** fits and centers both previews. Overlays follow the transformed image.
|
||||||
|
- Ordinary launches begin with a fresh, empty session. Saved projects and decisions remain on disk; explicit project opening and update restarts still restore the requested project.
|
||||||
|
- **Settings · Update available** turns cerulean blue when an update is available.
|
||||||
|
- The native startup background matches the application's charcoal grey.
|
||||||
|
|
||||||
|
Validation covers engine/resource policy, updater safety, mocked publication, routed mouse events, preview resets and frame switching, rendered layouts at normal and minimum size including 144 DPI, and Windows native window behavior. A 48-frame measurement benchmark on a 16-thread machine improved from 2.93 seconds with four workers to 1.32 seconds with fourteen workers, with identical star counts; this is not a whole-project speed guarantee. Development verification uses workspace fixtures and a fake updater, leaving installed copies untouched.
|
||||||
12
docs/release-notes/1.1.1.md
Normal file
12
docs/release-notes/1.1.1.md
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
# AstroFrame 1.1.1
|
||||||
|
|
||||||
|
Improves conservative cloud rejection without promoting uncertain exposures to Keep.
|
||||||
|
|
||||||
|
- Verifies stellar alignment using positional residuals and distributed tight matches, so severe cloud cover does not automatically defeat rejection by hiding reference stars.
|
||||||
|
- Corroborates broad cloud structure with brightness loss measured at the same stars in the affected area, using nearby references and photometry uncertainty.
|
||||||
|
- Cross-checks elongation against matched reference stars; measurable or uncertain shape changes continue to require Review.
|
||||||
|
- Preserves human decisions when reanalysis refreshes the new measurements.
|
||||||
|
|
||||||
|
In the supplied 490-frame NGC 1432 session, Review decreases from 55 to 32 and 23 visibly clouded exposures become Reject. All previous Keeps and Rejects remain unchanged. NGC 7000's 147-frame nebula session is unchanged; IC 1805 changes one cloud-contaminated Review to Reject while preserving every Keep. A second 563-frame NGC 1432 night is unchanged. Every changed decision was inspected; these results support the tested improvement rather than a guarantee for every future dataset.
|
||||||
|
|
||||||
|
Engine, updater and release automation checks pass on the versioned source. Old automatic measurements require reanalysis; manual labels are retained. Windows and Linux update channels are included.
|
||||||
9
docs/release-notes/1.1.2.md
Normal file
9
docs/release-notes/1.1.2.md
Normal 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.
|
||||||
10
docs/release-notes/1.1.3.md
Normal file
10
docs/release-notes/1.1.3.md
Normal 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.
|
||||||
9
docs/release-notes/1.1.4.md
Normal file
9
docs/release-notes/1.1.4.md
Normal 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.
|
||||||
9
docs/release-notes/1.1.5.md
Normal file
9
docs/release-notes/1.1.5.md
Normal 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.
|
||||||
11
docs/release-notes/1.1.6.md
Normal file
11
docs/release-notes/1.1.6.md
Normal 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.
|
||||||
10
docs/release-notes/1.1.7.md
Normal file
10
docs/release-notes/1.1.7.md
Normal 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.
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
## First release
|
## First release
|
||||||
|
|
||||||
Version **1.0.0** targets x64 Windows and Linux desktops. Windows uses a per-user Velopack installer. Linux uses one self-contained AppImage plus an optional per-user application-menu installer; the same binary targets both Debian and Arch. No Git client, Python, .NET runtime installation or administrator access is required to install AstroFrame itself.
|
The first published version, **1.0.1**, targets x64 Windows and Linux desktops. Download it from [the release page](https://git.elijahkuntz.com/Elijah/AstroFrame/releases/tag/v1.0.1). Windows uses a per-user Velopack installer. Linux uses one self-contained AppImage plus an optional per-user application-menu installer; the same binary targets both Debian and Arch. No Git client, Python, .NET runtime installation or administrator access is required to install AstroFrame itself.
|
||||||
|
|
||||||
### Windows
|
### Windows
|
||||||
|
|
||||||
|
|
@ -40,6 +40,8 @@ To uninstall a script-installed Linux copy, close AstroFrame and remove only `~/
|
||||||
|
|
||||||
## Settings and updates
|
## Settings and updates
|
||||||
|
|
||||||
|
Version **1.0.2** corrects the spatial preview overlay. Pink shows the strongest positive sky structure against the clean session reference; the display fit resists bright cloud contamination, and weak background residuals are suppressed. Both bright and moderately bright cloud patches remain visible. The grid shows regional stellar flux. This is supporting evidence rather than an exact cloud boundary. Existing saved projects reconstruct the display from cached catalogs without changing classification metrics or human decisions. See [1.0.2 release notes](release-notes/1.0.2.md).
|
||||||
|
|
||||||
Open **Settings → Updates** for the installed version, update status, last successful check, automatic-check preference, and **Check for updates**. The sidebar and independent settings store leave room for future categories.
|
Open **Settings → Updates** for the installed version, update status, last successful check, automatic-check preference, and **Check for updates**. The sidebar and independent settings store leave room for future categories.
|
||||||
|
|
||||||
Installed packages check on launch and every six hours while running. A persistent **Settings · Update available** indicator appears when a newer stable version is found. **Install update and restart** downloads the update, validates its package checksum, saves the project and restarts. Analysis, export and saving block installation; if work starts during download, the package remains ready for a later restart. Projects and settings survive updates. Failed checks display an error rather than claiming the app is up to date. Source-tree builds explain that installing a package enables updates.
|
Installed packages check on launch and every six hours while running. A persistent **Settings · Update available** indicator appears when a newer stable version is found. **Install update and restart** downloads the update, validates its package checksum, saves the project and restarts. Analysis, export and saving block installation; if work starts during download, the package remains ready for a later restart. Projects and settings survive updates. Failed checks display an error rather than claiming the app is up to date. Source-tree builds explain that installing a package enables updates.
|
||||||
|
|
@ -59,15 +61,15 @@ Once this workflow is committed and pushed, enable Actions for the AstroFrame re
|
||||||
To release a new version:
|
To release a new version:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
./packaging/Set-Version.ps1 -Version 1.0.1
|
./packaging/Set-Version.ps1 -Version 1.0.3
|
||||||
git add Directory.Build.props
|
git add Directory.Build.props
|
||||||
git commit -m "Release 1.0.1"
|
git commit -m "Release 1.0.3"
|
||||||
git push origin main
|
git push origin main
|
||||||
git tag v1.0.1
|
git tag v1.0.3
|
||||||
git push origin v1.0.1
|
git push origin v1.0.3
|
||||||
```
|
```
|
||||||
|
|
||||||
Include all intended source changes in the release commit before tagging. The pushed tag is the publication trigger; ordinary commits to `main` run the build and checks without publishing. The version in `Directory.Build.props` must exactly match the tag. For the first release, use `v1.0.0` after pushing this workflow and the finalized source.
|
Include all intended source changes in the release commit before tagging. The pushed tag is the publication trigger; ordinary commits to `main` run the build and checks without publishing. The version in `Directory.Build.props` must exactly match the tag. Version `v1.0.1` is published; `v1.0.0` remains an unpublished tag from the first failed publishing attempt. Choose a new version for each later release.
|
||||||
|
|
||||||
The job runs the engine, updater and release-publisher validation suites, builds both packages, renders the Linux settings page under Xvfb, then uploads everything into one draft release. Only after all uploads succeed does it make the release public, so users cannot discover an incomplete update. No local installer build or manual asset attachment is needed.
|
The job runs the engine, updater and release-publisher validation suites, builds both packages, renders the Linux settings page under Xvfb, then uploads everything into one draft release. Only after all uploads succeed does it make the release public, so users cannot discover an incomplete update. No local installer build or manual asset attachment is needed.
|
||||||
|
|
||||||
|
|
@ -89,14 +91,14 @@ The Windows script cross-packages both platforms. Results appear in `artifacts/r
|
||||||
On Linux with a .NET 10 SDK:
|
On Linux with a .NET 10 SDK:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
bash packaging/release.sh 1.0.0
|
bash packaging/release.sh 1.0.2
|
||||||
```
|
```
|
||||||
|
|
||||||
That script builds the Linux channel. The tool manifest pins Velopack CLI 1.2.161, matching the application's SDK dependency. Building on Windows is enough to create both packages, but compatibility should still be checked on target Linux desktops.
|
That script builds the Linux channel. The tool manifest pins Velopack CLI 1.2.161, matching the application's SDK dependency. Building on Windows is enough to create both packages, but compatibility should still be checked on target Linux desktops.
|
||||||
|
|
||||||
## Publish to the repository
|
## Publish to the repository
|
||||||
|
|
||||||
Commit and push the versioned source first. The initial release has **not** been uploaded by this implementation. To make update discovery live, create a public stable release tagged `v1.0.0` and attach the files described below.
|
Commit and push the versioned source first. Version `v1.0.1` was built and published automatically by the server. The following local publisher is an alternative to the tag workflow for future versions.
|
||||||
|
|
||||||
The helper script reads a repository-write token from `ASTROFRAME_RELEASE_TOKEN` in the process environment. On the server this is supplied automatically by the workflow. For local publication, set your own Gitea/Forgejo repository-write token. The script uploads both platforms into one draft, including the Linux installation helpers. It does not store the token or embed it in the application:
|
The helper script reads a repository-write token from `ASTROFRAME_RELEASE_TOKEN` in the process environment. On the server this is supplied automatically by the workflow. For local publication, set your own Gitea/Forgejo repository-write token. The script uploads both platforms into one draft, including the Linux installation helpers. It does not store the token or embed it in the application:
|
||||||
|
|
||||||
|
|
@ -119,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:
|
||||||
|
|
@ -129,6 +139,6 @@ dotnet run --project tests/AstroFrame.Updates.Validation -c Release -- artifacts
|
||||||
|
|
||||||
That test feed must contain a **1.0.1** package for the requested channel; it is not a production release. An explicit packaged-app `--verify-update <local feed directory> <report.jsonl> --apply` probe verifies actual replacement and restart. A `--capture-settings <output.png> [width] [dpi]` diagnostic captures the real settings page.
|
That test feed must contain a **1.0.1** package for the requested channel; it is not a production release. An explicit packaged-app `--verify-update <local feed directory> <report.jsonl> --apply` probe verifies actual replacement and restart. A `--capture-settings <output.png> [width] [dpi]` diagnostic captures the real settings page.
|
||||||
|
|
||||||
Both Windows and Linux local 1.0.0 → 1.0.1 replacement/restart were exercised during implementation. Linux rendering and per-user installation were checked under Ubuntu WSL with the missing ICU/X11 libraries extracted into a workspace test directory. Debian and Arch desktop execution have not yet been tested directly; those compatibility targets are based on the cross-platform runtime and documented system dependencies, not separate distro acceptance runs. The public repository API was verified anonymously; it currently contains no published releases.
|
Both Windows and Linux local 1.0.0 → 1.0.1 replacement/restart were exercised during implementation. Linux rendering and per-user installation were checked under Ubuntu WSL with the missing ICU/X11 libraries extracted into a workspace test directory. Debian and Arch desktop execution have not yet been tested directly; those compatibility targets are based on the cross-platform runtime and documented system dependencies, not separate distro acceptance runs. Server run #8 built and published version 1.0.1 with all 13 assets, passed 39 engine, 18 updater and 10 publisher checks, and rendered the packaged Linux settings page under Debian Bookworm. A packaged Linux 1.0.0 app also discovered and downloaded the public 1.0.1 update through the real Gitea source with checksum validation.
|
||||||
|
|
||||||
References: [Velopack C# integration](https://docs.velopack.io/getting-started/csharp), [cross-packaging](https://docs.velopack.io/packaging/cross-compiling), [Linux update behavior](https://docs.velopack.io/packaging/operating-systems/linux), [Gitea distribution](https://docs.velopack.io/distributing/self-hosting), [Avalonia Linux dependencies](https://v11.docs.avaloniaui.net/docs/overview/supported-platforms/).
|
References: [Velopack C# integration](https://docs.velopack.io/getting-started/csharp), [cross-packaging](https://docs.velopack.io/packaging/cross-compiling), [Linux update behavior](https://docs.velopack.io/packaging/operating-systems/linux), [Gitea distribution](https://docs.velopack.io/distributing/self-hosting), [Avalonia Linux dependencies](https://v11.docs.avaloniaui.net/docs/overview/supported-platforms/).
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,9 @@ try { $release = Invoke-RestMethod "$api/releases/tags/$tag" -Headers $headers }
|
||||||
catch { if ([int]$_.Exception.Response.StatusCode -ne 404) { throw } }
|
catch { if ([int]$_.Exception.Response.StatusCode -ne 404) { throw } }
|
||||||
if ($release -and !$release.draft) { throw "$tag is already published. Release assets are immutable; build a new version." }
|
if ($release -and !$release.draft) { throw "$tag is already published. Release assets are immutable; build a new version." }
|
||||||
if (!$release) {
|
if (!$release) {
|
||||||
$body = @{ tag_name=$tag; target_commitish=$commit; name="AstroFrame $Version"; body="AstroFrame $Version for Windows and Linux. See the repository README for installation and update instructions."; draft=$true; prerelease=$false } | ConvertTo-Json
|
$notesPath = Join-Path 'docs/release-notes' "$Version.md"
|
||||||
|
$notes = if (Test-Path -LiteralPath $notesPath) { Get-Content -LiteralPath $notesPath -Raw } else { "AstroFrame $Version for Windows and Linux. See the repository README for installation and update instructions." }
|
||||||
|
$body = @{ tag_name=$tag; target_commitish=$commit; name="AstroFrame $Version"; body=$notes; draft=$true; prerelease=$false } | ConvertTo-Json
|
||||||
$release = Invoke-RestMethod "$api/releases" -Method Post -Headers $headers -ContentType 'application/json' -Body $body
|
$release = Invoke-RestMethod "$api/releases" -Method Post -Headers $headers -ContentType 'application/json' -Body $body
|
||||||
}
|
}
|
||||||
$attached = @(Invoke-RestMethod "$api/releases/$($release.id)/assets" -Headers $headers)
|
$attached = @(Invoke-RestMethod "$api/releases/$($release.id)/assets" -Headers $headers)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
|
|
@ -10,7 +10,6 @@
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<AvaloniaResource Include="Assets/**" />
|
<AvaloniaResource Include="Assets/**" />
|
||||||
<RuntimeHostConfigurationOption Include="System.GC.HeapHardLimit" Value="3221225472" />
|
|
||||||
<RuntimeHostConfigurationOption Include="System.GC.Server" Value="false" />
|
<RuntimeHostConfigurationOption Include="System.GC.Server" Value="false" />
|
||||||
<ProjectReference Include="../AstroFrame.Engine/AstroFrame.Engine.csproj" />
|
<ProjectReference Include="../AstroFrame.Engine/AstroFrame.Engine.csproj" />
|
||||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.9" />
|
<PackageReference Include="Avalonia.Desktop" Version="11.3.9" />
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace AstroFrame.Desktop;
|
|
||||||
|
|
||||||
internal static class DesktopState
|
|
||||||
{
|
|
||||||
static string PathName=>System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AstroFrame","desktop.json");
|
|
||||||
public static void Remember(string projectDirectory)
|
|
||||||
{
|
|
||||||
if(Program.Arguments.Any(a=>a.StartsWith("--capture",StringComparison.Ordinal)||a=="--smoke"))return;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(PathName)!);
|
|
||||||
File.WriteAllText(PathName+".tmp",JsonSerializer.Serialize(new Dictionary<string,string>{{"LastProject",projectDirectory}}));File.Move(PathName+".tmp",PathName,true);
|
|
||||||
}
|
|
||||||
catch(IOException){}catch(UnauthorizedAccessException){}
|
|
||||||
}
|
|
||||||
public static string? LastProject()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if(!File.Exists(PathName)||new FileInfo(PathName).Length>4096)return null;
|
|
||||||
var state=JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllText(PathName));
|
|
||||||
string? directory=state?.GetValueOrDefault("LastProject");return directory!=null&&File.Exists(System.IO.Path.Combine(directory,"project.json"))?directory:null;
|
|
||||||
}
|
|
||||||
catch(IOException){return null;}catch(JsonException){return null;}catch(UnauthorizedAccessException){return null;}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
11
src/AstroFrame.Desktop/DiagnosticUpdateBackend.cs
Normal file
11
src/AstroFrame.Desktop/DiagnosticUpdateBackend.cs
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
namespace AstroFrame.Desktop;
|
||||||
|
|
||||||
|
// Diagnostic rendering never initializes the installed update locator or reads preferences.
|
||||||
|
internal sealed class DiagnosticUpdateBackend : IUpdateBackend
|
||||||
|
{
|
||||||
|
public bool IsInstalled=>true;
|
||||||
|
public string InstalledVersion=>typeof(MainWindow).Assembly.GetName().Version?.ToString(3)??"1.1.0";
|
||||||
|
public Task<string?> Check()=>Task.FromResult<string?>("9.0.0");
|
||||||
|
public Task Download(Action<int> progress,CancellationToken cancellation)=>throw new InvalidOperationException("Rendering diagnostics cannot download updates.");
|
||||||
|
public void ApplyAndRestart(string[] arguments)=>throw new InvalidOperationException("Rendering diagnostics cannot install updates.");
|
||||||
|
}
|
||||||
|
|
@ -1,25 +1,30 @@
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
using Avalonia.Threading;
|
using Avalonia.Threading;
|
||||||
using Avalonia.Controls.ApplicationLifetimes;
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Styling;
|
||||||
|
using Avalonia.Controls.Presenters;
|
||||||
|
|
||||||
namespace AstroFrame.Desktop;
|
namespace AstroFrame.Desktop;
|
||||||
|
|
||||||
public sealed partial class MainWindow
|
public sealed partial class MainWindow
|
||||||
{
|
{
|
||||||
readonly AppUpdates updates = new();
|
readonly AppUpdates updates = Program.Diagnostic ? new(new DiagnosticUpdateBackend(),new AppSettings(),_=>{}) : new();
|
||||||
readonly Button settingsButton = Button("Settings");
|
readonly Button settingsButton = Button("Settings");
|
||||||
readonly DispatcherTimer updateTimer = new() { Interval = TimeSpan.FromHours(6) };
|
readonly DispatcherTimer updateTimer = new() { Interval = TimeSpan.FromHours(6) };
|
||||||
SettingsWindow? settingsWindow;
|
SettingsWindow? settingsWindow;
|
||||||
|
|
||||||
void InitializeUpdates()
|
void InitializeUpdates()
|
||||||
{
|
{
|
||||||
|
Styles.Add(new Style(x=>x.OfType<Button>().Class("update-available").Template().OfType<ContentPresenter>())
|
||||||
|
{Setters={new Setter(ContentPresenter.BackgroundProperty,Palette.Update),new Setter(ContentPresenter.ForegroundProperty,Palette.Text)}});
|
||||||
settingsButton.Click += (_, _) => ShowSettings();
|
settingsButton.Click += (_, _) => ShowSettings();
|
||||||
updates.Changed += () =>
|
updates.Changed += () =>
|
||||||
{
|
{
|
||||||
settingsButton.Content = updates.AvailableVersion == null ? "Settings" : "Settings · Update available";
|
UpdateSettingsButton(updates.AvailableVersion!=null);
|
||||||
if (updates.Applying) { analyze.IsEnabled = false; export.IsEnabled = false; }
|
if (updates.Applying) { analyze.IsEnabled = false; export.IsEnabled = false; }
|
||||||
};
|
};
|
||||||
bool diagnostic = Program.Arguments.Any(a => a.StartsWith("--capture") || a == "--smoke");
|
bool diagnostic = Program.Diagnostic;
|
||||||
if (!diagnostic)
|
if (!diagnostic)
|
||||||
{
|
{
|
||||||
Opened += async (_, _) => await updates.Check(automatic: true);
|
Opened += async (_, _) => await updates.Check(automatic: true);
|
||||||
|
|
@ -28,6 +33,13 @@ public sealed partial class MainWindow
|
||||||
}
|
}
|
||||||
Closed += (_, _) => { updateTimer.Stop(); updates.Dispose(); settingsWindow?.Close(); };
|
Closed += (_, _) => { updateTimer.Stop(); updates.Dispose(); settingsWindow?.Close(); };
|
||||||
}
|
}
|
||||||
|
void UpdateSettingsButton(bool available)
|
||||||
|
{
|
||||||
|
settingsButton.Content=available?"Settings · Update available":"Settings";
|
||||||
|
settingsButton.Classes.Set("update-available",available);
|
||||||
|
settingsButton.Background=available?Palette.Update:Palette.Raised;
|
||||||
|
settingsButton.Foreground=Palette.Text;
|
||||||
|
}
|
||||||
public SettingsWindow ShowSettings()
|
public SettingsWindow ShowSettings()
|
||||||
{
|
{
|
||||||
if (settingsWindow != null) { settingsWindow.Activate(); return settingsWindow; }
|
if (settingsWindow != null) { settingsWindow.Activate(); return settingsWindow; }
|
||||||
|
|
|
||||||
116
src/AstroFrame.Desktop/MainWindow.Verification.cs
Normal file
116
src/AstroFrame.Desktop/MainWindow.Verification.cs
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Input;
|
||||||
|
using Avalonia.Input.Raw;
|
||||||
|
using Avalonia.Interactivity;
|
||||||
|
using Avalonia.Media.Imaging;
|
||||||
|
using Avalonia.VisualTree;
|
||||||
|
|
||||||
|
namespace AstroFrame.Desktop;
|
||||||
|
|
||||||
|
public sealed partial class MainWindow
|
||||||
|
{
|
||||||
|
public async Task VerifyInteractions(string fixture,string output)
|
||||||
|
{
|
||||||
|
if(!Program.Diagnostic)throw new InvalidOperationException("UI verification requires an isolated diagnostic launch.");
|
||||||
|
Directory.CreateDirectory(output);var results=new List<string>();
|
||||||
|
void Check(bool value,string text){if(!value)throw new Exception(text);results.Add("PASS "+text);}
|
||||||
|
void Capture(string name,double dpi=96)
|
||||||
|
{
|
||||||
|
using var bitmap=new RenderTargetBitmap(new PixelSize((int)Math.Ceiling(Bounds.Width*dpi/96),(int)Math.Ceiling(Bounds.Height*dpi/96)),new Vector(dpi,dpi));
|
||||||
|
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(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");
|
||||||
|
Capture("fresh-session");
|
||||||
|
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);
|
||||||
|
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);
|
||||||
|
var idle=new PointerPointProperties(RawInputModifiers.None,PointerUpdateKind.Other);
|
||||||
|
var held=new PointerPointProperties(RawInputModifiers.LeftMouseButton,PointerUpdateKind.LeftButtonPressed);
|
||||||
|
Point Local(double x,double y)=>preview.TranslatePoint(new Point(x,y),this)!.Value;
|
||||||
|
var at=Local(preview.Bounds.Width*.65,preview.Bounds.Height*.55);
|
||||||
|
var wheel=new PointerWheelEventArgs(preview,pointer,this,at,0,idle,KeyModifiers.None,new Vector(0,4));preview.RaiseEvent(wheel);
|
||||||
|
Check(viewport.Zoom>2&&wheel.Handled,"mouse wheel zooms through the actual preview handler");
|
||||||
|
var before=viewport.Pan;preview.RaiseEvent(new PointerPressedEventArgs(preview,pointer,this,at,0,held,KeyModifiers.None));
|
||||||
|
Check(pointer.Captured==preview,"left mouse press captures the preview for dragging");
|
||||||
|
preview.RaiseEvent(new PointerEventArgs(InputElement.PointerMovedEvent,preview,pointer,this,at+new Vector(35,22),0,held,KeyModifiers.None));
|
||||||
|
preview.RaiseEvent(new PointerReleasedEventArgs(preview,pointer,this,at+new Vector(35,22),0,idle,KeyModifiers.None,MouseButton.Left));
|
||||||
|
Check(viewport.Pan!=before&&pointer.Captured==null,"mouse drag pans and release ends capture");
|
||||||
|
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");
|
||||||
|
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 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);
|
||||||
|
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;
|
||||||
|
Check(bounds.X>=0&&bounds.X+resetView.Bounds.Width<=Bounds.Width,"Reset view stays visible at minimum window width");
|
||||||
|
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"));
|
||||||
|
File.WriteAllLines(System.IO.Path.Combine(output,"interaction-checks.txt"),results);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -23,9 +23,14 @@ public sealed partial class MainWindow:Window
|
||||||
readonly ComboBox sort=new(){ItemsSource=new[]{"Capture time","Most concerning","Lowest star count","Lowest stellar flux","Highest FWHM"},SelectedIndex=0,MinWidth=155};
|
readonly ComboBox sort=new(){ItemsSource=new[]{"Capture time","Most concerning","Lowest star count","Lowest stellar flux","Highest FWHM"},SelectedIndex=0,MinWidth=155};
|
||||||
readonly ComboBox metric=new(){ItemsSource=QualityChart.Metrics.Select(x=>x.Name).ToArray(),SelectedIndex=0,MinWidth=145};
|
readonly ComboBox metric=new(){ItemsSource=QualityChart.Metrics.Select(x=>x.Name).ToArray(),SelectedIndex=0,MinWidth=145};
|
||||||
readonly QualityChart chart=new();
|
readonly QualityChart chart=new();
|
||||||
readonly ExposureView preview=new(),comparison=new();
|
readonly PreviewViewport viewport=new();
|
||||||
|
readonly ExposureView preview,comparison;
|
||||||
|
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)};
|
||||||
|
|
@ -34,22 +39,29 @@ 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()
|
||||||
{
|
{
|
||||||
|
Background=TransparencyBackgroundFallback=Palette.Background;
|
||||||
|
NativeWindowBackground.Apply(this);
|
||||||
|
preview=new(viewport);comparison=new(viewport);
|
||||||
previewPanel=Panel(preview);comparisonBorder=Panel(comparison);
|
previewPanel=Panel(preview);comparisonBorder=Panel(comparison);
|
||||||
var displayPanel=new Grid{RowDefinitions=new("Auto,48")};var stretchHeading=new Grid{ColumnDefinitions=new("*,Auto")};stretchHeading.Children.Add(Palette.Label("Preview stretch",11,Palette.Muted));Grid.SetColumn(stretchValue,1);stretchHeading.Children.Add(stretchValue);displayPanel.Children.Add(stretchHeading);
|
var displayPanel=new Grid{RowDefinitions=new("Auto,48")};var stretchHeading=new Grid{ColumnDefinitions=new("*,Auto")};stretchHeading.Children.Add(Palette.Label("Preview stretch",11,Palette.Muted));Grid.SetColumn(stretchValue,1);stretchHeading.Children.Add(stretchValue);displayPanel.Children.Add(stretchHeading);
|
||||||
var stretchRow=new Grid{ColumnDefinitions=new("*,Auto")};displayStretch.MinHeight=44;displayStretch.VerticalAlignment=VerticalAlignment.Center;displayStretch.Margin=new(0,0,12,0);stretchRow.Children.Add(displayStretch);
|
var stretchRow=new Grid{ColumnDefinitions=new("*,Auto")};displayStretch.MinHeight=44;displayStretch.VerticalAlignment=VerticalAlignment.Center;displayStretch.Margin=new(0,0,12,0);stretchRow.Children.Add(displayStretch);
|
||||||
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;
|
||||||
|
|
@ -79,8 +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"),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);center.Children.Add(previewHeading);
|
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);
|
||||||
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);
|
var previewActions=new WrapPanel{Margin=new(0,8,0,0)};
|
||||||
|
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);
|
||||||
|
|
@ -89,11 +104,13 @@ 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.");
|
||||||
KeyDown+=async(_,e)=>
|
KeyDown+=async(_,e)=>
|
||||||
{
|
{
|
||||||
if(busy||updates.Applying||e.Source is TextBox)return;
|
if(busy||updates.Applying||e.Source is TextBox)return;
|
||||||
|
|
@ -102,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};
|
||||||
|
|
@ -132,7 +149,7 @@ public sealed partial class MainWindow:Window
|
||||||
int sessionCount=project.Frames.Select(f=>f.Session).Distinct().Count();title.Text=project.Name;subtitle.Text=$"{project.Frames.Count:N0} lights · {sessionCount} "+(sessionCount==1?"session":"sessions");
|
int sessionCount=project.Frames.Select(f=>f.Session).Distinct().Count();title.Text=project.Name;subtitle.Text=$"{project.Frames.Count:N0} lights · {sessionCount} "+(sessionCount==1?"session":"sessions");
|
||||||
refreshing=true;sessions.ItemsSource=new[]{"All sessions"}.Concat(project.Frames.Select(f=>f.Session).Distinct().Order()).ToArray();sessions.SelectedIndex=0;refreshing=false;
|
refreshing=true;sessions.ItemsSource=new[]{"All sessions"}.Concat(project.Frames.Select(f=>f.Session).Distinct().Order()).ToArray();sessions.SelectedIndex=0;refreshing=false;
|
||||||
RefreshFrames();status.Text=project.Complete?"":"Incomplete or changed project · reanalyze before exporting";export.IsEnabled=project.Complete;
|
RefreshFrames();status.Text=project.Complete?"":"Incomplete or changed project · reanalyze before exporting";export.IsEnabled=project.Complete;
|
||||||
DesktopState.Remember(directory);
|
// Projects remain saved on disk; each ordinary launch begins with an empty workspace.
|
||||||
}
|
}
|
||||||
void RefreshFrames(Frame? prefer=null)
|
void RefreshFrames(Frame? prefer=null)
|
||||||
{
|
{
|
||||||
|
|
@ -155,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)
|
||||||
|
|
@ -165,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");
|
||||||
|
|
@ -185,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");
|
||||||
|
|
@ -200,12 +219,13 @@ 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);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);
|
||||||
inspector.Children.Add(Palette.Label("DECISION EVIDENCE",10,Palette.Muted));
|
inspector.Children.Add(Palette.Label("DECISION EVIDENCE",10,Palette.Muted));
|
||||||
inspector.Children.Add(new TextBlock{Text=f.Cause,FontSize=14,Foreground=Palette.Text,TextWrapping=TextWrapping.Wrap});
|
inspector.Children.Add(new TextBlock{Text=f.Cause,FontSize=14,Foreground=Palette.Text,TextWrapping=TextWrapping.Wrap});
|
||||||
|
|
@ -225,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);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)
|
||||||
|
|
@ -245,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;
|
||||||
|
|
|
||||||
19
src/AstroFrame.Desktop/NativeWindowBackground.cs
Normal file
19
src/AstroFrame.Desktop/NativeWindowBackground.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
|
||||||
|
namespace AstroFrame.Desktop;
|
||||||
|
|
||||||
|
// Avalonia creates a native class without a background brush. Supply the same
|
||||||
|
// grey used by the content so Windows erases newly exposed pixels before rendering.
|
||||||
|
internal static class NativeWindowBackground
|
||||||
|
{
|
||||||
|
[DllImport("gdi32.dll")]static extern nint CreateSolidBrush(uint color);
|
||||||
|
[DllImport("user32.dll",EntryPoint="SetClassLongPtrW")]static extern nint SetClassLongPtr(nint window,int index,nint value);
|
||||||
|
[DllImport("user32.dll",EntryPoint="GetClassLongPtrW")]static extern nint GetClassLongPtr(nint window,int index);
|
||||||
|
static readonly nint brush=OperatingSystem.IsWindows()?CreateSolidBrush(0x00171615):0;
|
||||||
|
public static void Apply(Window window)
|
||||||
|
{
|
||||||
|
if(OperatingSystem.IsWindows()&&window.TryGetPlatformHandle() is { } handle)SetClassLongPtr(handle.Handle,-10,brush);
|
||||||
|
}
|
||||||
|
public static bool IsApplied(Window window)=>!OperatingSystem.IsWindows()||GetClassLongPtr(window.TryGetPlatformHandle()!.Handle,-10)==brush&&brush!=0;
|
||||||
|
}
|
||||||
33
src/AstroFrame.Desktop/PreviewViewport.cs
Normal file
33
src/AstroFrame.Desktop/PreviewViewport.cs
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
using Avalonia;
|
||||||
|
|
||||||
|
namespace AstroFrame.Desktop;
|
||||||
|
|
||||||
|
// Pan is measured relative to the fitted image, preserving the same image region
|
||||||
|
// when frames change or the window/comparison pane changes size.
|
||||||
|
public sealed class PreviewViewport
|
||||||
|
{
|
||||||
|
public double Zoom {get;private set;}=1;
|
||||||
|
public Vector Pan {get;private set;}
|
||||||
|
public event Action? Changed;
|
||||||
|
public Rect ImageRect(Rect area,Size image)
|
||||||
|
{
|
||||||
|
double fit=Math.Min(area.Width/image.Width,area.Height/image.Height);
|
||||||
|
double w=image.Width*fit,h=image.Height*fit;
|
||||||
|
return new(area.Center.X-w*Zoom/2+Pan.X*w,area.Center.Y-h*Zoom/2+Pan.Y*h,w*Zoom,h*Zoom);
|
||||||
|
}
|
||||||
|
public void ZoomAt(double delta,Point pointer,Rect area,Size image)
|
||||||
|
{
|
||||||
|
var before=ImageRect(area,image);double next=Math.Clamp(Zoom*Math.Pow(1.2,Math.Clamp(delta,-10,10)),1,16);
|
||||||
|
double factor=next/Zoom;
|
||||||
|
Zoom=next;
|
||||||
|
var after=ImageRect(area,image);
|
||||||
|
Pan+=new Vector((pointer.X-(pointer.X-before.X)*factor-after.X)/(after.Width/Zoom),(pointer.Y-(pointer.Y-before.Y)*factor-after.Y)/(after.Height/Zoom));
|
||||||
|
Clamp();Changed?.Invoke();
|
||||||
|
}
|
||||||
|
public void Drag(Vector pixels,Rect area,Size image)
|
||||||
|
{
|
||||||
|
var rect=ImageRect(area,image);Pan+=new Vector(pixels.X/(rect.Width/Zoom),pixels.Y/(rect.Height/Zoom));Clamp();Changed?.Invoke();
|
||||||
|
}
|
||||||
|
void Clamp()=>Pan=new Vector(Math.Clamp(Pan.X,-(Zoom-1)/2,(Zoom-1)/2),Math.Clamp(Pan.Y,-(Zoom-1)/2,(Zoom-1)/2));
|
||||||
|
public void Reset(){Zoom=1;Pan=default;Changed?.Invoke();}
|
||||||
|
}
|
||||||
|
|
@ -11,18 +11,20 @@ namespace AstroFrame.Desktop;
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
public static string[] Arguments=[];
|
public static string[] Arguments=[];
|
||||||
|
public static bool Diagnostic=>Arguments.Any(a=>a.StartsWith("--capture",StringComparison.Ordinal)||a=="--smoke"||a=="--verify-ui");
|
||||||
static Mutex? instance;
|
static Mutex? instance;
|
||||||
[STAThread] public static void Main(string[] args)
|
[STAThread] public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
Velopack.VelopackApp.Build().SetAutoApplyOnStartup(false).Run();
|
Arguments=args;
|
||||||
|
if(!Diagnostic)Velopack.VelopackApp.Build().SetAutoApplyOnStartup(false).Run();
|
||||||
if(args.Length>=3&&args[0]=="--verify-update"){Environment.ExitCode=UpdateDiagnostics.Run(args).GetAwaiter().GetResult();return;}
|
if(args.Length>=3&&args[0]=="--verify-update"){Environment.ExitCode=UpdateDiagnostics.Run(args).GetAwaiter().GetResult();return;}
|
||||||
instance=new Mutex(true,"AstroFrame.Desktop.OneInstance",out bool created);if(!created)return;
|
instance=new Mutex(true,Diagnostic?"AstroFrame.Desktop.Diagnostics":"AstroFrame.Desktop.OneInstance",out bool created);if(!created)return;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
ResourcePolicy.InstallWindowsLimit();Arguments=args;
|
ResourcePolicy.InstallWindowsLimit();Arguments=args;
|
||||||
AppBuilder.Configure<App>().UsePlatformDetect().With(new Win32PlatformOptions{RenderingMode=[Win32RenderingMode.Software]}).WithInterFont().LogToTrace().StartWithClassicDesktopLifetime(args);
|
AppBuilder.Configure<App>().UsePlatformDetect().With(new Win32PlatformOptions{RenderingMode=[Win32RenderingMode.Software]}).WithInterFont().LogToTrace().StartWithClassicDesktopLifetime(args);
|
||||||
}
|
}
|
||||||
catch(Exception e){try{Directory.CreateDirectory(AppSettings.DataDirectory);File.WriteAllText(System.IO.Path.Combine(AppSettings.DataDirectory,"startup-error.log"),e.ToString());}catch{}Environment.ExitCode=1;}
|
catch(Exception e){if(Diagnostic)Console.Error.WriteLine(e);else try{Directory.CreateDirectory(AppSettings.DataDirectory);File.WriteAllText(System.IO.Path.Combine(AppSettings.DataDirectory,"startup-error.log"),e.ToString());}catch{}Environment.ExitCode=1;}
|
||||||
finally{instance.ReleaseMutex();instance.Dispose();}
|
finally{instance.ReleaseMutex();instance.Dispose();}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -42,7 +44,15 @@ public sealed class App:Application
|
||||||
string directory=System.IO.Path.GetFullPath(Program.Arguments[1]);var project=ProjectStore.Load(directory);var frame=project.Frames.First(f=>f.Name.Contains(Program.Arguments[3],StringComparison.OrdinalIgnoreCase));desktop.MainWindow=new StarInspector(project,directory,frame,Program.Arguments[2]);base.OnFrameworkInitializationCompleted();return;
|
string directory=System.IO.Path.GetFullPath(Program.Arguments[1]);var project=ProjectStore.Load(directory);var frame=project.Frames.First(f=>f.Name.Contains(Program.Arguments[3],StringComparison.OrdinalIgnoreCase));desktop.MainWindow=new StarInspector(project,directory,frame,Program.Arguments[2]);base.OnFrameworkInitializationCompleted();return;
|
||||||
}
|
}
|
||||||
var window=new MainWindow();desktop.MainWindow=window;
|
var window=new MainWindow();desktop.MainWindow=window;
|
||||||
if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--capture-settings")
|
if(Program.Arguments.Length>=3&&Program.Arguments[0]=="--verify-ui")
|
||||||
|
{
|
||||||
|
window.Opened+=async(_,_)=>
|
||||||
|
{
|
||||||
|
try{await window.VerifyInteractions(Program.Arguments[1],Program.Arguments[2]);desktop.Shutdown(0);}
|
||||||
|
catch(Exception e){File.WriteAllText(System.IO.Path.Combine(Program.Arguments[2],"error.txt"),e.ToString());desktop.Shutdown(1);}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--capture-settings")
|
||||||
{
|
{
|
||||||
window.Opened+=async(_,_)=>
|
window.Opened+=async(_,_)=>
|
||||||
{
|
{
|
||||||
|
|
@ -68,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)
|
||||||
|
|
@ -86,7 +97,6 @@ public sealed class App:Application
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--project")window.Opened+=(_,_)=>window.LoadProject(System.IO.Path.GetFullPath(Program.Arguments[1]));
|
else if(Program.Arguments.Length>=2&&Program.Arguments[0]=="--project")window.Opened+=(_,_)=>window.LoadProject(System.IO.Path.GetFullPath(Program.Arguments[1]));
|
||||||
else if(DesktopState.LastProject() is string last)window.Opened+=async(_,_)=>{try{window.LoadProject(last);}catch(Exception e){await window.ReportLoadFailure(e.Message);}};
|
|
||||||
}
|
}
|
||||||
base.OnFrameworkInitializationCompleted();
|
base.OnFrameworkInitializationCompleted();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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()=>{await ResourcePolicy.WaitForHeadroom(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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 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,29 +74,48 @@ 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=[];
|
||||||
CancellationTokenSource? request;
|
CancellationTokenSource? request;
|
||||||
string message="Select an exposure";
|
string message="Select an exposure";
|
||||||
public Task Loading {get;private set;}=Task.CompletedTask;
|
public Task Loading {get;private set;}=Task.CompletedTask;
|
||||||
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 ExposureView(){RenderOptions.SetBitmapInterpolationMode(this,BitmapInterpolationMode.HighQuality);}
|
public PreviewViewport Viewport {get;}
|
||||||
public void Load(string projectDirectory,Frame? f)
|
Point? dragStart;IPointer? dragPointer;
|
||||||
|
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(PreviewViewport viewport)
|
||||||
|
{
|
||||||
|
Viewport=viewport;Viewport.Changed+=InvalidateVisual;ClipToBounds=true;
|
||||||
|
RenderOptions.SetBitmapInterpolationMode(this,BitmapInterpolationMode.HighQuality);
|
||||||
|
ToolTip.SetTip(this,"Scroll to zoom · Drag to pan · Reset view to fit");
|
||||||
|
PointerWheelChanged+=(_,e)=>{if(bitmap==null||!ImageArea.Contains(e.GetPosition(this)))return;Viewport.ZoomAt(e.Delta.Y,e.GetPosition(this),ImageArea,bitmap.Size);e.Handled=true;};
|
||||||
|
PointerPressed+=(_,e)=>{if(bitmap==null||!ImageArea.Contains(e.GetPosition(this))||!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)return;dragStart=e.GetPosition(this);dragPointer=e.Pointer;e.Pointer.Capture(this);Cursor=new Cursor(StandardCursorType.SizeAll);e.Handled=true;};
|
||||||
|
PointerMoved+=(_,e)=>{if(dragStart is not Point last||bitmap==null)return;var now=e.GetPosition(this);Viewport.Drag(now-last,ImageArea,bitmap.Size);dragStart=now;e.Handled=true;};
|
||||||
|
PointerReleased+=(_,e)=>{if(dragStart==null)return;EndDrag();e.Handled=true;};
|
||||||
|
PointerCaptureLost+=(_,_)=>{dragStart=null;dragPointer=null;Cursor=Cursor.Default;};
|
||||||
|
}
|
||||||
|
void EndDrag(){dragStart=null;dragPointer?.Capture(null);dragPointer=null;Cursor=Cursor.Default;}
|
||||||
|
public void Load(string projectDirectory,Frame? f,IReadOnlyList<Frame>? frames=null)
|
||||||
{
|
{
|
||||||
Dispose();Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
|
Dispose();Frame=f;message=f==null?"Select an exposure":"Loading preview…";InvalidateVisual();
|
||||||
if(f==null){Loading=Task.CompletedTask;return;}
|
if(f==null){Loading=Task.CompletedTask;return;}
|
||||||
request=new();Loading=LoadCore(projectDirectory,f,request.Token);
|
request=new();Loading=LoadCore(projectDirectory,f,frames??[],request.Token);
|
||||||
}
|
}
|
||||||
async Task LoadCore(string directory,Frame f,CancellationToken token)
|
async Task LoadCore(string directory,Frame f,IReadOnlyList<Frame> frames,CancellationToken token)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await LoadGate.WaitAsync(token);
|
await LoadGate.WaitAsync(token);
|
||||||
(PreviewDisplay Frame,PreviewDisplay Nebula) prepared;
|
(PreviewDisplay Frame,byte[] Overlay) prepared;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
prepared=await Task.Run(async()=>
|
prepared=await Task.Run(async()=>
|
||||||
|
|
@ -106,21 +125,50 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
try{if(File.Exists(path))plane=PreviewRenderer.Read(path,f);}catch(IOException){}
|
try{if(File.Exists(path))plane=PreviewRenderer.Read(path,f);}catch(IOException){}
|
||||||
if(plane==null)
|
if(plane==null)
|
||||||
{
|
{
|
||||||
await ResourcePolicy.WaitForHeadroom(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));
|
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;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();
|
||||||
|
|
@ -129,9 +177,12 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
{
|
{
|
||||||
base.Render(c);c.FillRectangle(Palette.Background,new Rect(Bounds.Size));
|
base.Render(c);c.FillRectangle(Palette.Background,new Rect(Bounds.Size));
|
||||||
if(bitmap==null){c.DrawText(new FormattedText(message,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),13,Palette.Muted){MaxTextWidth=Math.Max(100,Bounds.Width-32)},new(16,20));return;}
|
if(bitmap==null){c.DrawText(new FormattedText(message,System.Globalization.CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Inter"),13,Palette.Muted){MaxTextWidth=Math.Max(100,Bounds.Width-32)},new(16,20));return;}
|
||||||
double header=Caption!=""?26:0;
|
double captionHeight=Caption!=""?26:0,header=captionHeight+(Spatial?22:0);
|
||||||
if(header>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));
|
||||||
double scale=Math.Min(Bounds.Width/bitmap.PixelSize.Width,Math.Max(1,Bounds.Height-header)/bitmap.PixelSize.Height),w=bitmap.PixelSize.Width*scale,h=bitmap.PixelSize.Height*scale;var rect=new Rect((Bounds.Width-w)/2,header+(Bounds.Height-header-h)/2,w,h);c.DrawImage(bitmap,new Rect(bitmap.Size),rect);
|
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);
|
||||||
|
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)
|
||||||
{
|
{
|
||||||
var f=Frame;double aspect=(double)f.Height/f.Width;var a=f.Alignment;
|
var f=Frame;double aspect=(double)f.Height/f.Width;var a=f.Alignment;
|
||||||
|
|
@ -140,8 +191,8 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
{
|
{
|
||||||
StreamGeometry Cell(double x,double y,double dx,double dy)
|
StreamGeometry Cell(double x,double y,double dx,double dy)
|
||||||
{var geometry=new StreamGeometry();using(var g=geometry.Open()){g.BeginFigure(Map(x,y),true);g.LineTo(Map(x+dx,y));g.LineTo(Map(x+dx,y+dy));g.LineTo(Map(x,y+dy));g.EndFigure(true);}return geometry;}
|
{var geometry=new StreamGeometry();using(var g=geometry.Open()){g.BeginFigure(Map(x,y),true);g.LineTo(Map(x+dx,y));g.LineTo(Map(x+dx,y+dy));g.LineTo(Map(x,y+dy));g.EndFigure(true);}return geometry;}
|
||||||
if(f.CloudMask.Length==SkyModel.Count)for(int i=0;i<SkyModel.Count;i++)if(f.CloudMask[i]>0)
|
if(overlayMask.Length==SkyModel.Count)for(int i=0;i<SkyModel.Count;i++)if(overlayMask[i]>0)
|
||||||
c.DrawGeometry(new SolidColorBrush(Color.FromArgb(85,245,142,155)),null,Cell((double)(i%SkyModel.Columns)/SkyModel.Columns,(double)(i/SkyModel.Columns)/SkyModel.Rows,1.0/SkyModel.Columns,1.0/SkyModel.Rows));
|
c.DrawGeometry(new SolidColorBrush(Color.FromArgb((byte)Math.Round(105*overlayMask[i]/255.0),245,142,155)),null,Cell((double)(i%SkyModel.Columns)/SkyModel.Columns,(double)(i/SkyModel.Columns)/SkyModel.Rows,1.0/SkyModel.Columns,1.0/SkyModel.Rows));
|
||||||
for(int i=0;i<12;i++)
|
for(int i=0;i<12;i++)
|
||||||
{
|
{
|
||||||
double baseline=f.Baselines.GetValueOrDefault($"Region {i+1}"),ratio=baseline>0?f.RegionFlux[i]/baseline:1;
|
double baseline=f.Baselines.GetValueOrDefault($"Region {i+1}"),ratio=baseline>0?f.RegionFlux[i]/baseline:1;
|
||||||
|
|
@ -151,5 +202,5 @@ public sealed class ExposureView:Control,IDisposable
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public void Dispose(){request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=nebulaDisplay=null;}
|
public void Dispose(){EndDrag();request?.Cancel();request?.Dispose();request=null;bitmap?.Dispose();bitmap=null;frameDisplay=denoisedDisplay=null;denoiseAttempted=false;overlayMask=[];}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -48,6 +49,15 @@ public static class Classification
|
||||||
bool moderateStructure=spatial&&f.CloudSignificance>=5&&f.CloudCoverage>=.02&&connected>=.01;
|
bool moderateStructure=spatial&&f.CloudSignificance>=5&&f.CloudCoverage>=.02&&connected>=.01;
|
||||||
bool fluxLoss=fluxZ>=4&&fluxRatio<.78,starLoss=countZ>=3&&countRatio<.75;
|
bool fluxLoss=fluxZ>=4&&fluxRatio<.78,starLoss=countZ>=3&&countRatio<.75;
|
||||||
bool strongFlux=fluxZ>=5&&fluxRatio<.60&&starLoss;
|
bool strongFlux=fluxZ>=5&&fluxRatio<.60&&starLoss;
|
||||||
|
bool localCloudLoss=spatial&&f.CloudSignificance>=8&&f.CloudCoverage>=.08&&connected>=.035&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Cloud positive coverage")>=.08&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Cloud positive connected coverage")>=.035&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Cloud aperture samples")>=20&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Cloud aperture regions")>=2&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Cloud aperture flux ratio")<.90&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Cloud aperture flux deviation")>=3;
|
||||||
|
if(localCloudLoss)f.Evidence.Add(new("Cloud aperture flux",f.AdditionalMeasurements["Cloud aperture flux ratio"],1,f.AdditionalMeasurements["Cloud aperture flux deviation"],
|
||||||
|
$"Coherent excess sky coincides with stellar flux {f.AdditionalMeasurements["Cloud aperture flux ratio"]:P0} of the same-aperture reference ({f.AdditionalMeasurements["Cloud aperture samples"]:0} apertures); uncertainty {f.AdditionalMeasurements.GetValueOrDefault("Cloud aperture flux uncertainty"):P1}"));
|
||||||
bool regionLoss=false;
|
bool regionLoss=false;
|
||||||
for(int r=0;r<12;r++)
|
for(int r=0;r<12;r++)
|
||||||
{
|
{
|
||||||
|
|
@ -68,19 +78,56 @@ public static class Classification
|
||||||
if(fluxLoss)f.Evidence.Add(new("Stellar flux",f.Transparency,f.Baselines["Stellar flux"],fluxZ,$"Forced stellar flux reduced to {fluxRatio:P0} of nearby clear-frame baseline; lost detections remain in the measurement"));
|
if(fluxLoss)f.Evidence.Add(new("Stellar flux",f.Transparency,f.Baselines["Stellar flux"],fluxZ,$"Forced stellar flux reduced to {fluxRatio:P0} of nearby clear-frame baseline; lost detections remain in the measurement"));
|
||||||
if(starLoss)f.Evidence.Add(new("Star count",f.StarCount,f.Baselines["Star count"],countZ,$"Detected stars reduced to {countRatio:P0} of clear-frame baseline"));
|
if(starLoss)f.Evidence.Add(new("Star count",f.StarCount,f.Baselines["Star count"],countZ,$"Detected stars reduced to {countRatio:P0} of clear-frame baseline"));
|
||||||
bool widthBad=widthZ>4&&widthRatio>1.25,shapeBad=shapeZ>4&&f.Ellipticity>f.Baselines["Ellipticity"]+.15;
|
bool widthBad=widthZ>4&&widthRatio>1.25,shapeBad=shapeZ>4&&f.Ellipticity>f.Baselines["Ellipticity"]+.15;
|
||||||
|
if(shapeBad&&f.AdditionalMeasurements.GetValueOrDefault("Matched shape samples")>=50&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Matched shape reference frames")>=12&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Matched shape uncertainty")>0&&
|
||||||
|
f.AdditionalMeasurements["Matched shape uncertainty"]<=.025&&
|
||||||
|
f.AdditionalMeasurements.GetValueOrDefault("Matched shape change")+3*f.AdditionalMeasurements["Matched shape uncertainty"]<.10)
|
||||||
|
{
|
||||||
|
shapeBad=false;
|
||||||
|
f.Evidence.Add(new("Matched stellar shape",f.AdditionalMeasurements["Matched shape change"],.10,0,"Matched reference stars do not corroborate the detection-cohort elongation flag"));
|
||||||
|
}
|
||||||
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;
|
bool cloud=strongStructure||moderateStructure&&(fluxLoss||regionLoss||starLoss)||strongFlux||localCloudLoss;
|
||||||
bool weak=f.MatchFraction<.35||f.Transparency<=0||f.Fwhm<=0||(spatial&&f.AdditionalMeasurements.GetValueOrDefault("Forced flux samples")<20);
|
bool lowMatches=f.MatchFraction<.35;
|
||||||
|
bool geometryWeak=spatial?f.AdditionalMeasurements.GetValueOrDefault("Alignment verified")<=0:lowMatches;
|
||||||
|
bool weak=geometryWeak||f.Transparency<=0||f.Fwhm<=0||(spatial&&f.AdditionalMeasurements.GetValueOrDefault("Forced flux samples")<20);
|
||||||
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;
|
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"));
|
||||||
if(weak)f.Evidence.Add(new("Matching",f.MatchFraction,.35,0,"Uncertain star alignment or reference aperture coverage; inspect manually"));
|
if(weak)f.Evidence.Add(new("Matching",f.MatchFraction,.35,0,"Unverified geometric alignment or insufficient reference photometry; inspect manually"));
|
||||||
|
else if(lowMatches)f.Evidence.Add(new("Alignment",f.AdditionalMeasurements.GetValueOrDefault("Alignment tight matches"),20,0,
|
||||||
|
$"Star survival is low, but {f.AdditionalMeasurements.GetValueOrDefault("Alignment tight matches"):0} tight matches verify geometry; median residual {f.AdditionalMeasurements.GetValueOrDefault("Alignment median residual pixels"):0.00} source pixels"));
|
||||||
if(f.Warning!="")f.Evidence.Add(new("Metadata",0,0,0,f.Warning));
|
if(f.Warning!="")f.Evidence.Add(new("Metadata",0,0,0,f.Warning));
|
||||||
if(!widthBad)f.Evidence.Add(new("FWHM",f.Fwhm,f.Baselines["FWHM"],0,"Stellar width is within the practical tolerance of nearby clear frames"));
|
if(!widthBad)f.Evidence.Add(new("FWHM",f.Fwhm,f.Baselines["FWHM"],0,"Stellar width is within the practical tolerance of nearby clear frames"));
|
||||||
if(f.Evidence.Count==1)f.Evidence.Add(new("Reference",f.Transparency,f.Baselines["Stellar flux"],0,"Aligned sky structure, stellar flux and morphology show no substantial degradation"));
|
if(f.Evidence.Count==1)f.Evidence.Add(new("Reference",f.Transparency,f.Baselines["Stellar flux"],0,"Aligned sky structure, stellar flux and morphology show no substantial degradation"));
|
||||||
|
|
|
||||||
56
src/AstroFrame.Engine/DenoisedPreview.cs
Normal file
56
src/AstroFrame.Engine/DenoisedPreview.cs
Normal 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;}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -81,19 +81,40 @@ public static class Matching
|
||||||
{
|
{
|
||||||
frame.Transparency=0;frame.MatchFraction=0;frame.RegionFlux=new double[12];frame.RegionLoss=new double[12];frame.RegionMatches=new int[12];
|
frame.Transparency=0;frame.MatchFraction=0;frame.RegionFlux=new double[12];frame.RegionLoss=new double[12];frame.RegionMatches=new int[12];
|
||||||
frame.Alignment=[];frame.ReferenceId=reference.Id;
|
frame.Alignment=[];frame.ReferenceId=reference.Id;
|
||||||
|
frame.MatchedShape=Enumerable.Repeat(double.NaN,Math.Min(600,reference.Stars.Count)).ToArray();
|
||||||
|
foreach(string key in new[]{"Alignment verified","Alignment matches","Alignment tight matches","Alignment median residual pixels","Alignment p95 residual pixels","Alignment occupied regions"})frame.AdditionalMeasurements[key]=0;
|
||||||
var tr=Align(reference,frame);if(tr==null)return;
|
var tr=Align(reference,frame);if(tr==null)return;
|
||||||
frame.Alignment=[tr.A,tr.B,tr.Tx,tr.Ty];
|
frame.Alignment=[tr.A,tr.B,tr.Tx,tr.Ty];
|
||||||
double aspect=(double)reference.Height/reference.Width;var grid=new Grid(frame.Stars,aspect);
|
double aspect=(double)reference.Height/reference.Width;var grid=new Grid(frame.Stars,aspect);
|
||||||
List<double> ratios=[];List<double>[] regional=Enumerable.Range(0,12).Select(_=>new List<double>()).ToArray();int[] expected=new int[12],found=new int[12];HashSet<Star> used=[];
|
List<double> ratios=[];List<double>[] regional=Enumerable.Range(0,12).Select(_=>new List<double>()).ToArray();int[] expected=new int[12],found=new int[12];HashSet<Star> used=[];
|
||||||
|
List<double> residuals=[];List<Star> tight=[];int[] tightRegions=new int[12];int index=-1;
|
||||||
foreach(var s in reference.Stars.Take(600))
|
foreach(var s in reference.Stars.Take(600))
|
||||||
{
|
{
|
||||||
|
index++;
|
||||||
var(x,y)=tr.Apply(s.X,s.Y*aspect);y/=aspect;
|
var(x,y)=tr.Apply(s.X,s.Y*aspect);y/=aspect;
|
||||||
if(x<.025||x>.975||y<.025||y>.975)continue;
|
if(x<.025||x>.975||y<.025||y>.975)continue;
|
||||||
int region=Math.Clamp((int)(s.Y*4),0,3)*3+Math.Clamp((int)(s.X*3),0,2);expected[region]++;
|
int region=Math.Clamp((int)(s.Y*4),0,3)*3+Math.Clamp((int)(s.X*3),0,2);expected[region]++;
|
||||||
var other=grid.Nearest(x,y*aspect);if(other==null||!used.Add(other))continue;found[region]++;
|
var other=grid.Nearest(x,y*aspect);if(other==null||!used.Add(other))continue;found[region]++;
|
||||||
|
double residual=Math.Sqrt(Math.Pow(other.X-x,2)+Math.Pow((other.Y-y)*aspect,2))*reference.Width;
|
||||||
|
residuals.Add(residual);
|
||||||
|
if(residual<=Math.Max(1,reference.Fwhm*.4))
|
||||||
|
{tight.Add(s);tightRegions[region]++;frame.MatchedShape[index]=other.Ellipticity;}
|
||||||
double ratio=other.Flux/Math.Max(s.Flux,.001);if(double.IsFinite(ratio)&&ratio>0){ratios.Add(ratio);regional[region].Add(ratio);}
|
double ratio=other.Flux/Math.Max(s.Flux,.001);if(double.IsFinite(ratio)&&ratio>0){ratios.Add(ratio);regional[region].Add(ratio);}
|
||||||
}
|
}
|
||||||
frame.MatchFraction=(double)found.Sum()/Math.Max(expected.Sum(),1);
|
frame.MatchFraction=(double)found.Sum()/Math.Max(expected.Sum(),1);
|
||||||
|
double median=Robust.Median(residuals),p95=Robust.Quantile(residuals,.95),scale=Math.Sqrt(tr.A*tr.A+tr.B*tr.B);
|
||||||
|
int occupied=tightRegions.Count(n=>n>=3);
|
||||||
|
// Star survival is attenuation evidence, not a geometric fit-quality measure.
|
||||||
|
// Require tight, distributed correspondences before trusting any rejection.
|
||||||
|
bool verified=tight.Count>=20&&tight.Count>=residuals.Count*.8&&occupied>=3&&
|
||||||
|
tight.Max(s=>s.X)-tight.Min(s=>s.X)>=.15&&tight.Max(s=>s.Y)-tight.Min(s=>s.Y)>=.15&&
|
||||||
|
median<=Math.Max(.5,reference.Fwhm*.2)&&p95<=Math.Max(1,reference.Fwhm*.5)&&scale>=.975&&scale<=1.025;
|
||||||
|
frame.AdditionalMeasurements["Alignment verified"]=verified?1:0;
|
||||||
|
frame.AdditionalMeasurements["Alignment matches"]=residuals.Count;
|
||||||
|
frame.AdditionalMeasurements["Alignment tight matches"]=tight.Count;
|
||||||
|
frame.AdditionalMeasurements["Alignment median residual pixels"]=median;
|
||||||
|
frame.AdditionalMeasurements["Alignment p95 residual pixels"]=p95;
|
||||||
|
frame.AdditionalMeasurements["Alignment occupied regions"]=occupied;
|
||||||
if(ratios.Count>=15)frame.Transparency=Robust.Median(ratios);
|
if(ratios.Count>=15)frame.Transparency=Robust.Median(ratios);
|
||||||
for(int i=0;i<12;i++){frame.RegionMatches[i]=regional[i].Count;frame.RegionLoss[i]=expected[i]>=8?1-(double)found[i]/expected[i]:0;frame.RegionFlux[i]=regional[i].Count>=5?Robust.Median(regional[i]):0;}
|
for(int i=0;i<12;i++){frame.RegionMatches[i]=regional[i].Count;frame.RegionLoss[i]=expected[i]>=8?1-(double)found[i]/expected[i]:0;frame.RegionFlux[i]=regional[i].Count>=5?Robust.Median(regional[i]):0;}
|
||||||
frame.SpatialLoss=frame.RegionLoss.Max();
|
frame.SpatialLoss=frame.RegionLoss.Max();
|
||||||
|
|
|
||||||
|
|
@ -35,9 +35,12 @@ public sealed class Frame
|
||||||
public double CloudSignificance {get;set;}
|
public double CloudSignificance {get;set;}
|
||||||
public double ReferenceConfidence {get;set;}
|
public double ReferenceConfidence {get;set;}
|
||||||
public byte[] CloudMask {get;set;}=[];
|
public byte[] CloudMask {get;set;}=[];
|
||||||
|
// Pink overlay strength (0–255); independent of the two-sided classification mask.
|
||||||
|
public byte[] ExcessSkyMask {get;set;}=[];
|
||||||
[System.Text.Json.Serialization.JsonIgnore] public float[] SkyMap {get;set;}=[];
|
[System.Text.Json.Serialization.JsonIgnore] public float[] SkyMap {get;set;}=[];
|
||||||
[System.Text.Json.Serialization.JsonIgnore] public float[] SkyNoise {get;set;}=[];
|
[System.Text.Json.Serialization.JsonIgnore] public float[] SkyNoise {get;set;}=[];
|
||||||
[System.Text.Json.Serialization.JsonIgnore] public double[] ForcedFlux {get;set;}=[];
|
[System.Text.Json.Serialization.JsonIgnore] public double[] ForcedFlux {get;set;}=[];
|
||||||
|
[System.Text.Json.Serialization.JsonIgnore] public double[] MatchedShape {get;set;}=[];
|
||||||
[System.Text.Json.Serialization.JsonIgnore] public string ForcedReferenceId {get;set;}="";
|
[System.Text.Json.Serialization.JsonIgnore] public string ForcedReferenceId {get;set;}="";
|
||||||
[System.Text.Json.Serialization.JsonIgnore] public bool CacheDirty {get;set;}
|
[System.Text.Json.Serialization.JsonIgnore] public bool CacheDirty {get;set;}
|
||||||
public double Score {get;set;}
|
public double Score {get;set;}
|
||||||
|
|
@ -67,7 +70,7 @@ public sealed class Frame
|
||||||
}
|
}
|
||||||
public sealed class Project
|
public sealed class Project
|
||||||
{
|
{
|
||||||
public const string EngineVersion="0.2.0-spatial-reference-1";
|
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;}="";
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
|
|
|
||||||
|
|
@ -64,12 +64,12 @@ public sealed class Analyzer
|
||||||
Directory.CreateDirectory(System.IO.Path.Combine(directory,"previews"));int done=0;
|
Directory.CreateDirectory(System.IO.Path.Combine(directory,"previews"));int done=0;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
int activeWorkers=workers<=0?ResourcePolicy.DefaultWorkers:Math.Clamp(workers,1,4);
|
int activeWorkers=workers<=0?ResourcePolicy.DefaultWorkers:Math.Clamp(workers,1,ResourcePolicy.DefaultWorkers);
|
||||||
await Parallel.ForEachAsync(frames,new ParallelOptions{MaxDegreeOfParallelism=activeWorkers,CancellationToken=ct},async(f,token)=>
|
await Parallel.ForEachAsync(frames,new ParallelOptions{MaxDegreeOfParallelism=activeWorkers,CancellationToken=ct},async(f,token)=>
|
||||||
{
|
{
|
||||||
if(f.Error==""&&(!f.Measured||!File.Exists(ProjectStore.PreviewPath(directory,f))))
|
if(f.Error==""&&(!f.Measured||!File.Exists(ProjectStore.PreviewPath(directory,f))))
|
||||||
{
|
{
|
||||||
await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token,message=>progress?.Report(new(done,frames.Count,message,f.Name)));
|
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),token,message=>progress?.Report(new(done,frames.Count,message,f.Name)));
|
||||||
try{var image=Fits.Read(f.Path,token);if(!f.Measured)foreach(var detector in Detectors)detector.Measure(f,image,token);Fits.Preview(image,ProjectStore.PreviewPath(directory,f),f);}
|
try{var image=Fits.Read(f.Path,token);if(!f.Measured)foreach(var detector in Detectors)detector.Measure(f,image,token);Fits.Preview(image,ProjectStore.PreviewPath(directory,f),f);}
|
||||||
catch(Exception e)when(e is not (OperationCanceledException or OutOfMemoryException or ResourcePressureException)){f.Error=e.Message;f.Measured=false;}
|
catch(Exception e)when(e is not (OperationCanceledException or OutOfMemoryException or ResourcePressureException)){f.Error=e.Message;f.Measured=false;}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,10 +4,11 @@ namespace AstroFrame.Engine;
|
||||||
public static class ResourcePolicy
|
public static class ResourcePolicy
|
||||||
{
|
{
|
||||||
public const long GiB=1024L*1024*1024;
|
public const long GiB=1024L*1024*1024;
|
||||||
public const long ProcessLimit=6*GiB;
|
public static long ProcessLimit=>MemoryBudget(PhysicalMemory().Total);
|
||||||
public const long HeapLimit=3*GiB;
|
public static int DefaultWorkers=>WorkerLimit(Environment.ProcessorCount);
|
||||||
public static int DefaultWorkers=>Math.Clamp(Environment.ProcessorCount-2,1,4);
|
public static int WorkerLimit(int processors)=>Math.Clamp(processors-2,1,16);
|
||||||
public const long FrameBudget=256L*1024*1024;
|
public static long MemoryBudget(long total)=>total>0?Math.Max(0,total-Reserve(total))/65536*65536:GiB;
|
||||||
|
public static long FrameBudget=>MemoryBudget(PhysicalMemory().Total)/2;
|
||||||
public static long Reserve(long total)=>Math.Min(8*GiB,total/4);
|
public static long Reserve(long total)=>Math.Min(8*GiB,total/4);
|
||||||
[StructLayout(LayoutKind.Sequential)]struct MemoryStatus
|
[StructLayout(LayoutKind.Sequential)]struct MemoryStatus
|
||||||
{
|
{
|
||||||
|
|
@ -24,22 +25,16 @@ public static class ResourcePolicy
|
||||||
}
|
}
|
||||||
var info=GC.GetGCMemoryInfo();return(info.TotalAvailableMemoryBytes,Math.Max(0,info.TotalAvailableMemoryBytes-Process.GetCurrentProcess().WorkingSet64));
|
var info=GC.GetGCMemoryInfo();return(info.TotalAvailableMemoryBytes,Math.Max(0,info.TotalAvailableMemoryBytes-Process.GetCurrentProcess().WorkingSet64));
|
||||||
}
|
}
|
||||||
public static bool CanAnalyze(long total,long available,long estimatedBytes)=>available-estimatedBytes>=Reserve(total);
|
public static bool CanAnalyze(long total,long available,long estimatedBytes)=>total>0&&estimatedBytes>0&&available>=estimatedBytes&&available-estimatedBytes>=Reserve(total);
|
||||||
public static long EstimateFrameBytes(int width,int height,int scale)=>(long)(width/scale)*(height/scale)*16;
|
public static long EstimateFrameBytes(int width,int height,int scale)=>checked((long)(width/scale)*(height/scale)*16+64L*1024*1024);
|
||||||
public static void CheckFrame(int width,int height,int scale)
|
public static void CheckFrame(int width,int height,int scale)
|
||||||
{if(EstimateFrameBytes(width,height,scale)>FrameBudget)throw new InvalidDataException("Image exceeds the 256 MB per-frame analysis budget; this frame needs a memory-bounded detector");}
|
{if(width<1||height<1||scale<1||(long)width*height>100_000_000||EstimateFrameBytes(width,height,scale)>FrameBudget)throw new InvalidDataException("Image exceeds the safe per-frame budget for this computer's physical RAM");}
|
||||||
public static async Task WaitForHeadroom(long estimate,CancellationToken ct,Action<string>? report=null)
|
static readonly MemoryAdmission admission=new(() =>
|
||||||
{
|
{
|
||||||
for(int i=0;i<20;i++)
|
var(total,available)=PhysicalMemory();using var process=Process.GetCurrentProcess();
|
||||||
{
|
return(total,Math.Min(available,Math.Max(0,MemoryBudget(total)-process.PrivateMemorySize64)+Reserve(total)));
|
||||||
ct.ThrowIfCancellationRequested();using var process=Process.GetCurrentProcess();
|
});
|
||||||
if(process.PrivateMemorySize64>ProcessLimit*3/4)throw new ResourcePressureException("Analysis stopped before reaching the 6 GB process limit; completed measurements will be saved");
|
public static Task<IDisposable> Acquire(long estimate,CancellationToken ct,Action<string>? report=null)=>admission.Acquire(estimate,ct,report);
|
||||||
var(total,available)=PhysicalMemory();if(total>0&&CanAnalyze(total,available,estimate))return;
|
|
||||||
report?.Invoke($"Paused for RAM headroom · {available/(double)GiB:0.0} GB available · reserving {Reserve(total)/(double)GiB:0.0} GB");
|
|
||||||
await Task.Delay(1000,ct);
|
|
||||||
}
|
|
||||||
throw new ResourcePressureException("Physical RAM is busy. Analysis stopped safely after waiting for headroom; completed measurements were saved. Resume when other applications have released memory.");
|
|
||||||
}
|
|
||||||
[StructLayout(LayoutKind.Sequential)]struct BasicLimits
|
[StructLayout(LayoutKind.Sequential)]struct BasicLimits
|
||||||
{public long ProcessTime,JobTime;public uint Flags;public UIntPtr MinWorkingSet,MaxWorkingSet;public uint ActiveProcessLimit;public UIntPtr Affinity;public uint Priority,Scheduling;}
|
{public long ProcessTime,JobTime;public uint Flags;public UIntPtr MinWorkingSet,MaxWorkingSet;public uint ActiveProcessLimit;public UIntPtr Affinity;public uint Priority,Scheduling;}
|
||||||
[StructLayout(LayoutKind.Sequential)]struct IoCounters{public ulong ReadOps,WriteOps,OtherOps,ReadBytes,WriteBytes,OtherBytes;}
|
[StructLayout(LayoutKind.Sequential)]struct IoCounters{public ulong ReadOps,WriteOps,OtherOps,ReadBytes,WriteBytes,OtherBytes;}
|
||||||
|
|
@ -56,10 +51,43 @@ public static class ResourcePolicy
|
||||||
if(!OperatingSystem.IsWindows())return false;
|
if(!OperatingSystem.IsWindows())return false;
|
||||||
job=CreateJobObject(IntPtr.Zero,null);if(job==IntPtr.Zero)throw new InvalidOperationException("Cannot create the memory-limit job: "+Marshal.GetLastWin32Error());
|
job=CreateJobObject(IntPtr.Zero,null);if(job==IntPtr.Zero)throw new InvalidOperationException("Cannot create the memory-limit job: "+Marshal.GetLastWin32Error());
|
||||||
var limits=new ExtendedLimits{Basic=new(){Flags=0x100},ProcessMemory=new UIntPtr((ulong)ProcessLimit)};uint size=(uint)Marshal.SizeOf<ExtendedLimits>();
|
var limits=new ExtendedLimits{Basic=new(){Flags=0x100},ProcessMemory=new UIntPtr((ulong)ProcessLimit)};uint size=(uint)Marshal.SizeOf<ExtendedLimits>();
|
||||||
if(!SetInformationJobObject(job,9,ref limits,size)||!AssignProcessToJobObject(job,Process.GetCurrentProcess().Handle))throw new InvalidOperationException("Cannot enforce the 6 GB process limit: "+Marshal.GetLastWin32Error());
|
if(!SetInformationJobObject(job,9,ref limits,size)||!AssignProcessToJobObject(job,Process.GetCurrentProcess().Handle))throw new InvalidOperationException("Cannot enforce the physical RAM process limit: "+Marshal.GetLastWin32Error());
|
||||||
WindowsLimitEnforced=QueryInformationJobObject(job,9,out var actual,size,out _)&&actual.ProcessMemory.ToUInt64()==(ulong)ProcessLimit;
|
WindowsLimitEnforced=QueryInformationJobObject(job,9,out var actual,size,out _)&&actual.ProcessMemory.ToUInt64()==(ulong)ProcessLimit;
|
||||||
if(!WindowsLimitEnforced)throw new InvalidOperationException("Cannot verify the 6 GB process memory limit");
|
if(!WindowsLimitEnforced)throw new InvalidOperationException("Cannot verify the physical RAM process memory limit");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Reserve each in-flight frame atomically. Available RAM is sampled for every admission,
|
||||||
|
// so workers cannot all spend the same headroom. Counting full active reservations is
|
||||||
|
// deliberately conservative even after their allocations appear in OS memory statistics.
|
||||||
|
public sealed class MemoryAdmission(Func<(long Total,long Available)> memory)
|
||||||
|
{
|
||||||
|
readonly object gate=new();long reserved;
|
||||||
|
public long ReservedBytes {get{lock(gate)return reserved;}}
|
||||||
|
public async Task<IDisposable> Acquire(long estimate,CancellationToken ct,Action<string>? report=null)
|
||||||
|
{
|
||||||
|
if(estimate<=0)throw new ArgumentOutOfRangeException(nameof(estimate));
|
||||||
|
int idleWaits=0,waits=0;
|
||||||
|
while(true)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var(total,available)=memory();
|
||||||
|
if(estimate>ResourcePolicy.MemoryBudget(total))throw new ResourcePressureException("This frame exceeds the safe physical RAM budget; completed measurements will be saved.");
|
||||||
|
lock(gate)
|
||||||
|
{
|
||||||
|
if(ResourcePolicy.CanAnalyze(total,available,checked(estimate+reserved)))
|
||||||
|
{reserved+=estimate;return new Lease(this,estimate);}
|
||||||
|
idleWaits=reserved==0?idleWaits+1:0;
|
||||||
|
}
|
||||||
|
if(waits++%10==0)report?.Invoke($"Paused for RAM headroom · {available/(double)ResourcePolicy.GiB:0.0} GB available · reserving {ResourcePolicy.Reserve(total)/(double)ResourcePolicy.GiB:0.0} GB");
|
||||||
|
if(idleWaits>=200)throw new ResourcePressureException("Physical RAM is busy. Analysis stopped safely after waiting for headroom; completed measurements were saved. Resume when other applications have released memory.");
|
||||||
|
await Task.Delay(100,ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sealed class Lease(MemoryAdmission owner,long bytes):IDisposable
|
||||||
|
{
|
||||||
|
int disposed;
|
||||||
|
public void Dispose(){if(Interlocked.Exchange(ref disposed,1)==0)lock(owner.gate)owner.reserved-=bytes;}
|
||||||
|
}
|
||||||
|
}
|
||||||
public sealed class ResourcePressureException(string message):IOException(message);
|
public sealed class ResourcePressureException(string message):IOException(message);
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,8 @@ public static class SkyModel
|
||||||
int col=Math.Min((int)u,Columns-2),row=Math.Min((int)v,Rows-2);double dx=u-col,dy=v-row;
|
int col=Math.Min((int)u,Columns-2),row=Math.Min((int)v,Rows-2);double dx=u-col,dy=v-row;
|
||||||
return (map[row*Columns+col]*(1-dx)+map[row*Columns+col+1]*dx)*(1-dy)+(map[(row+1)*Columns+col]*(1-dx)+map[(row+1)*Columns+col+1]*dx)*dy;
|
return (map[row*Columns+col]*(1-dx)+map[row*Columns+col+1]*dx)*(1-dy)+(map[(row+1)*Columns+col]*(1-dx)+map[(row+1)*Columns+col+1]*dx)*dy;
|
||||||
}
|
}
|
||||||
public static double[] Aligned(Frame f)
|
public static double[] Aligned(Frame f)=>Detrend(AlignedBackground(f));
|
||||||
|
public static double[] AlignedBackground(Frame f)
|
||||||
{
|
{
|
||||||
double[] map=Enumerable.Repeat(double.NaN,Count).ToArray();if(f.Alignment.Length!=4||f.SkyMap.Length!=Count)return map;
|
double[] map=Enumerable.Repeat(double.NaN,Count).ToArray();if(f.Alignment.Length!=4||f.SkyMap.Length!=Count)return map;
|
||||||
var a=f.Alignment;double aspect=(double)f.Height/f.Width;
|
var a=f.Alignment;double aspect=(double)f.Height/f.Width;
|
||||||
|
|
@ -35,38 +36,61 @@ public static class SkyModel
|
||||||
double u=a[0]*x-a[1]*y*aspect+a[2],v=(a[1]*x+a[0]*y*aspect+a[3])/aspect;
|
double u=a[0]*x-a[1]*y*aspect+a[2],v=(a[1]*x+a[0]*y*aspect+a[3])/aspect;
|
||||||
if(u>.025&&u<.975&&v>.025&&v<.975)map[i]=Sample(f.SkyMap,u,v);
|
if(u>.025&&u<.975&&v>.025&&v<.975)map[i]=Sample(f.SkyMap,u,v);
|
||||||
}
|
}
|
||||||
return Detrend(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[] Solve(double[,] m)
|
static double[] Basis(int i,bool quadratic)
|
||||||
{
|
{
|
||||||
for(int k=0;k<3;k++)
|
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];
|
||||||
int pivot=k;for(int r=k+1;r<3;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];
|
|
||||||
for(int c=k;c<4;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;
|
|
||||||
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];}
|
|
||||||
}
|
}
|
||||||
return [m[0,3],m[1,3],m[2,3]];
|
/// <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)
|
||||||
|
{
|
||||||
|
int n=m.GetLength(0);
|
||||||
|
for(int k=0;k<n;k++)
|
||||||
|
{
|
||||||
|
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){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<=n;c++)(m[k,c],m[pivot,c])=(m[pivot,c],m[k,c]);
|
||||||
|
double divisor=m[k,k];for(int c=k;c<=n;c++)m[k,c]/=divisor;
|
||||||
|
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 Enumerable.Range(0,n).Select(r=>m[r,n]).ToArray();
|
||||||
}
|
}
|
||||||
public static int LargestComponent(bool[] mask)
|
public static int LargestComponent(bool[] mask)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
88
src/AstroFrame.Engine/SkyOverlay.cs
Normal file
88
src/AstroFrame.Engine/SkyOverlay.cs
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
namespace AstroFrame.Engine;
|
||||||
|
|
||||||
|
/// <summary>Display excess sky brightness without calling darker residuals cloud glow.</summary>
|
||||||
|
public static class SkyOverlay
|
||||||
|
{
|
||||||
|
public sealed class Reference(double[] background,double[] scatter,double noise)
|
||||||
|
{
|
||||||
|
public byte[] Measure(Frame frame)=>ExcessMask(Residual(SkyModel.AlignedBackground(frame).Select((v,j)=>v-background[j]).ToArray(),noise),scatter);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cloud glow is one-sided contamination of the local sky. An asymmetric fit
|
||||||
|
// gives clear cells more influence than bright patches when removing the
|
||||||
|
// offset/gradient, instead of introducing positive residuals in dark corners.
|
||||||
|
static double[] Residual(double[] values,double noise)
|
||||||
|
{
|
||||||
|
if(values.Count(double.IsFinite)<12)return Enumerable.Repeat(double.NaN,SkyModel.Count).ToArray();
|
||||||
|
double[] coefficients=[Robust.Median(values),0,0];noise=Math.Max(.1,noise);
|
||||||
|
for(int iteration=0;iteration<80;iteration++)
|
||||||
|
{
|
||||||
|
double[,] system=new double[3,4];
|
||||||
|
for(int i=0;i<SkyModel.Count;i++)if(double.IsFinite(values[i]))
|
||||||
|
{
|
||||||
|
double[] v=[1,(i%SkyModel.Columns+.5)/SkyModel.Columns-.5,(i/SkyModel.Columns+.5)/SkyModel.Rows-.5];
|
||||||
|
double residual=values[i]-v[0]*coefficients[0]-v[1]*coefficients[1]-v[2]*coefficients[2];
|
||||||
|
double weight=(residual>=0?.15:.85)/Math.Max(noise,Math.Abs(residual));
|
||||||
|
for(int r=0;r<3;r++){for(int c=0;c<3;c++)system[r,c]+=weight*v[r]*v[c];system[r,3]+=weight*v[r]*values[i];}
|
||||||
|
}
|
||||||
|
var fitted=SkyModel.Solve(system);double change=fitted.Zip(coefficients,(a,b)=>Math.Abs(a-b)).Max();coefficients=fitted;
|
||||||
|
if(change<.01)break;
|
||||||
|
}
|
||||||
|
return values.Select((v,i)=>v-coefficients[0]-coefficients[1]*((i%SkyModel.Columns+.5)/SkyModel.Columns-.5)-coefficients[2]*((i/SkyModel.Columns+.5)/SkyModel.Rows-.5)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Reference? CreateReference(IEnumerable<Frame> frames,CancellationToken ct)
|
||||||
|
{
|
||||||
|
var clean=frames.ToArray();if(clean.Length==0)return null;
|
||||||
|
List<double[]> maps=[];foreach(var f in clean){ct.ThrowIfCancellationRequested();maps.Add(SkyModel.AlignedBackground(f));}
|
||||||
|
double[] median=Enumerable.Range(0,SkyModel.Count).Select(j=>maps.Any(m=>double.IsFinite(m[j]))?Robust.Median(maps.Select(m=>m[j])):double.NaN).ToArray();
|
||||||
|
double floor=Math.Max(.1,Robust.Median(clean.Select(f=>f.Noise))*.08);
|
||||||
|
List<double[]> residuals=[];foreach(var map in maps){ct.ThrowIfCancellationRequested();residuals.Add(Residual(map.Select((v,j)=>v-median[j]).ToArray(),floor));}
|
||||||
|
double[] scatter=Enumerable.Range(0,SkyModel.Count).Select(j=>Math.Max(floor,Robust.Mad(residuals.Select(m=>m[j])))).ToArray();
|
||||||
|
return new(median,scatter,floor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ExcessMask(double[] residual,double[] scatter)
|
||||||
|
{
|
||||||
|
if(residual.Length!=SkyModel.Count||scatter.Length!=SkyModel.Count)return [];
|
||||||
|
// Use both reference scatter and the structure's dynamic range to exclude
|
||||||
|
// weak background-fit residuals. Saturate locally significant structure
|
||||||
|
// quickly so a bright cloud cannot wash out a second, fainter cloud.
|
||||||
|
double scale=Math.Max(.1,Robust.Quantile(residual.Where(v=>v>0),.95));
|
||||||
|
return residual.Select((v,j)=>
|
||||||
|
{
|
||||||
|
double threshold=Math.Max(5*scatter[j],scale*.15);
|
||||||
|
if(!double.IsFinite(v)||!double.IsFinite(threshold)||threshold<=0||v<=threshold)return (byte)0;
|
||||||
|
double strength=v/(2*threshold);
|
||||||
|
return (byte)Math.Clamp(Math.Round(255*strength),1,255);
|
||||||
|
}).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Older projects have only the two-sided classification mask. Reconstruct the
|
||||||
|
// display from their catalogs without saving or changing any measurements.
|
||||||
|
public static byte[] LoadMask(string directory,Frame frame,IReadOnlyList<Frame> frames,CancellationToken ct)
|
||||||
|
{
|
||||||
|
if(frame.ExcessSkyMask.Length==SkyModel.Count)return frame.ExcessSkyMask;
|
||||||
|
if(frame.Alignment.Length!=4)return [];
|
||||||
|
Frame? Read(Frame source)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var copy=new Frame{Id=source.Id,Length=source.Length,Modified=source.Modified,Width=source.Width,Height=source.Height,Alignment=source.Alignment,Noise=source.Noise};
|
||||||
|
return ProjectStore.LoadCatalog(directory,copy)&©.SkyMap.Length==SkyModel.Count?copy:null;
|
||||||
|
}
|
||||||
|
var selected=Read(frame);if(selected==null)return [];
|
||||||
|
var clean=frames.Where(f=>f.Session==frame.Session&&f.Measured&&f.Error==""&&f.Alignment.Length==4&&f.AdditionalMeasurements.GetValueOrDefault("Clear reference member")>0).ToArray();
|
||||||
|
if(clean.Length==0)return [];
|
||||||
|
List<Frame> references=[];
|
||||||
|
foreach(var referenceFrame in clean)
|
||||||
|
{
|
||||||
|
var reference=Read(referenceFrame);
|
||||||
|
// An incomplete reference would produce a different mask; show unavailable instead.
|
||||||
|
if(reference==null)return [];
|
||||||
|
references.Add(reference);
|
||||||
|
}
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var overlay=CreateReference(references,ct);
|
||||||
|
ct.ThrowIfCancellationRequested();return overlay?.Measure(selected)??[];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -32,7 +32,7 @@ public static class SpatialReference
|
||||||
ct.ThrowIfCancellationRequested();
|
ct.ThrowIfCancellationRequested();
|
||||||
if(f.Alignment.Length==4&&(f.ForcedReferenceId!=apertureReference||f.ForcedFlux.Length!=stars))
|
if(f.Alignment.Length==4&&(f.ForcedReferenceId!=apertureReference||f.ForcedFlux.Length!=stars))
|
||||||
{
|
{
|
||||||
await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),ct,message=>progress?.Report(new(done,frames.Count,message,f.Name)));
|
using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,f.Bayer!=""?2:1),ct,message=>progress?.Report(new(done,frames.Count,message,f.Name)));
|
||||||
try{f.ForcedFlux=Matching.ForcedFlux(anchor,f,Fits.Read(f.Path,ct));f.ForcedReferenceId=apertureReference;f.CacheDirty=true;}
|
try{f.ForcedFlux=Matching.ForcedFlux(anchor,f,Fits.Read(f.Path,ct));f.ForcedReferenceId=apertureReference;f.CacheDirty=true;}
|
||||||
catch(Exception e)when(e is not (OperationCanceledException or OutOfMemoryException or ResourcePressureException)){f.Error=e.Message;}
|
catch(Exception e)when(e is not (OperationCanceledException or OutOfMemoryException or ResourcePressureException)){f.Error=e.Message;}
|
||||||
}
|
}
|
||||||
|
|
@ -55,6 +55,18 @@ public static class SpatialReference
|
||||||
if(ratios.Count>=20)f.Transparency=Math.Max(0,Robust.Median(ratios));
|
if(ratios.Count>=20)f.Transparency=Math.Max(0,Robust.Median(ratios));
|
||||||
for(int r=0;r<12;r++){f.RegionMatches[r]=regional[r].Count;if(regional[r].Count>=5)f.RegionFlux[r]=Robust.Median(regional[r]);}
|
for(int r=0;r<12;r++){f.RegionMatches[r]=regional[r].Count;if(regional[r].Count>=5)f.RegionFlux[r]=Robust.Median(regional[r]);}
|
||||||
f.AdditionalMeasurements["Forced flux samples"]=ratios.Count;
|
f.AdditionalMeasurements["Forced flux samples"]=ratios.Count;
|
||||||
|
// Compare the same bright reference stars, avoiding changes in the
|
||||||
|
// independently selected detection cohort. Missing/uncertain pairs
|
||||||
|
// cannot dismiss an existing morphology warning.
|
||||||
|
var shapePeers=Nearby(a,clean,f).Where(x=>x.MatchedShape.Length==stars).ToArray();
|
||||||
|
double[] normalShape=Enumerable.Range(0,Math.Min(250,stars)).Select(j=>Robust.Median(shapePeers.Select(x=>x.MatchedShape[j]))).ToArray();
|
||||||
|
var changes=Enumerable.Range(0,Math.Min(250,stars)).Where(j=>
|
||||||
|
f.MatchedShape.Length==stars&&double.IsFinite(f.MatchedShape[j])&&normalShape[j]>0&&normal[j]*anchor.Exposure>=30*anchor.Noise)
|
||||||
|
.Select(j=>f.MatchedShape[j]-normalShape[j]).ToArray();
|
||||||
|
f.AdditionalMeasurements["Matched shape samples"]=changes.Length;
|
||||||
|
f.AdditionalMeasurements["Matched shape reference frames"]=shapePeers.Length;
|
||||||
|
f.AdditionalMeasurements["Matched shape change"]=Robust.Median(changes);
|
||||||
|
f.AdditionalMeasurements["Matched shape uncertainty"]=Math.Max(.005,1.253*Robust.Mad(changes)/Math.Sqrt(Math.Max(1,changes.Length)));
|
||||||
}
|
}
|
||||||
var residuals=clean.Select(i=>Difference(maps[i],reference)).ToArray();
|
var residuals=clean.Select(i=>Difference(maps[i],reference)).ToArray();
|
||||||
double referenceNoise=Robust.Median(clean.Select(i=>a[i].Noise));
|
double referenceNoise=Robust.Median(clean.Select(i=>a[i].Noise));
|
||||||
|
|
@ -62,10 +74,32 @@ public static class SpatialReference
|
||||||
double stability=Math.Min(1,referenceNoise*.5/Math.Max(referenceResidual,.1));
|
double stability=Math.Min(1,referenceNoise*.5/Math.Max(referenceResidual,.1));
|
||||||
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);
|
||||||
|
// 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);
|
||||||
var z=residual.Select((v,j)=>Math.Abs(v)/scatter[j]).ToArray();bool[] mask=z.Select(v=>double.IsFinite(v)&&v>5).ToArray();
|
var z=residual.Select((v,j)=>Math.Abs(v)/scatter[j]).ToArray();bool[] mask=z.Select(v=>double.IsFinite(v)&&v>5).ToArray();
|
||||||
|
// The two-sided residual remains classification evidence. Pink display
|
||||||
|
// cells identify excess sky brightness, not the compensating dark residual.
|
||||||
|
f.ExcessSkyMask=overlay?.Measure(f)??[];
|
||||||
|
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 connected coverage"]=positive.Length==SkyModel.Count?(double)SkyModel.LargestComponent(positive)/Math.Max(valid,1):0;
|
||||||
|
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);
|
||||||
|
|
@ -77,6 +111,57 @@ public static class SpatialReference
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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&&
|
||||||
|
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();
|
||||||
|
frame.AdditionalMeasurements[name+" samples"]=indices.Length;
|
||||||
|
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[name+" flux ratio"]=0;frame.AdditionalMeasurements[name+" flux deviation"]=0;
|
||||||
|
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]));
|
||||||
|
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();
|
||||||
|
double baseline=Robust.Median(comparisons);if(comparisons.Length<12||baseline<=0)return;
|
||||||
|
// Radius-4 aperture (49 pixels) and radius-6..8 median annulus.
|
||||||
|
// Include background-estimation uncertainty, rather than interpreting a
|
||||||
|
// noisy local flux estimate as confident extinction.
|
||||||
|
const double varianceFactor=49+49*49*Math.PI/(2*88);
|
||||||
|
double LocalNoise(int j)
|
||||||
|
{
|
||||||
|
var s=anchor.Stars[j];var a=frame.Alignment;double aspect=(double)anchor.Height/anchor.Width;
|
||||||
|
if(frame.SkyNoise.Length!=SkyModel.Count||a.Length!=4)return frame.Noise;
|
||||||
|
double x=a[0]*s.X-a[1]*s.Y*aspect+a[2],y=(a[1]*s.X+a[0]*s.Y*aspect+a[3])/aspect;
|
||||||
|
return Math.Max(frame.Noise,SkyModel.Sample(frame.SkyNoise,x,y));
|
||||||
|
}
|
||||||
|
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 measured=Flux(frame);
|
||||||
|
frame.AdditionalMeasurements[name+" flux ratio"]=measured/baseline;
|
||||||
|
frame.AdditionalMeasurements[name+" flux deviation"]=(baseline-measured)/spread;
|
||||||
|
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)
|
||||||
|
.OrderBy(f=>Math.Abs((f.Timestamp.GetValueOrDefault()-selected.Timestamp.GetValueOrDefault()).TotalSeconds)).Take(40);
|
||||||
static double Amplitude(double[] map)=>Robust.Quantile(map.Select(Math.Abs),.95);
|
static double Amplitude(double[] map)=>Robust.Quantile(map.Select(Math.Abs),.95);
|
||||||
static double[] Difference(double[] map,double[] reference)=>SkyModel.Detrend(map.Select((v,j)=>v-reference[j]).ToArray());
|
static double[] Difference(double[] map,double[] reference)=>SkyModel.Detrend(map.Select((v,j)=>v-reference[j]).ToArray());
|
||||||
static double[] MedianMap(double[][] maps)=>Enumerable.Range(0,SkyModel.Count).Select(j=>maps.Any(m=>double.IsFinite(m[j]))?Robust.Median(maps.Select(m=>m[j])):double.NaN).ToArray();
|
static double[] MedianMap(double[][] maps)=>Enumerable.Range(0,SkyModel.Count).Select(j=>maps.Any(m=>double.IsFinite(m[j]))?Robust.Median(maps.Select(m=>m[j])):double.NaN).ToArray();
|
||||||
|
|
|
||||||
|
|
@ -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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,14 @@ using Velopack.Sources;
|
||||||
|
|
||||||
int passed = 0;
|
int passed = 0;
|
||||||
void Check(bool value, string label) { if (!value) throw new Exception(label); Console.WriteLine("PASS " + label); passed++; }
|
void Check(bool value, string label) { if (!value) throw new Exception(label); Console.WriteLine("PASS " + label); passed++; }
|
||||||
|
var viewport=new PreviewViewport();var area=new Avalonia.Rect(0,26,600,500);var image=new Avalonia.Size(800,600);var anchor=new Avalonia.Point(365,250);
|
||||||
|
var beforeZoom=viewport.ImageRect(area,image);viewport.ZoomAt(3,anchor,area,image);var afterZoom=viewport.ImageRect(area,image);
|
||||||
|
Check(Math.Abs((anchor.X-beforeZoom.X)/beforeZoom.Width-(anchor.X-afterZoom.X)/afterZoom.Width)<1e-10&&Math.Abs((anchor.Y-beforeZoom.Y)/beforeZoom.Height-(anchor.Y-afterZoom.Y)/afterZoom.Height)<1e-10,"zoom preserves the image point under the cursor");
|
||||||
|
var centerBefore=(area.Center.X-afterZoom.X)/afterZoom.Width;var resized=viewport.ImageRect(new Avalonia.Rect(0,26,300,250),image);
|
||||||
|
Check(Math.Abs(centerBefore-(150-resized.X)/resized.Width)<1e-10,"resizing preserves the normalized image position");
|
||||||
|
viewport.ZoomAt(1000,area.Center,area,image);viewport.ZoomAt(1000,area.Center,area,image);Check(viewport.Zoom==16,"zoom stays bounded at maximum magnification");
|
||||||
|
viewport.Drag(new Avalonia.Vector(1e6,-1e6),area,image);Check(Math.Abs(viewport.Pan.X)<viewport.Zoom/2&&Math.Abs(viewport.Pan.Y)<viewport.Zoom/2,"drag limits keep the image reachable");
|
||||||
|
viewport.Reset();Check(viewport.Zoom==1&&viewport.Pan==default,"reset restores fitted and centered image");
|
||||||
var temp = Path.Combine(Path.GetTempPath(), "AstroFrame-update-tests-" + Guid.NewGuid());
|
var temp = Path.Combine(Path.GetTempPath(), "AstroFrame-update-tests-" + Guid.NewGuid());
|
||||||
Directory.CreateDirectory(temp);
|
Directory.CreateDirectory(temp);
|
||||||
try
|
try
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
|
|
@ -7,8 +7,8 @@
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<None Update="Fixtures/*.json" CopyToOutputDirectory="PreserveNewest" />
|
||||||
<ProjectReference Include="../../src/AstroFrame.Engine/AstroFrame.Engine.csproj" />
|
<ProjectReference Include="../../src/AstroFrame.Engine/AstroFrame.Engine.csproj" />
|
||||||
<RuntimeHostConfigurationOption Include="System.GC.HeapHardLimit" Value="3221225472" />
|
|
||||||
<RuntimeHostConfigurationOption Include="System.GC.Server" Value="false" />
|
<RuntimeHostConfigurationOption Include="System.GC.Server" Value="false" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -38,6 +38,18 @@ static class ImageRegression
|
||||||
check(clear.All(f=>f.Automatic==Verdict.Keep),"persistent nebulosity and gradual sky/flux trends remain KEEP in image pipeline");
|
check(clear.All(f=>f.Automatic==Verdict.Keep),"persistent nebulosity and gradual sky/flux trends remain KEEP in image pipeline");
|
||||||
check(cloud.All(f=>f.Automatic==Verdict.Reject),"prolonged moving cloud does not become the local baseline");
|
check(cloud.All(f=>f.Automatic==Verdict.Reject),"prolonged moving cloud does not become the local baseline");
|
||||||
check(cloud.All(f=>f.CloudMask.Any(v=>v>0)&&f.Evidence.Any(e=>e.Metric=="Cloud structure")),"cloud masks and spatial explanations survive the full image pipeline");
|
check(cloud.All(f=>f.CloudMask.Any(v=>v>0)&&f.Evidence.Any(e=>e.Metric=="Cloud structure")),"cloud masks and spatial explanations survive the full image pipeline");
|
||||||
|
bool Localized(Frame f)
|
||||||
|
{
|
||||||
|
int n=frames.IndexOf(f);double center=.22+(n%9)*.045,aspect=(double)f.Height/f.Width;var a=f.Alignment;
|
||||||
|
var cells=Enumerable.Range(0,SkyModel.Count).Select(i=>
|
||||||
|
{
|
||||||
|
double x=(i%SkyModel.Columns+.5)/SkyModel.Columns,y=(i/SkyModel.Columns+.5)/SkyModel.Rows;
|
||||||
|
return(i,Y:(a[1]*x+a[0]*y*aspect+a[3])/aspect);
|
||||||
|
}).Where(c=>c.Y>.05&&c.Y<.95).ToArray();
|
||||||
|
var core=cells.Where(c=>Math.Abs(c.Y-center)<.05).ToArray();var clearSky=cells.Where(c=>Math.Abs(c.Y-center)>.24).ToArray();
|
||||||
|
return f.ExcessSkyMask.Length==SkyModel.Count&&core.Length>0&&core.Count(c=>f.ExcessSkyMask[c.i]>=128)>=core.Length*.85&&clearSky.Length>0&&clearSky.Count(c=>f.ExcessSkyMask[c.i]>0)<=clearSky.Length*.1;
|
||||||
|
}
|
||||||
|
check(cloud.All(Localized),"image pipeline highlights physical cloud cores while leaving distant clear sky unshaded");
|
||||||
check(frames[18].Automatic==Verdict.Review,"modest transient sky structure without stellar loss routes to REVIEW, preserving conservative rejection");
|
check(frames[18].Automatic==Verdict.Review,"modest transient sky structure without stellar loss routes to REVIEW, preserving conservative rejection");
|
||||||
var reference=frames.First(f=>f.Id==cloud[0].ReferenceId);var image=Fits.Read(cloud[0].Path);
|
var reference=frames.First(f=>f.Id==cloud[0].ReferenceId);var image=Fits.Read(cloud[0].Path);
|
||||||
var vanished=reference.Stars[0] with{Flux=1};reference.Stars=[vanished];var forced=Matching.ForcedFlux(reference,cloud[0],image);
|
var vanished=reference.Stars[0] with{Flux=1};reference.Stars=[vanished];var forced=Matching.ForcedFlux(reference,cloud[0],image);
|
||||||
|
|
@ -48,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);
|
||||||
|
|
|
||||||
77
tests/AstroFrame.Validation/OverlayRegression.cs
Normal file
77
tests/AstroFrame.Validation/OverlayRegression.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
using AstroFrame.Engine;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
static class OverlayRegression
|
||||||
|
{
|
||||||
|
public static void Run(Action<bool,string> check)
|
||||||
|
{
|
||||||
|
var residual=new double[SkyModel.Count];var scatter=Enumerable.Repeat(2.0,SkyModel.Count).ToArray();
|
||||||
|
for(int i=0;i<100;i++)residual[i]=500;
|
||||||
|
residual[100]=100;residual[101]=-500;residual[102]=9;residual[103]=double.NaN;residual[104]=50;
|
||||||
|
var strengths=SkyOverlay.ExcessMask(residual,scatter);
|
||||||
|
check(strengths[0]==255&&strengths[100]>=128&&strengths[101]==0&&strengths[102]==0&&strengths[103]==0&&strengths[104]==0,"fainter cloud structure stays visible while weak, dark and invalid residuals are unshaded");
|
||||||
|
RealFrames(check);
|
||||||
|
string directory=Path.Combine(Path.GetTempPath(),"AstroFrame-overlay-"+Guid.NewGuid());
|
||||||
|
try
|
||||||
|
{
|
||||||
|
float[] Map(bool cloud)=>Enumerable.Range(0,SkyModel.Count).Select(i=>
|
||||||
|
{
|
||||||
|
double x=(i%SkyModel.Columns+.5)/SkyModel.Columns,y=(i/SkyModel.Columns+.5)/SkyModel.Rows;
|
||||||
|
double nebula=80*Math.Exp(-((x-.45)*(x-.45)+(y-.55)*(y-.55))*35);
|
||||||
|
double glow=cloud?450*Math.Exp(-Math.Pow(y/.18,2))+400*Math.Exp(-Math.Pow((x-.25)/.23,2)-Math.Pow((y-.42)/.16,2)):0;
|
||||||
|
return (float)(1000+75*x+30*y+nebula+glow);
|
||||||
|
}).ToArray();
|
||||||
|
Frame Make(int n,bool cloud=false)=>new()
|
||||||
|
{
|
||||||
|
Id=n.ToString(),Length=100,Modified=200,Width=240,Height=400,Session="same night",Measured=true,
|
||||||
|
SkyMap=Map(cloud),SkyNoise=Enumerable.Repeat(20f,SkyModel.Count).ToArray(),Noise=20,Alignment=[1,0,0,0],
|
||||||
|
Stars=[new(.4,.5,1000,3,.1)],AdditionalMeasurements=new(){{"Clear reference member",cloud?0:1}}
|
||||||
|
};
|
||||||
|
var frames=Enumerable.Range(0,30).Select(n=>Make(n)).ToList();var selected=Make(30,true);
|
||||||
|
selected.CloudMask=Enumerable.Repeat((byte)1,SkyModel.Count).ToArray();selected.CloudCoverage=.9;selected.Automatic=Verdict.Reject;selected.Override=Verdict.Keep;selected.Note="Human decision";
|
||||||
|
frames.Add(selected);
|
||||||
|
// Other sessions must not contribute to the reference, even without a readable catalog.
|
||||||
|
frames.Add(new(){Id="other",Session="other night",Measured=true,Alignment=[1,0,0,0],AdditionalMeasurements=new(){{"Clear reference member",1}}});
|
||||||
|
var project=new Project{Frames=frames,Complete=true};ProjectStore.Save(project,directory);
|
||||||
|
var files=Directory.GetFiles(directory,"*",SearchOption.AllDirectories);
|
||||||
|
string Hash(string path)=>Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)));
|
||||||
|
var before=files.ToDictionary(path=>path,Hash);
|
||||||
|
var restored=ProjectStore.Load(directory);selected=restored.Frames.Single(f=>f.Id=="30");
|
||||||
|
var mask=SkyOverlay.LoadMask(directory,selected,restored.Frames,CancellationToken.None);
|
||||||
|
var clear=Enumerable.Range(0,SkyModel.Count).Where(i=>(i%SkyModel.Columns+.5)/SkyModel.Columns>.7&&(i/SkyModel.Columns+.5)/SkyModel.Rows>.35&&(i/SkyModel.Columns+.5)/SkyModel.Rows<.6).ToArray();
|
||||||
|
var core=Enumerable.Range(0,SkyModel.Count).Where(i=>(i%SkyModel.Columns+.5)/SkyModel.Columns>.15&&(i%SkyModel.Columns+.5)/SkyModel.Columns<.35&&(i/SkyModel.Columns+.5)/SkyModel.Rows>.35&&(i/SkyModel.Columns+.5)/SkyModel.Rows<.45).ToArray();
|
||||||
|
check(mask.Length==SkyModel.Count&&clear.All(i=>mask[i]==0)&&core.All(i=>mask[i]>0),"legacy overlay follows localized cloud glow instead of the compensating dark sky");
|
||||||
|
check(selected.CloudMask.All(v=>v==1)&&selected.CloudCoverage==.9&&selected.Automatic==Verdict.Reject&&selected.Override==Verdict.Keep&&selected.Note=="Human decision","overlay reconstruction preserves classification evidence and human decisions");
|
||||||
|
check(files.All(path=>before[path]==Hash(path)),"legacy overlay reconstruction leaves the saved project and catalogs byte-identical");
|
||||||
|
selected.ExcessSkyMask=mask;
|
||||||
|
check(SkyOverlay.LoadMask("missing directory",selected,[],CancellationToken.None).SequenceEqual(mask),"newly measured overlays display without reopening reference catalogs");
|
||||||
|
selected.ExcessSkyMask=[];
|
||||||
|
File.Delete(Path.Combine(directory,"catalogs","0-v2.bin"));
|
||||||
|
check(SkyOverlay.LoadMask(directory,selected,restored.Frames,CancellationToken.None).Length==0,"incomplete legacy references never fall back to the misleading two-sided mask");
|
||||||
|
}
|
||||||
|
finally{if(Directory.Exists(directory))Directory.Delete(directory,true);}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed record Sample(string Name,int Width,int Height,double[] Alignment,float[] SkyMap,double[][] CloudRegions,double[][] ClearRegions);
|
||||||
|
sealed record Fixture(double?[] ReferenceBackground,double[] ReferenceScatter,double Noise,Sample[] Samples);
|
||||||
|
static void RealFrames(Action<bool,string> check)
|
||||||
|
{
|
||||||
|
var fixture=JsonSerializer.Deserialize<Fixture>(File.ReadAllText(Path.Combine(AppContext.BaseDirectory,"Fixtures","overlay-backgrounds.json")))!;
|
||||||
|
var reference=new SkyOverlay.Reference(fixture.ReferenceBackground.Select(v=>v??double.NaN).ToArray(),fixture.ReferenceScatter,fixture.Noise);
|
||||||
|
foreach(var sample in fixture.Samples)
|
||||||
|
{
|
||||||
|
var frame=new Frame{Width=sample.Width,Height=sample.Height,Alignment=sample.Alignment,SkyMap=sample.SkyMap};
|
||||||
|
var mask=reference.Measure(frame);var a=sample.Alignment;double aspect=(double)sample.Height/sample.Width;
|
||||||
|
int[] Cells(double[] region)=>Enumerable.Range(0,SkyModel.Count).Where(i=>
|
||||||
|
{
|
||||||
|
double x=(i%SkyModel.Columns+.5)/SkyModel.Columns,y=(i/SkyModel.Columns+.5)/SkyModel.Rows;
|
||||||
|
double u=a[0]*x-a[1]*y*aspect+a[2],v=(a[1]*x+a[0]*y*aspect+a[3])/aspect;
|
||||||
|
return u>region[0]&&u<region[1]&&v>region[2]&&v<region[3];
|
||||||
|
}).ToArray();
|
||||||
|
var clouds=sample.CloudRegions.Select(Cells).ToArray();var clear=sample.ClearRegions.Select(Cells).ToArray();
|
||||||
|
check(clouds.All(cells=>cells.Length>0&&cells.Count(i=>mask[i]>=128)>=cells.Length*.85&&cells.Average(i=>(double)mask[i])>180),$"{sample.Name}: each reported cloud core has clearly visible overlay strength");
|
||||||
|
check(clear.All(cells=>cells.Length>0&&cells.Count(i=>mask[i]>0)<=cells.Length*.1),$"{sample.Name}: dark comparison regions avoid the false corner overlay");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,11 @@ using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
ResourcePolicy.InstallWindowsLimit();
|
ResourcePolicy.InstallWindowsLimit();
|
||||||
|
if(args.Length>0&&args[0]=="quality-regression")
|
||||||
|
{
|
||||||
|
int failed=0;QualityRegression.Run((ok,name)=>{Console.WriteLine($"{(ok?"PASS":"FAIL")} {name}");if(!ok)failed++;});
|
||||||
|
if(failed>0)throw new Exception($"{failed} quality regressions failed");return;
|
||||||
|
}
|
||||||
if(args.Length>0&&args[0]=="preview")
|
if(args.Length>0&&args[0]=="preview")
|
||||||
{
|
{
|
||||||
var plane=PreviewRenderer.Reduce(Fits.Read(Path.GetFullPath(args[1])),3);var pixels=PreviewRenderer.Render(plane);using var writer=new BinaryWriter(File.Create(args[2]));writer.Write(plane.Width);writer.Write(plane.Height);writer.Write(pixels);return;
|
var plane=PreviewRenderer.Reduce(Fits.Read(Path.GetFullPath(args[1])),3);var pixels=PreviewRenderer.Render(plane);using var writer=new BinaryWriter(File.Create(args[2]));writer.Write(plane.Width);writer.Write(plane.Height);writer.Write(pixels);return;
|
||||||
|
|
@ -14,7 +19,7 @@ if(args.Length>0&&args[0]=="profile-workers")
|
||||||
string[] all=Directory.GetFiles(args[1],"*.fit").Order().ToArray();int count=Math.Min(int.Parse(args[2]),all.Length),workers=int.Parse(args[3]);
|
string[] all=Directory.GetFiles(args[1],"*.fit").Order().ToArray();int count=Math.Min(int.Parse(args[2]),all.Length),workers=int.Parse(args[3]);
|
||||||
var files=Enumerable.Range(0,count).Select(i=>all[i*all.Length/count]).ToArray();var summaries=new System.Collections.Concurrent.ConcurrentDictionary<string,int>();var timer=Stopwatch.StartNew();
|
var files=Enumerable.Range(0,count).Select(i=>all[i*all.Length/count]).ToArray();var summaries=new System.Collections.Concurrent.ConcurrentDictionary<string,int>();var timer=Stopwatch.StartNew();
|
||||||
await Parallel.ForEachAsync(files,new ParallelOptions{MaxDegreeOfParallelism=workers},async(path,ct)=>
|
await Parallel.ForEachAsync(files,new ParallelOptions{MaxDegreeOfParallelism=workers},async(path,ct)=>
|
||||||
{var f=Fits.Inspect(path);await ResourcePolicy.WaitForHeadroom(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,2),ct);new StellarDetector().Measure(f,Fits.Read(path,ct),ct);summaries[f.Name]=f.StarCount;});
|
{var f=Fits.Inspect(path);using var memory=await ResourcePolicy.Acquire(ResourcePolicy.EstimateFrameBytes(f.Width,f.Height,2),ct);new StellarDetector().Measure(f,Fits.Read(path,ct),ct);summaries[f.Name]=f.StarCount;});
|
||||||
using var process=Process.GetCurrentProcess();Console.WriteLine(JsonSerializer.Serialize(new{workers,count,elapsedSeconds=timer.Elapsed.TotalSeconds,peakWorkingMiB=process.PeakWorkingSet64/1048576.0,peakPrivateMiB=process.PeakPagedMemorySize64/1048576.0,logicalProcessors=Environment.ProcessorCount,starCounts=summaries.OrderBy(x=>x.Key).Select(x=>x.Value)}));return;
|
using var process=Process.GetCurrentProcess();Console.WriteLine(JsonSerializer.Serialize(new{workers,count,elapsedSeconds=timer.Elapsed.TotalSeconds,peakWorkingMiB=process.PeakWorkingSet64/1048576.0,peakPrivateMiB=process.PeakPagedMemorySize64/1048576.0,logicalProcessors=Environment.ProcessorCount,starCounts=summaries.OrderBy(x=>x.Key).Select(x=>x.Value)}));return;
|
||||||
}
|
}
|
||||||
if(args.Length>0&&args[0]=="resources")
|
if(args.Length>0&&args[0]=="resources")
|
||||||
|
|
@ -42,7 +47,7 @@ if(args.Length>0&&args[0]=="analyze")
|
||||||
var p=await new Analyzer().AnalyzeAsync(source,directory,existing,
|
var p=await new Analyzer().AnalyzeAsync(source,directory,existing,
|
||||||
new DirectProgress(x=>{int pct=x.Total==0?0:x.Done*100/x.Total;if(pct/10!=last){last=pct/10;Console.WriteLine($"{x.Stage}: {x.Done}/{x.Total}");}}),CancellationToken.None);
|
new DirectProgress(x=>{int pct=x.Total==0?0:x.Done*100/x.Total;if(pct/10!=last){last=pct/10;Console.WriteLine($"{x.Stage}: {x.Done}/{x.Total}");}}),CancellationToken.None);
|
||||||
File.WriteAllText(Path.Combine(directory,"decisions.csv"),Export.Manifest(p));
|
File.WriteAllText(Path.Combine(directory,"decisions.csv"),Export.Manifest(p));
|
||||||
using var process=Process.GetCurrentProcess();var report=new {elapsedSeconds=watch.Elapsed.TotalSeconds,peakWorkingMB=process.PeakWorkingSet64/(1024.0*1024),peakCommittedMB=process.PeakPagedMemorySize64/(1024.0*1024),processLimitMB=ResourcePolicy.ProcessLimit/(1024*1024),heapLimitMB=ResourcePolicy.HeapLimit/(1024*1024),windowsLimitEnforced=ResourcePolicy.WindowsLimitEnforced,engine=Project.EngineVersion,validation="Unlabeled exploratory results; no evidence of stack parity",sessions=p.Frames.GroupBy(f=>f.Session).Select(g=>new{session=g.Key,frames=g.Count(),keep=g.Count(f=>f.Effective==Verdict.Keep),review=g.Count(f=>f.Effective==Verdict.Review),reject=g.Count(f=>f.Effective==Verdict.Reject),totalMinutes=g.Sum(f=>f.Exposure)/60,keepMinutes=g.Where(f=>f.Effective==Verdict.Keep).Sum(f=>f.Exposure)/60,stars=Range(g.Select(f=>(double)f.StarCount)),fwhm=Range(g.Select(f=>f.Fwhm)),flux=Range(g.Select(f=>f.Transparency)),matching=Range(g.Select(f=>f.MatchFraction)),causes=g.GroupBy(f=>f.Cause).ToDictionary(x=>x.Key,x=>x.Count())})};
|
using var process=Process.GetCurrentProcess();var report=new {elapsedSeconds=watch.Elapsed.TotalSeconds,peakWorkingMB=process.PeakWorkingSet64/(1024.0*1024),peakCommittedMB=process.PeakPagedMemorySize64/(1024.0*1024),processLimitMB=ResourcePolicy.ProcessLimit/(1024*1024),heapLimitMB=GC.GetGCMemoryInfo().TotalAvailableMemoryBytes/(1024*1024),windowsLimitEnforced=ResourcePolicy.WindowsLimitEnforced,engine=Project.EngineVersion,validation="Unlabeled exploratory results; no evidence of stack parity",sessions=p.Frames.GroupBy(f=>f.Session).Select(g=>new{session=g.Key,frames=g.Count(),keep=g.Count(f=>f.Effective==Verdict.Keep),review=g.Count(f=>f.Effective==Verdict.Review),reject=g.Count(f=>f.Effective==Verdict.Reject),totalMinutes=g.Sum(f=>f.Exposure)/60,keepMinutes=g.Where(f=>f.Effective==Verdict.Keep).Sum(f=>f.Exposure)/60,stars=Range(g.Select(f=>(double)f.StarCount)),fwhm=Range(g.Select(f=>f.Fwhm)),flux=Range(g.Select(f=>f.Transparency)),matching=Range(g.Select(f=>f.MatchFraction)),causes=g.GroupBy(f=>f.Cause).ToDictionary(x=>x.Key,x=>x.Count())})};
|
||||||
string json=JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true});File.WriteAllText(Path.Combine(directory,"report.json"),json);Console.WriteLine(json);return;
|
string json=JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true});File.WriteAllText(Path.Combine(directory,"report.json"),json);Console.WriteLine(json);return;
|
||||||
}
|
}
|
||||||
if(args.Length>0&&args[0]=="benchmark")
|
if(args.Length>0&&args[0]=="benchmark")
|
||||||
|
|
@ -69,6 +74,22 @@ Check(!OperatingSystem.IsWindows()||ResourcePolicy.WindowsLimitEnforced,"Windows
|
||||||
Check(ResourcePolicy.Reserve(32*ResourcePolicy.GiB)==8*ResourcePolicy.GiB,"32 GB machines reserve 8 GB physical RAM");
|
Check(ResourcePolicy.Reserve(32*ResourcePolicy.GiB)==8*ResourcePolicy.GiB,"32 GB machines reserve 8 GB physical RAM");
|
||||||
Check(!ResourcePolicy.CanAnalyze(32*ResourcePolicy.GiB,7*ResourcePolicy.GiB,32*1024*1024),"low physical RAM pauses analysis");
|
Check(!ResourcePolicy.CanAnalyze(32*ResourcePolicy.GiB,7*ResourcePolicy.GiB,32*1024*1024),"low physical RAM pauses analysis");
|
||||||
Check(ResourcePolicy.CanAnalyze(32*ResourcePolicy.GiB,12*ResourcePolicy.GiB,32*1024*1024),"sufficient RAM allows bounded analysis");
|
Check(ResourcePolicy.CanAnalyze(32*ResourcePolicy.GiB,12*ResourcePolicy.GiB,32*1024*1024),"sufficient RAM allows bounded analysis");
|
||||||
|
Check(ResourcePolicy.MemoryBudget(32*ResourcePolicy.GiB)==24*ResourcePolicy.GiB&&ResourcePolicy.MemoryBudget(64*ResourcePolicy.GiB)==56*ResourcePolicy.GiB,"memory ceiling scales beyond 6 GB with installed RAM");
|
||||||
|
Check(ResourcePolicy.MemoryBudget(4*ResourcePolicy.GiB)==3*ResourcePolicy.GiB,"small computers retain physical RAM headroom");
|
||||||
|
Check(ResourcePolicy.WorkerLimit(16)>4&&ResourcePolicy.WorkerLimit(2)==1&&ResourcePolicy.WorkerLimit(64)==16,"worker count scales with CPU while leaving capacity for desktop work");
|
||||||
|
var admission=new MemoryAdmission(()=>(8*ResourcePolicy.GiB,4*ResourcePolicy.GiB));
|
||||||
|
using(var first=await admission.Acquire(2*ResourcePolicy.GiB,CancellationToken.None))
|
||||||
|
{
|
||||||
|
using var cancel=new CancellationTokenSource();var second=admission.Acquire(ResourcePolicy.GiB,cancel.Token);
|
||||||
|
await Task.Delay(120);Check(!second.IsCompleted,"concurrent frames cannot spend the same RAM headroom");
|
||||||
|
cancel.Cancel();bool canceled=false;try{await second;}catch(OperationCanceledException){canceled=true;}Check(canceled&&admission.ReservedBytes==2*ResourcePolicy.GiB,"waiting frames cancel without leaking reservations");
|
||||||
|
}
|
||||||
|
Check(admission.ReservedBytes==0,"completed frames release RAM admission");
|
||||||
|
using(var next=await admission.Acquire(ResourcePolicy.GiB,CancellationToken.None)){next.Dispose();next.Dispose();Check(admission.ReservedBytes==0,"RAM leases release only once");}
|
||||||
|
long free=ResourcePolicy.GiB;var changing=new MemoryAdmission(()=>(8*ResourcePolicy.GiB,Interlocked.Read(ref free)));
|
||||||
|
var waiting=changing.Acquire(ResourcePolicy.GiB,CancellationToken.None);await Task.Delay(120);Check(!waiting.IsCompleted,"external memory pressure pauses allocation");
|
||||||
|
Interlocked.Exchange(ref free,4*ResourcePolicy.GiB);using(var resumed=await waiting.WaitAsync(TimeSpan.FromSeconds(2)))Check(changing.ReservedBytes==ResourcePolicy.GiB,"available RAM increases resume processing dynamically");
|
||||||
|
var ample=new MemoryAdmission(()=>(64*ResourcePolicy.GiB,40*ResourcePolicy.GiB));using(var large=await ample.Acquire(8*ResourcePolicy.GiB,CancellationToken.None))Check(ample.ReservedBytes>6*ResourcePolicy.GiB,"large machines admit work beyond the former fixed ceiling");
|
||||||
bool budgetRefused=false;try{ResourcePolicy.CheckFrame(16000,16000,1);}catch(InvalidDataException){budgetRefused=true;}Check(budgetRefused,"oversized images refused before allocating pixels");
|
bool budgetRefused=false;try{ResourcePolicy.CheckFrame(16000,16000,1);}catch(InvalidDataException){budgetRefused=true;}Check(budgetRefused,"oversized images refused before allocating pixels");
|
||||||
var trend=Enumerable.Range(0,121).Select(i=>Synthetic(i,1-i*.002,160,1000+i*3)).ToList();Classification.Run(trend);
|
var trend=Enumerable.Range(0,121).Select(i=>Synthetic(i,1-i*.002,160,1000+i*3)).ToList();Classification.Run(trend);
|
||||||
Check(trend.All(f=>f.Automatic!=Verdict.Reject),"gradual transparency and background trends do not reject");
|
Check(trend.All(f=>f.Automatic!=Verdict.Reject),"gradual transparency and background trends do not reject");
|
||||||
|
|
@ -105,5 +126,8 @@ try
|
||||||
}
|
}
|
||||||
finally{Directory.Delete(temp,true);}
|
finally{Directory.Delete(temp,true);}
|
||||||
await ImageRegression.Run(Check);
|
await ImageRegression.Run(Check);
|
||||||
|
QualityRegression.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.");
|
||||||
|
|
|
||||||
89
tests/AstroFrame.Validation/QualityRegression.cs
Normal file
89
tests/AstroFrame.Validation/QualityRegression.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
using AstroFrame.Engine;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
static class QualityRegression
|
||||||
|
{
|
||||||
|
public static void Run(Action<bool,string> check)
|
||||||
|
{
|
||||||
|
var stars=Enumerable.Range(0,100).Select(i=>new Star(.08+(i%10)*.09,.08+(i/10)*.09,3000-i*10,4,.1)).ToList();
|
||||||
|
Frame Make(int n)=>new(){Id=n.ToString(),Path="quality"+n,Target="Quality",Exposure=30,Width=2160,Height=3840,
|
||||||
|
Timestamp=new DateTime(2026,9,20,8,0,0,DateTimeKind.Utc).AddSeconds(n*30),Measured=true,
|
||||||
|
StarCount=100,Stars=stars.ToList(),Fwhm=4,Ellipticity=.1,Background=1000,Noise=20,
|
||||||
|
CloudMask=new byte[SkyModel.Count],ReferenceConfidence=1,
|
||||||
|
AdditionalMeasurements=new(){{"Clear reference member",1},{"Forced flux samples",100},{"Matched shape reference frames",20}}};
|
||||||
|
var frames=Enumerable.Range(0,40).Select(Make).ToList();
|
||||||
|
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 subtleShape=Make(46);var insufficient=Make(47);var noisyFlux=Make(48);
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
Matching.Measure(frames[0],f);f.Transparency=1;f.RegionFlux=Enumerable.Repeat(1.0,12).ToArray();f.RegionMatches=Enumerable.Repeat(8,12).ToArray();
|
||||||
|
}
|
||||||
|
void Cloud(Frame f,double significance,double coverage,double ratio)
|
||||||
|
{
|
||||||
|
f.AdditionalMeasurements["Clear reference member"]=0;f.CloudSignificance=significance;f.CloudCoverage=coverage;
|
||||||
|
f.AdditionalMeasurements["Cloud connected coverage"]=coverage*.6;
|
||||||
|
f.AdditionalMeasurements["Cloud positive coverage"]=coverage*.6;
|
||||||
|
f.AdditionalMeasurements["Cloud positive connected coverage"]=coverage*.4;
|
||||||
|
f.AdditionalMeasurements["Cloud aperture samples"]=80;f.AdditionalMeasurements["Cloud aperture regions"]=6;
|
||||||
|
f.AdditionalMeasurements["Cloud aperture flux ratio"]=ratio;f.AdditionalMeasurements["Cloud aperture flux deviation"]=(1-ratio)/.03;
|
||||||
|
}
|
||||||
|
Cloud(opaque,100,.9,.05);opaque.Transparency=.05;
|
||||||
|
Cloud(broad,15,.5,.85);broad.Transparency=.90;
|
||||||
|
Cloud(gradient,15,.5,1);
|
||||||
|
Cloud(insufficient,15,.5,.85);insufficient.AdditionalMeasurements["Cloud aperture samples"]=19;
|
||||||
|
Cloud(noisyFlux,15,.5,.85);noisyFlux.AdditionalMeasurements["Cloud aperture flux deviation"]=2.9;
|
||||||
|
Cloud(uncertain,100,.9,.05);uncertain.Transparency=.05;uncertain.MatchFraction=.1;
|
||||||
|
uncertain.AdditionalMeasurements["Alignment verified"]=0;
|
||||||
|
cohort.Ellipticity=.3;cohort.AdditionalMeasurements["Matched shape samples"]=100;
|
||||||
|
cohort.AdditionalMeasurements["Matched shape change"]=.04;cohort.AdditionalMeasurements["Matched shape uncertainty"]=.01;
|
||||||
|
trailing.Ellipticity=.3;trailing.AdditionalMeasurements["Matched shape samples"]=100;
|
||||||
|
trailing.AdditionalMeasurements["Matched shape change"]=.2;trailing.AdditionalMeasurements["Matched shape uncertainty"]=.01;
|
||||||
|
subtleShape.Ellipticity=.3;subtleShape.AdditionalMeasurements["Matched shape samples"]=100;
|
||||||
|
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);
|
||||||
|
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(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(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(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(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(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 fixture=JsonSerializer.Deserialize<Fixture>(File.ReadAllText(Path.Combine(AppContext.BaseDirectory,"Fixtures","quality-real-frames.json")),options)!;
|
||||||
|
var real=fixture.Frames.ToList();Classification.Run(real);
|
||||||
|
foreach(var label in fixture.Expected)
|
||||||
|
check(real.Single(f=>f.Name==label.Key).Automatic==label.Value,$"real measured regression {label.Key}: {label.Value}");
|
||||||
|
}
|
||||||
|
sealed record Fixture(string Source,Frame[] Frames,Dictionary<string,Verdict> Expected);
|
||||||
|
}
|
||||||
51
tests/AstroFrame.Validation/StellarDetailRegression.cs
Normal file
51
tests/AstroFrame.Validation/StellarDetailRegression.cs
Normal 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);}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,10 +1,14 @@
|
||||||
{
|
{
|
||||||
"source": "User-reviewed screenshots supplied 2026-10-02; these are regression examples, not a representative accuracy sample",
|
"source": "User-reviewed screenshots supplied 2026-10-02 and 2026-10-04; these are regression examples, not a representative accuracy sample",
|
||||||
"frames": [
|
"frames": [
|
||||||
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235146.fit","expected":"Reject","reason":"Extensive upper-frame cloud cover"},
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235146.fit","expected":"Reject","reason":"Extensive upper-frame cloud cover"},
|
||||||
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235218.fit","expected":"Reject","reason":"Extensive upper-frame cloud cover incorrectly kept"},
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235218.fit","expected":"Reject","reason":"Extensive upper-frame cloud cover incorrectly kept"},
|
||||||
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235652.fit","expected":"Keep","reason":"User-confirmed clear exposure"},
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235652.fit","expected":"Keep","reason":"User-confirmed clear exposure"},
|
||||||
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235856.fit","expected":"Keep","reason":"User-confirmed clear exposure falsely reviewed"},
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235856.fit","expected":"Keep","reason":"User-confirmed clear exposure falsely reviewed"},
|
||||||
{"file":"Light_NGC 1432_30.0s_IRCUT_20260920-001734.fit","expected":"Reject","reason":"Extensive bands of cloud incorrectly kept"}
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260920-001734.fit","expected":"Reject","reason":"Extensive bands of cloud incorrectly kept"},
|
||||||
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260919-235506.fit","expected":"Reject","reason":"User-supplied 2026-10-04 example with extensive cloud bands previously REVIEW"},
|
||||||
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260920-000331.fit","expected":"Reject","reason":"User-supplied 2026-10-04 example with extensive cloud bands previously REVIEW"},
|
||||||
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260920-003713.fit","expected":"Reject","reason":"User-supplied nearly opaque frame previously REVIEW due to lost detections"},
|
||||||
|
{"file":"Light_NGC 1432_30.0s_IRCUT_20260920-004304.fit","expected":"Reject","reason":"User-supplied 2026-10-04 example with extensive cloud bands previously REVIEW"}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
36
tools/Verify-Preview.ps1
Normal file
36
tools/Verify-Preview.ps1
Normal 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"
|
||||||
Loading…
Add table
Add a link
Reference in a new issue