Repository navigation
Expand file tree
/
Copy pathdepth.py
More file actions
executable file
·1011 lines (896 loc) · 50.4 KB
/
Copy pathdepth.py
File metadata and controls
executable file
·1011 lines (896 loc) · 50.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""How faint a stack really reaches, measured on the stack itself.
./depth.py M31 the newest M31 session's stack
./depth.py frames/M31/20261014-021118
./depth.py M31 --plant also plant fake stars and count how many are found
./depth.py M31 --sweep the same on 60, 120, 180, 300 and 600 s of its frames
./depth.py M31 --json
./depth.py --model how depth follows star size, sky and time, from every measurement kept
./depth.py --predict --fwhm 4.7 --sky 19.2 --minutes 5
The stack is plate-solved and its stars are matched to Gaia DR3, which gives
the zero point: the magnitude a star of one unit of brightness would have.
From the noise in empty patches of sky that gives the faintest star the
stack would show at 5 sigma. That figure is a formula's; --plant measures
instead. Copies of the stack's own stars, scaled to set magnitudes, are
added at random places and the star finder is run again: the share it
finds at each magnitude is the completeness, given separately for open sky
and for the parts of a galaxy of each brightness, since a star is harder to
see on a bright background. --sweep asks how much depth longer stacks buy.
--model fits one line to every depth.json kept so far: for a faint star
against the sky, the magnitude at which half are found goes up with the
log of the time the light is gathered for, down by 2.5 log of the star's
width, and up by half the sky's darkness in magnitudes per square
arcsecond. The width and sky terms are fixed by that physics; the
constant and the time term are fitted, since frame quality changes how much
time is worth. --predict uses it to say how deep a stack would reach
before it is taken: whether to refocus first, or whether tonight's sky is
worth a patrol.
Magnitudes are Gaia G: the camera has no filter, and G is the nearest of
Gaia's bands to what it sees. The record is kept as depth.json beside a
final.fits, or NAME-depth.json beside any other stack. Nothing here moves the mount or uses the camera; it needs the
internet once per field, for Gaia.
"""
import argparse
import json
import math
from pathlib import Path
import numpy as np
import requests
from astropy.io import fits
from astropy.wcs import WCS
from scipy import ndimage
from scipy.spatial import cKDTree
import config
import interface
import records
import stacking
from camera import luminance
GAIA_URL = "https://vizier.cds.unistra.fr/viz-bin/asu-tsv"
FAINTEST = 19.5 # Gaia stars fainter than this are no use to a 150P
CALIBRATORS = (11.0, 17.5) # G range of the stars the zero point is taken from
MATCH = 2.0 # pixels: a detected star this close to a Gaia star is that star
SIGMA = 5.0 # the detection limit is quoted at 5 sigma
PSF_HALF = 15 # the stars' shape is kept in a square 31 pixels across
MAGNITUDES = tuple(np.arange(13.0, 19.51, 0.5)) # planted stars, from bright to faint: the
# brightest are well above any stack's limit, so what is missing among them is crowding
BRIGHT_BELOW = 15.0 # planted stars brighter than this are planted on their own
SPACING = 25 # pixels kept between planted stars, so they never blend with each other
SWEEP = (60, 120, 180, 300, 600) # seconds of frames for --sweep
# Surface brightness of the smooth glow under a point, magnitudes per square
# arcsecond above the sky: where each kind of background begins. Open sky is
# anything fainter than the first. The figures suit M31; they are not
# special to it, and say nothing about which galaxy is in the frame.
REGIONS = (("sky", None), ("faint glow", 22.0), ("bright glow", 20.5), ("core", 19.0))
# --- the stack -----------------------------------------------------------------
def find_stack(name):
"""The stack to measure: a FITS file, a session folder, or an object's
newest session."""
import restack
path = Path(name)
if path.suffix.lower() in (".fits", ".fit"):
return path
session = restack.find_session(name)
stack = session / "final.fits"
if not stack.exists():
raise interface.Refusal("NO_SESSION", f"{session} has no final.fits yet: run restack.py on it.")
return stack
def object_name(stack):
"""The object a stack is of, from its folder: frames/NAME/<date-time>/final.fits."""
parent = stack.parent
return (parent.parent if parent.name[:1].isdigit() or parent.name.startswith("combined") else parent).name
def brightness(rgb):
"""One brightness image from a stack's colour planes."""
rgb = np.asarray(rgb, dtype=np.float32)
return rgb.sum(axis=0) if rgb.ndim == 3 else rgb
# --- where the stars are, and Gaia ---------------------------------------------
def plate(lum, name):
"""The stack's WCS, from a plate solve near the object it is of."""
import mount
import solve
target = mount.find_target(name)
found = solve.solve(lum, target["ra"], target["dec"], radius=5)
if not found or "cd" not in found:
raise interface.Refusal("PLATE_SOLVE_FAILED", f"The stack of {name} would not plate-solve.")
return wcs_from(found, lum.shape)
def footprint_of(wcs, shape):
"""The solve kept with a measurement, so the stack's place and turn on
the sky are known later without solving again (footprint.py)."""
return {"ra": round(float(wcs.wcs.crval[0]), 6), "dec": round(float(wcs.wcs.crval[1]), 6),
"cd": [[float(v) for v in row] for row in wcs.wcs.cd],
"width_px": int(shape[1]), "height_px": int(shape[0])}
def wcs_from(found, shape):
"""A WCS from a plate solve: the solve's centre at the image's centre."""
w = WCS(naxis=2)
w.wcs.ctype = ["RA---TAN", "DEC--TAN"]
w.wcs.crval = [found["ra"], found["dec"]]
w.wcs.crpix = [(shape[1] + 1) / 2, (shape[0] + 1) / 2]
w.wcs.cd = np.array(found["cd"])
return w
def field(wcs, shape):
"""Centre and radius (degrees) of a circle round the whole image."""
centre = wcs.pixel_to_world_values(shape[1] / 2, shape[0] / 2)
corner = wcs.pixel_to_world_values(0, 0)
ra0, dec0 = np.radians(centre)
ra1, dec1 = np.radians(corner)
apart = math.acos(min(1.0, math.sin(dec0) * math.sin(dec1)
+ math.cos(dec0) * math.cos(dec1) * math.cos(ra0 - ra1)))
return float(centre[0]), float(centre[1]), math.degrees(apart) * 1.05
# The mirrors CDS listed during its cybersecurity incident of late October 2026, working ones first.
DARKEST_SKY = 23.0 # mag per square arcsecond: fainter than any real night sky
GAIA_MIRRORS = (GAIA_URL, "https://vizier.idia.ac.za/viz-bin/asu-tsv", "http://vizier.china-vo.org/viz-bin/asu-tsv",
"http://vizier.nao.ac.jp/viz-bin/asu-tsv", "https://vizier.cfa.harvard.edu/viz-bin/asu-tsv")
# ESA's own Gaia archive, asked when no VizieR mirror answers (4 November
# 2026: every VizieR mirror timed out from here, ESA answered in 2 s).
ESA_TAP = "https://gea.esac.esa.int/tap-server/tap/sync"
def esa_gaia(ra, dec, radius, faintest, get):
"""The same stars from ESA's Gaia archive (ADQL), as VizieR's
tab-separated text so they are kept and read the same way: Gaia DR3's
ra/dec are the same epoch-2016 ICRS places as VizieR's RA_ICRS/DE_ICRS."""
reply = get(ESA_TAP, timeout=(10, 120), params={
"REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "csv",
"QUERY": ("SELECT TOP 200000 ra, dec, phot_g_mean_mag, bp_rp FROM gaiadr3.gaia_source WHERE "
f"1=CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',{ra:.5f},{dec:+.5f},{radius:.3f})) "
f"AND phot_g_mean_mag < {faintest:g}")})
reply.raise_for_status()
rows = [line.split(",") for line in reply.text.strip().splitlines()[1:]]
text = ("#Gaia DR3 from ESA's archive (" + ESA_TAP + ")\nRA_ICRS\tDE_ICRS\tGmag\tBP-RP\n"
"deg\tdeg\tmag\tmag\n---\t---\t---\t---\n"
+ "\n".join("\t".join((r + ["", "", "", ""])[:4]) for r in rows if len(r) >= 3) + "\n")
if not len(read_tsv(text)):
raise requests.RequestException("answered with no stars")
return text
def covering(store, ra, dec, radius, faintest):
"""A circle already fetched that holds this one whole: (path, its centre
and radius), or None. A field imaged night after night is pointed a
little differently each time; on 1 November 2026 the cache, keyed to a
thousandth of a degree, missed and the search needed VizieR while it was
down, for stars it already had."""
best = None
for kept in store.glob(f"*_{faintest:g}_colour.tsv") if store.exists() else []:
try:
cra, cdec, cradius = (float(x) for x in kept.name.split("_")[:3])
except ValueError:
continue
cosd = math.cos(math.radians((dec + cdec) / 2))
apart = math.hypot((ra - cra) * cosd, dec - cdec)
if apart + radius <= cradius and (best is None or cradius < best[3]):
best = (kept, cra, cdec, cradius)
return best
def gaia(ra, dec, radius, faintest=FAINTEST, get=None):
"""Gaia DR3 stars in a circle, as an array of (ra, dec, G, BP-RP), the
colour NaN where Gaia has none. Kept on disk: a field is fetched once, and
any kept circle that holds this one is used instead of fetching again.
VizieR's mirror is tried when Strasbourg does not answer; with neither,
a plain refusal, never a traceback."""
get = get or requests.get
store = config.DATA / "cache" / "gaia"
path = store / f"{ra:.3f}_{dec:+.3f}_{radius:.2f}_{faintest:g}_colour.tsv"
if not path.exists():
held = covering(store, ra, dec, radius, faintest)
if held:
rows = read_tsv(held[0].read_text(encoding="utf-8"))
if len(rows):
cosd = math.cos(math.radians(dec))
inside = np.hypot((rows[:, 0] - ra) * cosd, rows[:, 1] - dec) <= radius
return rows[inside]
failures, text = [], None
for url in GAIA_MIRRORS:
try:
reply = get(url, timeout=(10, 120), params={
"-source": "I/355/gaiadr3", "-c": f"{ra:.5f} {dec:+.5f}", "-c.rd": f"{radius:.3f}",
"-out": "RA_ICRS,DE_ICRS,Gmag,BP-RP", "-out.max": "200000", "Gmag": f"<{faintest:g}"})
reply.raise_for_status()
if not len(read_tsv(reply.text)):
# A mirror that answers with no stars (China-VO, 2 November 2026) is
# not believed: Gaia has stars in every field; never kept.
raise requests.RequestException("answered with no stars")
text = reply.text
break
except requests.RequestException as problem:
failures.append(f"{url.split('/')[2]}: {type(problem).__name__}")
if text is None:
try:
text = esa_gaia(ra, dec, radius, faintest, get)
except requests.RequestException as problem:
failures.append(f"gea.esac.esa.int: {type(problem).__name__}")
raise interface.Refusal("REMOTE_FAILED", "Gaia's stars could not be fetched for this field ("
+ "; ".join(failures) + "), and none kept cover it. Search again when "
"VizieR or ESA answers: ./patrol.py --analyse SESSION")
store.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return read_tsv(path.read_text(encoding="utf-8"))
def read_tsv(text):
"""VizieR's tab-separated answer: comments, a header, units, a rule, rows,
as (ra, dec, G, BP-RP); a missing colour is NaN, a row with no G is left out."""
rows = []
lines = [line for line in text.splitlines() if line.strip() and not line.startswith("#")]
for line in lines[3:]:
parts = line.split("\t") + ["", ""]
try:
ra, dec, g = (float(p) for p in parts[:3])
except ValueError:
continue
try:
colour = float(parts[3])
except ValueError:
colour = float("nan")
rows.append([ra, dec, g, colour])
return np.array(rows, dtype=float).reshape(-1, 4)
# --- measuring -----------------------------------------------------------------
def background(lum, block=16, size=9):
"""The smooth glow under the stars: sky, gradient and galaxy, without
the stars themselves."""
h, w = lum.shape[0] // block * block, lum.shape[1] // block * block
small = lum[:h, :w].reshape(h // block, block, w // block, block)
small = np.median(small, axis=(1, 3))
small = ndimage.median_filter(small, size, mode="nearest")
full = ndimage.zoom(small, (lum.shape[0] / small.shape[0], lum.shape[1] / small.shape[1]), order=1)
return full[:lum.shape[0], :lum.shape[1]].astype(np.float32)
def aperture(radius):
"""Offsets of the pixels in a round aperture."""
r = int(math.ceil(radius))
yy, xx = np.mgrid[-r:r + 1, -r:r + 1]
inside = xx ** 2 + yy ** 2 <= radius ** 2
return yy[inside], xx[inside]
def photometry(flat, xy, radius):
"""Flux in a round aperture at each (x, y) of an image whose glow has
been taken off. Stars too near the edge give NaN."""
dy, dx = aperture(radius)
x = np.rint(xy[:, 0]).astype(int)
y = np.rint(xy[:, 1]).astype(int)
r = int(math.ceil(radius))
ok = (x >= r) & (y >= r) & (x < flat.shape[1] - r) & (y < flat.shape[0] - r)
flux = np.full(len(xy), np.nan)
flux[ok] = flat[y[ok, None] + dy, x[ok, None] + dx].sum(axis=1)
return flux
def peaks(flat, xy):
"""The brightest pixel near each star."""
x = np.clip(np.rint(xy[:, 0]).astype(int), 1, flat.shape[1] - 2)
y = np.clip(np.rint(xy[:, 1]).astype(int), 1, flat.shape[0] - 2)
return np.max([flat[y + j, x + i] for j in (-1, 0, 1) for i in (-1, 0, 1)], axis=0)
def calibrate(flat, stars, wcs, catalogue, radius):
"""Match the detected stars to Gaia and find the zero point. Returns a
dict with the zero point, its uncertainty, the stars used, and the
matched stars (for the star shape)."""
if len(catalogue) == 0 or len(stars) == 0:
return None
px = np.column_stack(wcs.world_to_pixel_values(catalogue[:, 0], catalogue[:, 1]))
inside = ((px[:, 0] > 0) & (px[:, 1] > 0) & (px[:, 0] < flat.shape[1])
& (px[:, 1] < flat.shape[0]))
px, g = px[inside], catalogue[inside, 2]
if not len(px):
return None
tree = cKDTree(stars[:, :2])
# A solve centred a pixel or two off still matches at a loose radius;
# take the typical offset off before matching closely.
d, i = tree.query(px, distance_upper_bound=8 * MATCH)
near = np.isfinite(d)
if near.sum() < 5:
return None
shift = np.median(stars[i[near], :2] - px[near], axis=0)
d, i = tree.query(px + shift, distance_upper_bound=MATCH)
matched = np.isfinite(d)
# A Gaia star with another bright one close by is measured as a blend.
gaia_tree = cKDTree(px)
crowded = np.array([len(gaia_tree.query_ball_point(p, 3 * radius)) > 1 for p in px])
use = matched & ~crowded & (g >= CALIBRATORS[0]) & (g <= CALIBRATORS[1])
if use.sum() < 5:
return None
xy = stars[i[use], :2]
flux = photometry(flat, xy, radius)
# A saturated star is flat-topped: its brightest pixel is too faint for
# its total. Leave those out.
sharpness = peaks(flat, xy) / np.maximum(flux, 1e-6)
good = np.isfinite(flux) & (flux > 0)
typical = np.median(sharpness[good])
good &= sharpness > 0.7 * typical
zp = g[use][good] + 2.5 * np.log10(flux[good])
keep = np.ones(len(zp), bool)
for _ in range(5):
middle = np.median(zp[keep])
spread = 1.4826 * np.median(np.abs(zp[keep] - middle)) + 1e-3
keep = np.abs(zp - middle) < 3 * spread
if keep.sum() < 5:
return None
zps = zp[keep]
spread = 1.4826 * float(np.median(np.abs(zps - np.median(zps))))
term, middle_colour = colour_term(zps, catalogue, inside, use, good, keep)
return {"zeropoint": float(np.median(zps)), "colour_term": term, "colour_ref": middle_colour,
"zeropoint_error": spread / math.sqrt(len(zps)),
"scatter": spread, "stars_used": int(len(zps)),
"psf_stars": xy[good][keep], "shift_px": [float(shift[0]), float(shift[1])]}
COLOUR_STARS = 20 # calibration stars with a colour needed to fit the colour term
def colour_term(zps, catalogue, inside, use, good, keep):
"""How the zero point changes with a star's Gaia BP-RP: the camera has no
filter and is not Gaia's G, so a red star gives it more or less light per
G magnitude than a blue one. Returns (magnitudes per magnitude of BP-RP,
the calibrators' middle colour), or (None, None) without enough colours."""
if catalogue.shape[1] < 4:
return None, None
colours = catalogue[inside, 3][use][good][keep]
ok = np.isfinite(colours)
if ok.sum() < COLOUR_STARS or np.ptp(colours[ok]) < 0.5:
return None, None
slope, _ = np.polyfit(colours[ok], zps[ok], 1)
return round(float(slope), 3), round(float(np.median(colours[ok])), 3)
def psf(flat, xy, radius, half=PSF_HALF, most=40):
"""The stars' own shape, from the matched stars: each one centred to a
fraction of a pixel, scaled to one unit of aperture flux, and the median
taken. Planted stars are copies of it, so they blur and trail exactly as
the real ones do."""
cuts = []
for x, y in xy[:most]:
ix, iy = int(round(x)), int(round(y))
if not (half + 1 <= ix < flat.shape[1] - half - 1 and half + 1 <= iy < flat.shape[0] - half - 1):
continue
cut = flat[iy - half:iy + half + 1, ix - half:ix + half + 1].astype(np.float64)
cut = ndimage.shift(cut, (iy - y, ix - x), order=3, mode="nearest")
total = photometry(cut, np.array([[half, half]]), radius)[0]
if total > 0:
cuts.append(cut / total)
if len(cuts) < 3:
return None
shape = np.median(cuts, axis=0)
# Taper the edges to nothing: a neighbour caught in a corner must not
# be planted along with the star.
yy, xx = np.mgrid[-half:half + 1, -half:half + 1]
shape *= np.clip((half - np.hypot(xx, yy)) / 4, 0, 1)
return (shape / photometry(shape, np.array([[half, half]]), radius)[0]).astype(np.float32)
def stars_mask(lum, stars, grow=3.0):
"""Pixels on or close to a detected star."""
mask = np.zeros(lum.shape, bool)
for x, y, _, fwhm, _ in stars:
r = int(grow * max(fwhm, 2))
ix, iy = int(round(x)), int(round(y))
mask[max(iy - r, 0):iy + r + 1, max(ix - r, 0):ix + r + 1] = True
return mask
def regions(glow, sky, zp, pixel_arcsec):
"""Which kind of background each pixel is on (an index into REGIONS),
from the brightness of the glow above the sky."""
excess = np.maximum(glow - sky, 1e-9) / pixel_arcsec ** 2
surface = zp - 2.5 * np.log10(excess)
kind = np.zeros(glow.shape, np.int8)
for n, (_, brighter_than) in enumerate(REGIONS):
if brighter_than is not None:
kind[surface < brighter_than] = n
return kind
def empty_apertures(flat, mask, kinds, radius, count=4000, seed=1):
"""The spread of the flux in apertures dropped on empty patches: the
noise a star has to stand out from, whatever the stacking did to it.
Per kind of background; None where too few fell."""
rng = np.random.default_rng(seed)
r = int(math.ceil(radius)) + 1
x = rng.uniform(r, flat.shape[1] - r, count)
y = rng.uniform(r, flat.shape[0] - r, count)
xy = np.column_stack([x, y])
dy, dx = aperture(radius)
ix, iy = np.rint(x).astype(int), np.rint(y).astype(int)
clear = ~mask[iy[:, None] + dy, ix[:, None] + dx].any(axis=1)
flux = photometry(flat, xy, radius)
kind = kinds[iy, ix]
spread = {}
for n, (label, _) in enumerate(REGIONS):
pick = clear & (kind == n) & np.isfinite(flux)
if pick.sum() >= 30:
values = flux[pick]
spread[label] = 1.4826 * float(np.median(np.abs(values - np.median(values))))
return spread
# --- planted stars -------------------------------------------------------------
def places(shape, count, rng, edge=PSF_HALF + 2, apart=SPACING):
"""Random places for planted stars, none closer than `apart` to another."""
chosen = []
tries = 0
while len(chosen) < count and tries < count * 50:
tries += 1
p = rng.uniform((edge, edge), (shape[1] - edge, shape[0] - edge))
if all((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 >= apart ** 2 for q in chosen):
chosen.append(p)
return np.array(chosen).reshape(-1, 2)
def plant(lum, shape, xy, flux):
"""A copy of the image with a star of the given shape added at each
place, each with its own flux."""
out = lum.astype(np.float32).copy()
half = shape.shape[0] // 2
for (x, y), f in zip(xy, flux):
ix, iy = int(round(x)), int(round(y))
star = ndimage.shift(shape, (y - iy, x - ix), order=3, mode="constant")
out[iy - half:iy + half + 1, ix - half:ix + half + 1] += f * star
return out
def found_again(before, after, xy, near=MATCH):
"""Which planted stars the star finder picked up: a new detection close
to the place, and not one that was there before."""
if len(after) == 0:
return np.zeros(len(xy), bool)
d, i = cKDTree(after[:, :2]).query(xy, distance_upper_bound=near)
hit = np.isfinite(d)
if len(before) and hit.any():
old, _ = cKDTree(before[:, :2]).query(after[i[hit], :2], distance_upper_bound=near * 0.75)
new = ~np.isfinite(old)
hit[np.flatnonzero(hit)] = new
return hit
def crossing(mags, share, level):
"""The faintest magnitude at which the share found is still `level`,
by a straight line to the next planted magnitude. Read from the faint
end, so a dip among the bright ones (a planted star that landed on a
real one) does not end the curve early. None if no planted magnitude
reaches the level; the faintest planted if all of them do."""
pairs = [(m, s) for m, s in zip(mags, share) if s is not None]
reached = [n for n, (_, s) in enumerate(pairs) if s >= level]
if not reached:
return None
n = reached[-1]
if n == len(pairs) - 1:
return float(pairs[n][0])
(m0, s0), (m1, s1) = pairs[n], pairs[n + 1]
return round(m0 + (s0 - level) / (s0 - s1) * (m1 - m0), 2)
BRIGHT_END = 3 # planted magnitudes, from the brightest, that make the plateau
def plateau(share):
"""The share found among the brightest planted stars: they are all bright
enough to see, so what is missing landed on a real star. That loss is
crowding, and no amount of exposure wins it back."""
top = [s for s in share[:BRIGHT_END] if s is not None]
return float(np.mean(top)) if top else None
def completeness(lum, shape, zp, kinds, trials=6, per_trial=400, seed=7, finder=None):
"""Plant stars at each of MAGNITUDES, run the star finder, and count.
Returns, for every kind of background and for the whole image, the share
found at each magnitude and the magnitudes at which 90% and 50% are."""
finder = finder or (lambda image: stacking.find_stars(image, limit=10 ** 6))
rng = np.random.default_rng(seed)
before = finder(lum)
planted, recovered, kind_of = [], [], []
# The brightest planted stars go in a round of their own: their light
# spreads far enough to raise the star finder's idea of the background
# round a faint one planted near them, and hide it.
bright = [m for m in MAGNITUDES if m < BRIGHT_BELOW]
faint = [m for m in MAGNITUDES if m >= BRIGHT_BELOW]
rounds = [(faint, per_trial)] * trials + [(bright, per_trial // 2)] * trials
for choices, count in rounds:
xy = places(lum.shape, count, rng)
mags = rng.choice(choices, len(xy))
flux = 10 ** (-0.4 * (mags - zp))
hit = found_again(before, finder(plant(lum, shape, xy, flux)), xy)
planted.append(mags)
recovered.append(hit)
kind_of.append(kinds[np.rint(xy[:, 1]).astype(int), np.rint(xy[:, 0]).astype(int)])
mags, hit, kind = np.concatenate(planted), np.concatenate(recovered), np.concatenate(kind_of)
out = {}
for label, pick in [("all", np.ones(len(mags), bool))] + [
(name, kind == n) for n, (name, _) in enumerate(REGIONS)]:
if pick.sum() < 20:
continue
rows, shares = [], []
for m in MAGNITUDES:
at = pick & (mags == m)
share = float(hit[at].mean()) if at.sum() >= 5 else None
shares.append(share)
rows.append({"mag": float(m), "planted": int(at.sum()),
"found": int(hit[at].sum()), "share": None if share is None else round(share, 3)})
# The 90% and 50% points are of the stars not lost to crowding: how
# faint the stack sees, apart from how crowded the field is.
top = plateau(shares)
relative = [None if s is None or not top else s / top for s in shares]
out[label] = {"curve": rows, "bright_end": None if top is None else round(top, 3),
"mag_90": crossing(MAGNITUDES, relative, 0.9),
"mag_50": crossing(MAGNITUDES, relative, 0.5),
"mag_50_error": scatter_of_mag_50(mags[pick], hit[pick], rng),
"planted": int(pick.sum())}
return out
def scatter_of_mag_50(mags, hit, rng, draws=200):
"""How far the 50% point would move with another set of planted stars:
the spread of it over the planted stars drawn again with replacement.
Two stacks whose 50% points differ by less than about twice this have not
been told apart. None when too few draws give a 50% point."""
found = []
for _ in range(draws):
i = rng.integers(0, len(mags), len(mags))
m, h = mags[i], hit[i]
shares = [float(h[m == level].mean()) if (m == level).sum() >= 5 else None for level in MAGNITUDES]
top = plateau(shares)
point = crossing(MAGNITUDES, [None if s is None or not top else s / top for s in shares], 0.5)
if point is not None:
found.append(point)
return round(float(np.std(found)), 3) if len(found) >= draws // 2 else None
# --- putting it together -------------------------------------------------------
def measure(lum, wcs, catalogue, plant_stars=False, trials=6, seed=7, finder=None):
"""Everything this script knows about one stack."""
finder = finder or (lambda image: stacking.find_stars(image, limit=10 ** 6))
glow = background(lum)
flat = lum - glow
stars = finder(lum)
if len(stars) < 5:
raise interface.Refusal("NO_STARS", "Too few stars in the stack to measure it.")
fwhm = float(np.median(stars[:200, 3]))
radius = max(fwhm, 2.0) # an aperture as wide as the star is about the best for faint ones
cal = calibrate(flat, stars, wcs, catalogue, radius)
if cal is None:
raise interface.Refusal("PLATE_SOLVE_FAILED", "Too few of the stack's stars matched Gaia "
"to set its brightness scale.")
zp = cal["zeropoint"]
scale = float(np.sqrt(abs(np.linalg.det(wcs.wcs.cd))) * 3600)
sky = float(np.percentile(glow, 5))
kinds = regions(glow, sky, zp, scale)
noise = empty_apertures(flat, stars_mask(lum, stars), kinds, radius)
limits = {label: round(zp - 2.5 * math.log10(SIGMA * s), 2) for label, s in noise.items() if s > 0}
record = {
"zeropoint": round(zp, 3), "zeropoint_error": round(cal["zeropoint_error"], 3),
"calibration_scatter": round(cal["scatter"], 3), "calibration_stars": cal["stars_used"],
"colour_term": cal.get("colour_term"), "colour_ref": cal.get("colour_ref"),
"fwhm_px": round(fwhm, 2), "fwhm_arcsec": round(fwhm * scale, 2),
"scale_arcsec_per_px": round(scale, 3), "aperture_px": round(radius, 2),
"sky_level": round(sky, 2),
# None when the stack's sky is at or below zero: the bias taken off was
# above tonight's camera offset (1 November 2026: -58, read as 46 mag).
"sky_mag_per_arcsec2": round(zp - 2.5 * math.log10(sky / scale ** 2), 2) if sky > 0 else None,
"stars_detected": int(len(stars)),
"limit_5sigma": limits,
"share_of_image": {name: round(float((kinds == n).mean()), 3) for n, (name, _) in enumerate(REGIONS)},
"band": "Gaia G (camera unfiltered)",
"kinds": {"zeropoint": "measured", "colour_term": "measured", "limit_5sigma": "inferred",
"completeness": "simulated"},
}
if plant_stars:
shape = psf(flat, cal["psf_stars"], radius)
if shape is None:
raise interface.Refusal("NO_STARS", "Too few clean stars to copy for planting.")
record["completeness"] = completeness(lum, shape, zp, kinds, trials=trials, seed=seed,
finder=finder)
record["planted_per_trial"] = 400
record["trials"] = trials
return record
def named(record, header):
"""A filtered stack's (the 183M's) magnitudes named for what took them:
instrumental, in its own band ("L (Optolong), 183M"), with the zero point
against Gaia G and its colour term from comparison stars of different
colours, or said when there were too few to fit one. Never called Gaia
G or V. The 183C's unfiltered stacks keep their wording."""
import filters
band = filters.band(header)
if not band:
return record
term = record.get("colour_term")
record["band"] = (f"{band}, instrumental: zero point against Gaia G with a colour term of {term:+.3f} mag "
f"per mag of BP-RP about BP-RP {record.get('colour_ref')}" if term is not None else
f"{band}, instrumental: zero point against Gaia G, no colour term (too few comparison stars "
"of different colours), so a star's magnitude carries its colour's error")
record["band_key"] = list(filters.band_key(header))
if term is None:
record.setdefault("kinds", {})["colour_term"] = "not known"
return record
def frames_for_sweep(session):
"""The session's frames worth stacking, in the order they were taken."""
import restack
log = session / "restack.json"
if log.exists():
kept = json.loads(log.read_text(encoding="utf-8")).get("kept", [])
names = sorted(Path(k).name for k in kept)
return [session / n for n in names if (session / n).exists()]
frames = stacking.read_log(session)
return [Path(f["path"]) for f in restack.select(frames)] if frames else sorted(session.glob("light-*.fits"))
def sweep_stacks(paths, seconds_list, say=print):
"""Stacks of the first so many seconds of frames, one per entry in
seconds_list, all lined up on the first frame so one plate solve serves
them all. Nothing is trimmed: the first frame covers the whole picture,
and trimming each stack differently would move its pixels from under
the solve. Returns {seconds: (brightness image, seconds really used)}."""
paths = stacking.on_target(paths, say)
stacking.same_camera(paths)
stacking.require_frames(paths, "A depth sweep")
mosaic, header = stacking.load_light(paths[0])
exposure, gain = float(header.get("EXPTIME", 0)), int(float(header.get("GAIN", 0)))
if exposure <= 0:
raise interface.Refusal("INVALID_REQUEST", f"{paths[0]} does not say its exposure.")
calibration = stacking.Calibration(exposure, gain, header) # the frame's own masters (vet.stacked)
mono = stacking.is_mono(header)
rgb = stacking.prepare(mosaic, calibration, mono=mono)
lum = rgb.sum(axis=2)
reference = {"square": stacking.centre_square(lum), "stars": stacking.find_stars(lum)}
wanted = sorted({min(len(paths), max(1, round(s / exposure))): s for s in seconds_list}.items())
stack = stacking.Stack(rgb.shape)
out, n = {}, 0
for path in paths[:wanted[-1][0]]:
if n:
mosaic, head = stacking.load_light(path)
# Each frame its own masters, one calibration per set of settings.
rgb = stacking.prepare(mosaic, stacking._calibration(float(head.get("EXPTIME", 0)),
int(float(head.get("GAIN", 0))),
stacking.worker_cards(head)), mono=mono)
rgb, _ = stacking.register(rgb, rgb.sum(axis=2), stacking.find_stars(rgb.sum(axis=2)),
reference)
stack.add(rgb)
n += 1
for count, seconds in wanted:
if count == n:
out[seconds] = (stack.result().sum(axis=2), n * exposure)
say(f" {seconds} s asked: {n} frames, {n * exposure:g} s")
return out
def run(args, say=print):
if config.DEMO:
raise interface.Refusal("DEMO_UNSUPPORTED", "Measuring depth needs a real stack and Gaia.")
stack = find_stack(args.target)
stacking.require_stack(stack, "A depth measurement")
name = args.near or object_name(stack)
lum = brightness(fits.getdata(stack))
header = fits.getheader(stack)
say(f"{stack}: {lum.shape[1]} x {lum.shape[0]}, {header.get('EXPTIME', '?')} s "
f"in {header.get('NFRAMES', '?')} frames")
wcs = plate(lum, name)
catalogue = gaia(*field(wcs, lum.shape))
say(f"{len(catalogue)} Gaia stars in the field")
record = measure(lum, wcs, catalogue, plant_stars=args.plant or args.sweep, trials=args.trials)
named(record, header)
record.update(stack=str(stack), object=name, exposure_s=header.get("EXPTIME"),
frames=header.get("NFRAMES"), footprint=footprint_of(wcs, lum.shape))
report(record, say)
if args.sweep:
session = stack.parent
paths = frames_for_sweep(session)
if not paths:
raise interface.Refusal("NO_SESSION", f"No raw frames in {session} for a sweep.")
say(f"sweep over {len(paths)} frames:")
stacks = sweep_stacks(paths, SWEEP, say)
first = max(stacks)
big, _ = stacks[first]
sweep_wcs = plate(big, name)
rows = []
for seconds in sorted(stacks):
image, used = stacks[seconds]
one = measure(image, sweep_wcs, catalogue, plant_stars=True, trials=max(2, args.trials // 2))
rows.append({"asked_s": seconds, "exposure_s": used, "zeropoint": one["zeropoint"],
"limit_5sigma": one["limit_5sigma"],
"mag_90": {k: v["mag_90"] for k, v in one["completeness"].items()},
"mag_50": {k: v["mag_50"] for k, v in one["completeness"].items()}})
say(f" {used:5.0f} s: 5-sigma {one['limit_5sigma'].get('sky')}, "
f"50% found at {one['completeness'].get('all', {}).get('mag_50')}")
record["sweep"] = rows
kept = record_path(stack)
if kept.exists():
# A run without --plant or --sweep keeps what an earlier one measured.
earlier = json.loads(kept.read_text(encoding="utf-8"))
for key in ("completeness", "planted_per_trial", "trials", "sweep"):
if key in earlier and key not in record:
record[key] = earlier[key]
record.setdefault("carried_over", []).append(key)
if record.get("carried_over"):
say(f"kept from the earlier measurement: {', '.join(record['carried_over'])}")
records.write(kept, record, schema="depth", stamp=True)
say(f"kept as {kept}")
return record
# --- how depth follows the conditions ---------------------------------------
def measurements(folder=None):
"""Every kept measurement of a stack's depth, as rows of (seconds, star
width in arcseconds, sky in mag per square arcsecond, magnitude at which
half the planted stars were found), from each depth.json under frames/:
the whole stack and each step of a sweep."""
rows = []
for path in sorted((folder or config.DATA / "frames").glob("**/*depth.json")):
r = json.loads(path.read_text(encoding="utf-8"))
width, sky = r.get("fwhm_arcsec"), r.get("sky_mag_per_arcsec2")
whole = r.get("completeness", {}).get("all", {}).get("mag_50")
# A sky no real sky gives is a calibration fault, not a measurement:
# 1 November 2026's 46.13 came from a negative stack.
if width and sky is not None and sky <= DARKEST_SKY and whole is not None and r.get("exposure_s"):
rows.append({"stack": r.get("stack", str(path.parent)), "session": str(path.parent),
"seconds": float(r["exposure_s"]),
"fwhm_arcsec": width, "sky": sky, "mag_50": whole})
for step in r.get("sweep", []):
if width and sky is not None and step.get("mag_50", {}).get("all") is not None:
rows.append({"stack": f"{r.get('stack', path.parent)} first {step['exposure_s']:g} s",
"session": str(path.parent),
"seconds": float(step["exposure_s"]), "fwhm_arcsec": width, "sky": sky,
"mag_50": step["mag_50"]["all"]})
return rows
FREE_AFTER = 20 # independent stacks needed before the width and sky terms are fitted too
def fit(rows, free=False):
"""The model mag_50 = constant + time x log10(seconds) + fwhm x log10(FWHM")
+ sky x sky, with how far each measurement sits from it. Normally only
the constant and the time term are fitted, and the width and sky terms
are held at what a perfect detector against the sky would give (-2.5
and 0.5). With `free`, all four are fitted, which needs FREE_AFTER
independent stacks: the steps of one sweep share their night's star
width and sky, so they count as one."""
if len(rows) < 3 or len({r["seconds"] for r in rows}) < 2:
raise interface.Refusal("INVALID_REQUEST", "Too few depth measurements to fit: run "
"depth.py --plant on a few stacks, or --sweep on one.")
independent = len({r.get("session", r["stack"]) for r in rows})
t = np.log10([r["seconds"] for r in rows])
w = np.log10([r["fwhm_arcsec"] for r in rows])
sky = np.array([r["sky"] for r in rows])
m = np.array([r["mag_50"] for r in rows])
if free:
if independent < FREE_AFTER:
raise interface.Refusal("INVALID_REQUEST", f"Fitting every term needs {FREE_AFTER} independent "
f"stacks, nights of different focus and sky; there are {independent}.")
terms, *_ = np.linalg.lstsq(np.column_stack([np.ones(len(m)), t, w, sky]), m, rcond=None)
constant, slope, width, darkness = (float(v) for v in terms)
else:
slope, constant = np.polyfit(t, m + 2.5 * w - 0.5 * sky, 1)
width, darkness = -2.5, 0.5
model = {"constant": round(float(constant), 3), "time": round(float(slope), 3),
"fwhm": round(width, 3), "sky": round(darkness, 3), "measurements": len(rows),
"independent": independent, "free": bool(free)}
for r in rows:
r["predicted"] = round(predict(model, r["fwhm_arcsec"], r["sky"], r["seconds"]), 2)
r["off_by"] = round(r["mag_50"] - r["predicted"], 2)
model["scatter"] = round(float(np.std([r["off_by"] for r in rows])), 3)
return model, rows
def predict(model, fwhm_arcsec, sky, seconds):
"""The magnitude at which half of faint stars would be found."""
return (model["constant"] + model["time"] * math.log10(seconds)
+ model["fwhm"] * math.log10(fwhm_arcsec) + model["sky"] * sky)
def run_model(args, say=print):
model, rows = fit(measurements(), free=getattr(args, "free", False))
say(f"from {model['measurements']} measurements of {model['independent']} independent stacks: "
f"half found at {model['constant']:.2f} + {model['time']:.2f} log10(seconds) "
f"{model['fwhm']:+.2f} log10(FWHM\") {model['sky']:+.2f} sky; scatter {model['scatter']:.2f} mag"
+ ("" if model["free"] else " (width and sky terms held at -2.5 and +0.5)"))
say(f"each doubling of time buys {model['time'] * math.log10(2):.2f} mag "
f"(0.38 if only the sky's noise mattered)")
for r in rows:
say(f" {r['mag_50']:5.2f} measured, {r['predicted']:5.2f} predicted {r['stack']}")
answer = {"model": model, "measurements": rows}
if args.predict:
if args.fwhm is None or args.sky is None:
raise interface.Refusal("INVALID_REQUEST", "--predict needs --fwhm (arcseconds) and --sky "
"(mag per square arcsecond).")
seconds = 60 * args.minutes
m = predict(model, args.fwhm, args.sky, seconds)
say(f"stars {args.fwhm}\" across under a {args.sky} sky, {args.minutes:g} minutes: "
f"half found at about G {m:.1f} (inferred, ± {model['scatter']:.1f}; good enough to "
"decide whether to refocus or patrol, not an exact limit)")
answer["prediction"] = {"fwhm_arcsec": args.fwhm, "sky": args.sky, "seconds": seconds,
"mag_50": round(m, 2), "kind": "inferred"}
return answer
def gaussian_star(fwhm, half=PSF_HALF):
"""A round star of total 1 on a (2 half + 1) square."""
yy, xx = np.mgrid[-half:half + 1, -half:half + 1]
star = np.exp(-(xx ** 2 + yy ** 2) / (2 * (fwhm / 2.3548) ** 2))
return star / star.sum()
# Elliptical rings of a planted galaxy, in its scale lengths: the first is
# its centre, all of them together its total light.
GALAXY_RINGS = (0, 0.5, 1, 2, 3, 4)
def galaxy(shape, centre, scale, ratio, angle, peak):
"""An exponential disc on an image of the given shape, peak brightness at
its centre, `scale` pixels along its long axis and `ratio` of that along
its short one, turned by `angle` radians; with each pixel's elliptical
radius in scale lengths."""
yy, xx = np.indices(shape, dtype=np.float32)
dx, dy = xx - centre[0], yy - centre[1]
along = dx * np.cos(angle) + dy * np.sin(angle)
across = -dx * np.sin(angle) + dy * np.cos(angle)
radius = np.hypot(along / scale, across / (scale * ratio))
return (peak * np.exp(-radius)).astype(np.float32), radius
def profile(image, radius, rings=GALAXY_RINGS):
"""Total light of an image in each elliptical ring."""
return np.array([image[(radius >= a) & (radius < b)].sum() for a, b in zip(rings, rings[1:])])
def destripe_check(session, frames=5, per_frame=300, fwhm=4.0, seed=11, say=print):
"""Whether stacking.destripe takes real light with the stripes: stars of
known brightness are planted in raw frames of a session, before
anything is done to them, and each frame is then measured with and
without the destriping. For each way: the share of planted stars found,
and the planted stars' measured flux over what was put in (1 is none
lost). With it, how much of the broad light (a galaxy, the sky's
gradient) the destriping changed, in blocks of 64 pixels, against how
much that broad light varies. M31 filling a frame is the hard case: its
light runs along whole rows. And since that broad light is what an
extended object is made of, a faint galaxy of known profile is planted
in each frame too, of a random size, shape and turn, and what the
destriping kept of it is measured in elliptical rings: its centre, its
profile and its total (1 is all kept)."""
files = stacking.on_target(sorted(Path(session).glob("light-*.fits"))[:frames], lambda line: None)
if not files:
raise interface.Refusal("NO_SESSION", f"No saved frames in {session}.")
rng = np.random.default_rng(seed)
shape = gaussian_star(fwhm)
lum = lambda mosaic: luminance(mosaic).astype(np.float32)
found = {"plain": [], "destriped": []}
ratio = {"plain": [], "destriped": []}
broad = []
rings = []
for path in files:
mosaic, header = stacking.load_light(path)
raw = stacking.Calibration(float(header["EXPTIME"]), int(header["GAIN"]), header).apply(mosaic).astype(np.float32)
base = lum(raw)
noise = 1.4826 * float(np.median(np.abs(base - np.median(base))))
xy = places(base.shape, per_frame, rng)
# From a little above the noise in one aperture to well clear of it.
flux = noise * np.sqrt(np.pi * fwhm ** 2) * rng.uniform(3, 40, len(xy))
# Planted in the raw mosaic: the same star in each 2x2 cell's four
# sites, so its luminance is the flux asked for.
planted = plant(np.zeros(base.shape, np.float32), shape, xy, flux / 4)
with_stars = raw + np.repeat(np.repeat(planted, 2, axis=0), 2, axis=1)
for way, treat in (("plain", lambda m: m), ("destriped", stacking.destripe)):
empty, full = lum(treat(raw)), lum(treat(with_stars))
found[way].append(found_again(stacking.find_stars(empty, 10 ** 6),
stacking.find_stars(full, 10 ** 6), xy))
ratio[way].append(photometry(full - empty, xy, 1.5 * fwhm) / flux)
blocks = lambda image: image[:image.shape[0] // 64 * 64, :image.shape[1] // 64 * 64].reshape(
image.shape[0] // 64, 64, -1, 64).mean(axis=(1, 3))
levelled = lum(stacking.destripe(raw))
before, after = blocks(base), blocks(levelled)
broad.append(float(np.std(after - before) / max(np.std(before), 1e-9)))
# A galaxy from a few rows across to more than the levelling's
# window, its centre one to five times the noise of a pixel.
scale = rng.uniform(15, min(60, min(base.shape) / 10))
edge = GALAXY_RINGS[-1] * scale + 2
centre = rng.uniform((edge, edge), (base.shape[1] - edge, base.shape[0] - edge))
glow, radius = galaxy(base.shape, centre, scale, rng.uniform(0.3, 1), rng.uniform(0, np.pi),
noise * rng.uniform(1, 5))
with_galaxy = raw + np.repeat(np.repeat(glow / 4, 2, axis=0), 2, axis=1)
kept = lum(stacking.destripe(with_galaxy)) - levelled
rings.append((profile(kept, radius), profile(glow, radius)))
answer = {"session": str(session), "frames": len(files), "planted": per_frame * len(files),
"broad_light_changed": round(float(np.median(broad)), 4)}
kept, put = (np.array(side) for side in zip(*rings))
answer["galaxy"] = {"rings": list(GALAXY_RINGS),
"profile": [round(float(v), 4) for v in np.median(kept / put, axis=0)],
"centre": round(float(np.median(kept[:, 0] / put[:, 0])), 4),
"total": round(float(np.median(kept.sum(axis=1) / put.sum(axis=1))), 4)}
for way in found:
r = np.concatenate(ratio[way])
r = r[np.isfinite(r)]
answer[way] = {"found": round(float(np.concatenate(found[way]).mean()), 3),
"flux_ratio": round(float(np.median(r)), 4),
"flux_scatter": round(float(1.4826 * np.median(np.abs(r - np.median(r)))), 4)}
p, d = answer["plain"], answer["destriped"]
say(f"{Path(session).parent.name} {Path(session).name}, {answer['planted']} stars planted in {len(files)} raw "
f"frames: found {p['found']:.1%} plain, {d['found']:.1%} destriped; measured flux {p['flux_ratio']:.3f} "
f"plain, {d['flux_ratio']:.3f} destriped (1 is all kept); broad light changed by "
f"{answer['broad_light_changed']:.2%} of its own variation")
g = answer["galaxy"]
say(f"planted galaxies kept by the destriping: centre {g['centre']:.3f}, total {g['total']:.3f}, rings of "
f"{', '.join(f'{a}-{b}' for a, b in zip(GALAXY_RINGS, GALAXY_RINGS[1:]))} scale lengths "
f"{', '.join(f'{v:.3f}' for v in g['profile'])}")
return answer
def record_path(stack):
"""Where a stack's measurement is kept: depth.json beside the picture's
final.fits, NAME-depth.json beside any other stack."""
stack = Path(stack)
return stack.parent / ("depth.json" if stack.name == "final.fits" else f"{stack.stem}-depth.json")
def report(r, say=print):
say(f"zero point {r['zeropoint']:.2f} ± {r['zeropoint_error']:.2f} (G) from "
f"{r['calibration_stars']} Gaia stars, scatter {r['calibration_scatter']:.2f}")
say(f"stars {r['fwhm_arcsec']:.1f}\" across ({r['fwhm_px']:.1f} px); "
+ (f"sky {r['sky_mag_per_arcsec2']:.1f} mag per square arcsecond" if r.get("sky_mag_per_arcsec2") is not None
else "sky not measured: the stack's background is at or below zero (the bias taken off is too high)"))
for label, limit in r["limit_5sigma"].items():
say(f"5-sigma limit on {label}: {limit:.2f} (a formula's figure)")
for label, c in r.get("completeness", {}).items():
lost = "" if c["bright_end"] is None else f"; {100 * (1 - c['bright_end']):.0f}% lost on real stars"
say(f"planted stars on {label}: 90% found to {c['mag_90']}, 50% to {c['mag_50']} "
f"({c['planted']} planted{lost})")
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("target", nargs="?",
help="an object (its newest session), a session folder, or a FITS stack")
ap.add_argument("--plant", action="store_true", help="plant fake stars and count how many are found")
ap.add_argument("--trials", type=int, default=10, help="rounds of 400 planted stars (default 10)")
ap.add_argument("--sweep", action="store_true",
help="also measure stacks of 60, 120, 180, 300 and 600 s of the session's frames")
ap.add_argument("--near", help="the object to plate-solve near, if the folder does not say")
ap.add_argument("--model", action="store_true",
help="fit how depth follows star size, sky and time, from every depth.json kept")
ap.add_argument("--free", action="store_true",
help=f"with --model: fit the width and sky terms too (needs {FREE_AFTER} independent stacks)")
ap.add_argument("--predict", action="store_true",
help="with --fwhm, --sky and --minutes: how deep a stack would reach")
ap.add_argument("--fwhm", type=float, help="star width in arcseconds, for --predict")
ap.add_argument("--sky", type=float, help="sky in mag per square arcsecond, for --predict")
ap.add_argument("--minutes", type=float, default=5.0, help="length of the stack, for --predict (default 5)")
ap.add_argument("--destripe-check", action="store_true",
help="with a session folder: plant stars in its raw frames and measure them with and "
"without the row-stripe correction")
ap.add_argument("--json", action="store_true", help="answer in JSON")
args = ap.parse_args()
if args.destripe_check:
if not args.target:
ap.error("name a session folder")
interface.main("depth-destripe-check", lambda: destripe_check(args.target), args.json)