jacscanomaly 0.3.4__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/MANIFEST.in +1 -0
  2. {jacscanomaly-0.3.4/src/jacscanomaly.egg-info → jacscanomaly-0.5.0}/PKG-INFO +31 -7
  3. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/README.md +30 -6
  4. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/pyproject.toml +1 -1
  5. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/setup.py +44 -3
  6. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/__init__.py +9 -29
  7. jacscanomaly-0.5.0/src/jacscanomaly/_vbm_cpp.cpp +278 -0
  8. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/config.py +56 -13
  9. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/finder.py +213 -33
  10. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/magnification.py +13 -6
  11. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/models.py +15 -7
  12. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/planet_signal.py +394 -493
  13. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/runner.py +3 -16
  14. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/singlelens_fit.py +232 -21
  15. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/singlelens_model.py +40 -0
  16. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0/src/jacscanomaly.egg-info}/PKG-INFO +31 -7
  17. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly.egg-info/SOURCES.txt +2 -18
  18. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_config.py +13 -0
  19. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_planet_signal.py +198 -38
  20. jacscanomaly-0.5.0/tests/test_scoring.py +117 -0
  21. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/__init__.py +0 -64
  22. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/__init__.py +0 -41
  23. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/base.py +0 -379
  24. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/bump.py +0 -181
  25. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/central.py +0 -140
  26. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/chang_refsdal.py +0 -269
  27. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/cusp.py +0 -165
  28. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/fold.py +0 -713
  29. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/second_pspl.py +0 -51
  30. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/atoms/smooth.py +0 -194
  31. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/classifier.py +0 -403
  32. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/features.py +0 -72
  33. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/fold_kernel.py +0 -246
  34. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/linear.py +0 -45
  35. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/pspl.py +0 -65
  36. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/seeds.py +0 -331
  37. jacscanomaly-0.3.4/src/jacscanomaly/planet_class/types.py +0 -396
  38. jacscanomaly-0.3.4/tests/test_planet_class.py +0 -850
  39. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/LICENSE +0 -0
  40. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/setup.cfg +0 -0
  41. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/_cpp_grid.cpp +0 -0
  42. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/anomaly_models.py +0 -0
  43. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/criteria.py +0 -0
  44. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/data/__init__.py +0 -0
  45. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/data/earth_orbital_parallax_table.txt +0 -0
  46. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/extract.py +0 -0
  47. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/objective.py +0 -0
  48. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/parallax.py +0 -0
  49. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/photometry.py +0 -0
  50. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/plot.py +0 -0
  51. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/seasons.py +0 -0
  52. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/template_free.py +0 -0
  53. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly/trajectory.py +0 -0
  54. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly.egg-info/dependency_links.txt +0 -0
  55. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly.egg-info/requires.txt +0 -0
  56. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/src/jacscanomaly.egg-info/top_level.txt +0 -0
  57. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_cpp_extension.py +0 -0
  58. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_criteria.py +0 -0
  59. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_extract.py +0 -0
  60. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_magnitude_input.py +0 -0
  61. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_models.py +0 -0
  62. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_photometry.py +0 -0
  63. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_refit.py +0 -0
  64. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_seasons.py +0 -0
  65. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_space_parallax.py +0 -0
  66. {jacscanomaly-0.3.4 → jacscanomaly-0.5.0}/tests/test_template_free.py +0 -0
@@ -2,4 +2,5 @@ include pyproject.toml
2
2
  include setup.py
3
3
  include README.md
4
4
  include src/jacscanomaly/_cpp_grid.cpp
5
+ include src/jacscanomaly/_vbm_cpp.cpp
5
6
  recursive-include src/jacscanomaly/data *
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jacscanomaly
3
- Version: 0.3.4
3
+ Version: 0.5.0
4
4
  Summary: JAX-based scan anomaly detection for time-series residuals
5
5
  Author: Kansuke Nunota
6
6
  License: MIT
@@ -138,6 +138,18 @@ Example notebooks are available in `example/`:
138
138
  * `template_scan_example.ipynb` for the standard bell-template scan
139
139
  * `template_free_example.ipynb` for the template-free residual chi-square scan
140
140
 
141
+ For a refined planetary residual, measure its peaks and dips directly:
142
+
143
+ ```python
144
+ features = signal.measure_features()
145
+ print(features.n_peaks, features.n_dips)
146
+ for feature in features.features:
147
+ print(feature.kind, feature.time, feature.timescale, feature.strength)
148
+ ```
149
+
150
+ This measurement does not assign a caustic shape or estimate binary-lens
151
+ parameters.
152
+
141
153
  ---
142
154
 
143
155
  ## Method Overview
@@ -176,16 +188,27 @@ To quantify how significant the best anomaly candidate is relative to others,
176
188
  we define a **score**:
177
189
 
178
190
  ```
179
- score = (Δχ²_best − median(Δχ²_others)) / std(Δχ²_others)
191
+ score = (Δχ²_best − median(Δχ²_others)) / robust_scale(Δχ²_others)
180
192
  ```
181
193
 
182
- In practice, `jacscanomaly` estimates `median(Δχ²_others)` and
183
- `std(Δχ²_others)` from the bulk of the other cluster peaks, trimming values
184
- above `best_score_trim_percentile` first when possible. This makes the score
185
- less sensitive to a few strong secondary peaks.
194
+ The reference population is restricted to raw clusters from the same observing
195
+ season and a comparable `teff`. Candidate-quality cuts are applied only after
196
+ raw cluster extraction, so changing those cuts does not redefine the score
197
+ background. The center and scale are estimated robustly with the median and
198
+ MAD. Strong secondary candidates are removed with adaptive one-sided clipping
199
+ rather than an unconditional percentile cut.
186
200
 
187
201
  This measures how strongly the best candidate stands out from the rest of the grid.
188
202
 
203
+ Since v0.4.0, the score background is local to the candidate's observing
204
+ season and timescale, with robust median/MAD normalization. Quality cuts do not
205
+ change that background, and strong secondary clusters are removed only by
206
+ adaptive one-sided clipping. In checks on four retained Roman light curves,
207
+ the selected candidate and its ``Δχ²`` were unchanged while the score changed
208
+ moderately, indicating that the normalization is less sensitive to unrelated
209
+ seasons and timescales. Existing ``simscan`` efficiency maps using score
210
+ thresholds should be recalibrated with v0.4.0 scores.
211
+
189
212
  ---
190
213
 
191
214
  ## Candidate Quality Diagnostics
@@ -253,7 +276,8 @@ config = FinderConfig(
253
276
  teff_grid_n=20, # number of teff grid points
254
277
  sigma=3.0, # per-point improvement threshold for n_contrib
255
278
  candidate_criteria=CandidateCriteria(min_n_eff=2.0),
256
- best_score_trim_percentile=95.0, # trim upper tail for best-candidate score
279
+ best_score_teff_ratio=2.0,
280
+ best_score_upper_clip_sigma=5.0,
257
281
  )
258
282
  ```
259
283
 
@@ -108,6 +108,18 @@ Example notebooks are available in `example/`:
108
108
  * `template_scan_example.ipynb` for the standard bell-template scan
109
109
  * `template_free_example.ipynb` for the template-free residual chi-square scan
110
110
 
111
+ For a refined planetary residual, measure its peaks and dips directly:
112
+
113
+ ```python
114
+ features = signal.measure_features()
115
+ print(features.n_peaks, features.n_dips)
116
+ for feature in features.features:
117
+ print(feature.kind, feature.time, feature.timescale, feature.strength)
118
+ ```
119
+
120
+ This measurement does not assign a caustic shape or estimate binary-lens
121
+ parameters.
122
+
111
123
  ---
112
124
 
113
125
  ## Method Overview
@@ -146,16 +158,27 @@ To quantify how significant the best anomaly candidate is relative to others,
146
158
  we define a **score**:
147
159
 
148
160
  ```
149
- score = (Δχ²_best − median(Δχ²_others)) / std(Δχ²_others)
161
+ score = (Δχ²_best − median(Δχ²_others)) / robust_scale(Δχ²_others)
150
162
  ```
151
163
 
152
- In practice, `jacscanomaly` estimates `median(Δχ²_others)` and
153
- `std(Δχ²_others)` from the bulk of the other cluster peaks, trimming values
154
- above `best_score_trim_percentile` first when possible. This makes the score
155
- less sensitive to a few strong secondary peaks.
164
+ The reference population is restricted to raw clusters from the same observing
165
+ season and a comparable `teff`. Candidate-quality cuts are applied only after
166
+ raw cluster extraction, so changing those cuts does not redefine the score
167
+ background. The center and scale are estimated robustly with the median and
168
+ MAD. Strong secondary candidates are removed with adaptive one-sided clipping
169
+ rather than an unconditional percentile cut.
156
170
 
157
171
  This measures how strongly the best candidate stands out from the rest of the grid.
158
172
 
173
+ Since v0.4.0, the score background is local to the candidate's observing
174
+ season and timescale, with robust median/MAD normalization. Quality cuts do not
175
+ change that background, and strong secondary clusters are removed only by
176
+ adaptive one-sided clipping. In checks on four retained Roman light curves,
177
+ the selected candidate and its ``Δχ²`` were unchanged while the score changed
178
+ moderately, indicating that the normalization is less sensitive to unrelated
179
+ seasons and timescales. Existing ``simscan`` efficiency maps using score
180
+ thresholds should be recalibrated with v0.4.0 scores.
181
+
159
182
  ---
160
183
 
161
184
  ## Candidate Quality Diagnostics
@@ -223,7 +246,8 @@ config = FinderConfig(
223
246
  teff_grid_n=20, # number of teff grid points
224
247
  sigma=3.0, # per-point improvement threshold for n_contrib
225
248
  candidate_criteria=CandidateCriteria(min_n_eff=2.0),
226
- best_score_trim_percentile=95.0, # trim upper tail for best-candidate score
249
+ best_score_teff_ratio=2.0,
250
+ best_score_upper_clip_sigma=5.0,
227
251
  )
228
252
  ```
229
253
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "jacscanomaly"
7
- version = "0.3.4"
7
+ version = "0.5.0"
8
8
  description = "JAX-based scan anomaly detection for time-series residuals"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import sys
4
+ import os
4
5
  from pathlib import Path
5
6
 
6
7
  import numpy as np
@@ -9,6 +10,31 @@ from setuptools.command.build_ext import build_ext as _build_ext
9
10
 
10
11
 
11
12
  CPP_GRID_SOURCE = Path("src/jacscanomaly/_cpp_grid.cpp")
13
+ VBM_CPP_SOURCE = Path("src/jacscanomaly/_vbm_cpp.cpp")
14
+
15
+
16
+ def _find_vbm_sources() -> tuple[Path, Path] | None:
17
+ """Locate the C++ sources installed by the optional VBMicrolensing package.
18
+
19
+ The VBM wrapper remains an optional extension: standard jacscanomaly
20
+ installs retain the existing C++ PSPL backend, while ``jacscanomaly[vbm]``
21
+ gains the native FSPL+annual-parallax backend when VBM ships its sources.
22
+ ``VBMICROLENSING_SOURCE_DIR`` supports non-standard installations.
23
+ """
24
+ candidates: list[Path] = []
25
+ source_dir = os.environ.get("VBMICROLENSING_SOURCE_DIR")
26
+ if source_dir:
27
+ candidates.append(Path(source_dir))
28
+ try:
29
+ import VBMicrolensing # type: ignore
30
+
31
+ candidates.append(Path(VBMicrolensing.__file__).resolve().parent / "lib")
32
+ except ImportError:
33
+ pass
34
+ for directory in candidates:
35
+ if (directory / "VBMicrolensingLibrary.cpp").is_file() and (directory / "VBMicrolensingLibrary.h").is_file():
36
+ return directory / "VBMicrolensingLibrary.cpp", directory
37
+ return None
12
38
 
13
39
 
14
40
  def _compile_and_link_args() -> tuple[list[str], list[str]]:
@@ -52,8 +78,7 @@ class build_ext(_build_ext):
52
78
  ) from exc
53
79
 
54
80
 
55
- setup(
56
- ext_modules=[
81
+ extensions = [
57
82
  Extension(
58
83
  "jacscanomaly._cpp_grid",
59
84
  [str(CPP_GRID_SOURCE)],
@@ -61,6 +86,22 @@ setup(
61
86
  language="c++",
62
87
  depends=[str(CPP_GRID_SOURCE)],
63
88
  )
64
- ],
89
+ ]
90
+
91
+ vbm_sources = _find_vbm_sources()
92
+ if vbm_sources is not None:
93
+ vbm_library, vbm_include = vbm_sources
94
+ extensions.append(
95
+ Extension(
96
+ "jacscanomaly._vbm_cpp",
97
+ [str(VBM_CPP_SOURCE), str(vbm_library)],
98
+ include_dirs=[np.get_include(), str(vbm_include)],
99
+ language="c++",
100
+ depends=[str(VBM_CPP_SOURCE), str(vbm_library), str(vbm_include / "VBMicrolensingLibrary.h")],
101
+ )
102
+ )
103
+
104
+ setup(
105
+ ext_modules=extensions,
65
106
  cmdclass={"build_ext": build_ext},
66
107
  )
@@ -15,6 +15,7 @@ from .singlelens_fit import (
15
15
  CPPPSPLFitter,
16
16
  FSPLFitter,
17
17
  VBMFiniteDiffFSPLFitter,
18
+ CPPVBMFSPLParallaxFitter,
18
19
  PSPLParallaxFitter,
19
20
  FSPLParallaxFitter,
20
21
  PSPLSpaceParallaxFitter,
@@ -31,27 +32,15 @@ from .template_free import (
31
32
  )
32
33
  from .planet_signal import (
33
34
  FlatBaselineDiagnostic,
34
- PlanetSignalClassification,
35
- PlanetSignalClassificationConfig,
36
- PlanetSignalClassifier,
37
- PlanetSignalComponentClassification,
35
+ PlanetFeature,
36
+ PlanetFeatureConfig,
37
+ PlanetFeatureResult,
38
38
  PlanetSignalCandidate,
39
39
  PlanetSignalConfig,
40
40
  PlanetSignalExtractor,
41
41
  PlanetSignalIteration,
42
- PlanetSignalPeak,
43
42
  PlanetSignalResult,
44
43
  )
45
- from .planet_class import (
46
- AtomFitResult,
47
- PlanetAnomalyClassifier,
48
- PlanetAnomalyFitResult,
49
- PlanetClassConfig,
50
- PSPLParams,
51
- SeedCandidate,
52
- SegmentData,
53
- SegmentModelResult,
54
- )
55
44
 
56
45
  __all__ = [
57
46
  "FinderConfig",
@@ -66,6 +55,7 @@ __all__ = [
66
55
  "CPPPSPLFitter",
67
56
  "FSPLFitter",
68
57
  "VBMFiniteDiffFSPLFitter",
58
+ "CPPVBMFSPLParallaxFitter",
69
59
  "PSPLParallaxFitter",
70
60
  "FSPLParallaxFitter",
71
61
  "PSPLSpaceParallaxFitter",
@@ -79,24 +69,14 @@ __all__ = [
79
69
  "TemplateFreeSearchConfig",
80
70
  "TemplateFreeSearchResult",
81
71
  "FlatBaselineDiagnostic",
82
- "PlanetSignalClassification",
83
- "PlanetSignalClassificationConfig",
84
- "PlanetSignalClassifier",
85
- "PlanetSignalComponentClassification",
72
+ "PlanetFeature",
73
+ "PlanetFeatureConfig",
74
+ "PlanetFeatureResult",
86
75
  "PlanetSignalCandidate",
87
76
  "PlanetSignalConfig",
88
77
  "PlanetSignalExtractor",
89
78
  "PlanetSignalIteration",
90
- "PlanetSignalPeak",
91
79
  "PlanetSignalResult",
92
- "AtomFitResult",
93
- "PlanetAnomalyClassifier",
94
- "PlanetAnomalyFitResult",
95
- "PlanetClassConfig",
96
- "PSPLParams",
97
- "SeedCandidate",
98
- "SegmentData",
99
- "SegmentModelResult",
100
80
  ]
101
81
 
102
- __version__ = "0.3.2"
82
+ __version__ = "0.5.0"
@@ -0,0 +1,278 @@
1
+ #define PY_SSIZE_T_CLEAN
2
+ #include <Python.h>
3
+ #define NPY_NO_DEPRECATED_API NPY_1_19_API_VERSION
4
+ #include <numpy/arrayobject.h>
5
+
6
+ #include "VBMicrolensingLibrary.h"
7
+
8
+ #include <algorithm>
9
+ #include <array>
10
+ #include <cmath>
11
+ #include <cstring>
12
+ #include <limits>
13
+ #include <string>
14
+ #include <vector>
15
+
16
+ namespace {
17
+
18
+ constexpr int kNParam = 6;
19
+
20
+ PyArrayObject* as_double_array(PyObject* obj) {
21
+ return reinterpret_cast<PyArrayObject*>(
22
+ PyArray_FROM_OTF(obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY));
23
+ }
24
+
25
+ struct LinearFit {
26
+ double fs = 0.0;
27
+ double fb = 0.0;
28
+ bool valid = false;
29
+ };
30
+
31
+ double sumsq(const std::vector<double>& x) {
32
+ double out = 0.0;
33
+ for (double v : x) out += v * v;
34
+ return out;
35
+ }
36
+
37
+ LinearFit solve_fluxes(const std::vector<double>& A, const double* flux, const double* ferr) {
38
+ const size_t n = A.size();
39
+ double sw = 0.0, sx = 0.0, sy = 0.0;
40
+ for (size_t i = 0; i < n; ++i) {
41
+ const double fe = std::max(ferr[i], 1e-12);
42
+ const double w = 1.0 / (fe * fe);
43
+ sw += w;
44
+ sx += w * A[i];
45
+ sy += w * flux[i];
46
+ }
47
+ if (!(sw > 0.0)) return {};
48
+ const double xm = sx / sw, ym = sy / sw;
49
+ double wxx = 0.0, wxy = 0.0;
50
+ for (size_t i = 0; i < n; ++i) {
51
+ const double fe = std::max(ferr[i], 1e-12);
52
+ const double w = 1.0 / (fe * fe);
53
+ wxx += w * (A[i] - xm) * (A[i] - xm);
54
+ wxy += w * (A[i] - xm) * (flux[i] - ym);
55
+ }
56
+ if (!(wxx > 0.0) || !std::isfinite(wxx)) return {};
57
+ return {wxy / wxx, ym - (wxy / wxx) * xm, true};
58
+ }
59
+
60
+ bool solve_linear(double a[kNParam][kNParam], double b[kNParam], double x[kNParam]) {
61
+ double m[kNParam][kNParam + 1];
62
+ for (int i = 0; i < kNParam; ++i) {
63
+ for (int j = 0; j < kNParam; ++j) m[i][j] = a[i][j];
64
+ m[i][kNParam] = b[i];
65
+ }
66
+ for (int col = 0; col < kNParam; ++col) {
67
+ int pivot = col;
68
+ for (int row = col + 1; row < kNParam; ++row) {
69
+ if (std::abs(m[row][col]) > std::abs(m[pivot][col])) pivot = row;
70
+ }
71
+ if (std::abs(m[pivot][col]) < 1e-30) return false;
72
+ if (pivot != col) {
73
+ for (int j = col; j <= kNParam; ++j) std::swap(m[col][j], m[pivot][j]);
74
+ }
75
+ const double inv = 1.0 / m[col][col];
76
+ for (int j = col; j <= kNParam; ++j) m[col][j] *= inv;
77
+ for (int row = 0; row < kNParam; ++row) {
78
+ if (row == col) continue;
79
+ const double f = m[row][col];
80
+ for (int j = col; j <= kNParam; ++j) m[row][j] -= f * m[col][j];
81
+ }
82
+ }
83
+ for (int i = 0; i < kNParam; ++i) x[i] = m[i][kNParam];
84
+ return true;
85
+ }
86
+
87
+ void clamp_q(double q[kNParam], double max_piE) {
88
+ q[1] = std::clamp(q[1], std::log(1e-6), std::log(1e8));
89
+ // Keep trial sources inside the well-behaved part of VBM's ESPL lookup
90
+ // table. Larger values are not useful for the point-lens FSPL workflow
91
+ // and make the library emit a diagnostic for every model evaluation.
92
+ q[3] = std::clamp(q[3], -50.0, std::log(10.0));
93
+ if (std::isfinite(max_piE) && max_piE > 0.0) {
94
+ q[4] = std::clamp(q[4], -max_piE, max_piE);
95
+ q[5] = std::clamp(q[5], -max_piE, max_piE);
96
+ }
97
+ }
98
+
99
+ bool residuals(
100
+ VBMicrolensing& vbm,
101
+ const double q[kNParam],
102
+ const double* time, const double* flux, const double* ferr, npy_intp n,
103
+ std::vector<double>& residual, std::vector<double>* A_out = nullptr, LinearFit* fit_out = nullptr
104
+ ) {
105
+ std::vector<double> A(static_cast<size_t>(n));
106
+ std::vector<double> y1(static_cast<size_t>(n));
107
+ std::vector<double> y2(static_cast<size_t>(n));
108
+ // VBM's bundled Sun table stores time as JD-2450000. Its table loader
109
+ // applies that offset internally, so its parallax API must receive the
110
+ // same reduced convention even when jacscanomaly's public API uses JD.
111
+ constexpr double kVBMTimeOffset = 2450000.0;
112
+ std::vector<double> vbm_time(static_cast<size_t>(n));
113
+ for (npy_intp i = 0; i < n; ++i) vbm_time[static_cast<size_t>(i)] = time[i] - kVBMTimeOffset;
114
+ // VBM convention: [u0, log(tE), t0, log(rho), piE_1, piE_2].
115
+ double p[kNParam] = {q[2], q[1], q[0] - kVBMTimeOffset, q[3], q[4], q[5]};
116
+ // ESPLMag2, used internally by this VBM call, already changes method away
117
+ // from the finite-source regime when appropriate. Give VBM every datum
118
+ // and leave that numerical decision to its native implementation.
119
+ vbm.ESPLLightCurveParallax(p, vbm_time.data(), A.data(), y1.data(), y2.data(), static_cast<int>(n));
120
+ for (double a : A) {
121
+ if (!std::isfinite(a) || a <= 0.0) {
122
+ residual.assign(static_cast<size_t>(n), 1e100);
123
+ return false;
124
+ }
125
+ }
126
+ const LinearFit fit = solve_fluxes(A, flux, ferr);
127
+ if (!fit.valid) {
128
+ residual.assign(static_cast<size_t>(n), 1e100);
129
+ return false;
130
+ }
131
+ residual.resize(static_cast<size_t>(n));
132
+ for (npy_intp i = 0; i < n; ++i) {
133
+ const double fe = std::max(ferr[i], 1e-12);
134
+ residual[static_cast<size_t>(i)] = (flux[i] - (fit.fs * A[static_cast<size_t>(i)] + fit.fb)) / fe;
135
+ }
136
+ if (A_out) *A_out = std::move(A);
137
+ if (fit_out) *fit_out = fit;
138
+ return true;
139
+ }
140
+
141
+ PyObject* fit_fspl_parallax(PyObject*, PyObject* args, PyObject* kwargs) {
142
+ PyObject *time_obj = nullptr, *flux_obj = nullptr, *ferr_obj = nullptr, *p0_obj = nullptr;
143
+ const char *coordinates = nullptr, *sun_table = nullptr, *espl_table = nullptr;
144
+ int maxiter = 200;
145
+ double damping_parameter = 1e-4, tol = 1e-5, vbm_tol = 1e-4, vbm_reltol = 1e-4;
146
+ double max_piE = 5.0;
147
+ static const char* kwlist[] = {
148
+ "time", "flux", "ferr", "p0", "coordinates", "sun_table", "espl_table",
149
+ "maxiter", "damping_parameter", "tol", "vbm_tol", "vbm_reltol", "max_piE", nullptr};
150
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOOOsss|iddddd", const_cast<char**>(kwlist),
151
+ &time_obj, &flux_obj, &ferr_obj, &p0_obj, &coordinates, &sun_table, &espl_table,
152
+ &maxiter, &damping_parameter, &tol, &vbm_tol, &vbm_reltol, &max_piE)) {
153
+ return nullptr;
154
+ }
155
+
156
+ PyArrayObject *time_arr = as_double_array(time_obj), *flux_arr = as_double_array(flux_obj);
157
+ PyArrayObject *ferr_arr = as_double_array(ferr_obj), *p0_arr = as_double_array(p0_obj);
158
+ npy_intp n = 0;
159
+ if (!time_arr || !flux_arr || !ferr_arr || !p0_arr) goto fail;
160
+ n = PyArray_DIM(time_arr, 0);
161
+ if (PyArray_NDIM(time_arr) != 1 || PyArray_NDIM(flux_arr) != 1 || PyArray_NDIM(ferr_arr) != 1 ||
162
+ PyArray_NDIM(p0_arr) != 1 || PyArray_DIM(flux_arr, 0) != n || PyArray_DIM(ferr_arr, 0) != n ||
163
+ PyArray_DIM(p0_arr, 0) < kNParam || n < 7) {
164
+ PyErr_SetString(PyExc_ValueError, "fit_fspl_parallax requires equal one-dimensional arrays, p0 with 6 values, and at least 7 data points.");
165
+ goto fail;
166
+ }
167
+ {
168
+ VBMicrolensing vbm;
169
+ vbm.Tol = vbm_tol;
170
+ vbm.RelTol = vbm_reltol;
171
+ vbm.t_in_HJD = true;
172
+ vbm.parallaxsystem = 1;
173
+ std::vector<char> coord(coordinates, coordinates + std::strlen(coordinates) + 1);
174
+ std::vector<char> sun(sun_table, sun_table + std::strlen(sun_table) + 1);
175
+ vbm.SetObjectCoordinates(coord.data());
176
+ if (!vbm.AreCoordinatesSet()) {
177
+ PyErr_SetString(PyExc_ValueError, "coordinates must be 'HH:MM:SS.s +/-DD:MM:SS.s'.");
178
+ goto fail;
179
+ }
180
+ vbm.LoadSunTable(sun.data());
181
+ vbm.LoadESPLTable(espl_table);
182
+
183
+ const double* p0 = static_cast<const double*>(PyArray_DATA(p0_arr));
184
+ double q[kNParam] = {p0[0], std::log(std::max(std::abs(p0[1]), 1e-12)), p0[2],
185
+ std::log(std::max(std::abs(p0[3]), 1e-12)), p0[4], p0[5]};
186
+ clamp_q(q, max_piE);
187
+ const double* time = static_cast<const double*>(PyArray_DATA(time_arr));
188
+ const double* flux = static_cast<const double*>(PyArray_DATA(flux_arr));
189
+ const double* ferr = static_cast<const double*>(PyArray_DATA(ferr_arr));
190
+ std::vector<double> residual;
191
+ if (!residuals(vbm, q, time, flux, ferr, n, residual)) {
192
+ PyErr_SetString(PyExc_RuntimeError, "VBMicrolensing failed to evaluate the starting FSPL-parallax model.");
193
+ goto fail;
194
+ }
195
+ double chi2 = sumsq(residual);
196
+ double lambda = std::max(damping_parameter, 1e-12);
197
+ const double fd[kNParam] = {1e-4, 1e-4, 1e-5, 1e-4, 1e-5, 1e-5};
198
+ for (int iter = 0; iter < maxiter; ++iter) {
199
+ std::array<std::vector<double>, kNParam> jac;
200
+ for (int k = 0; k < kNParam; ++k) {
201
+ double qp[kNParam], qm[kNParam];
202
+ std::copy(q, q + kNParam, qp); std::copy(q, q + kNParam, qm);
203
+ qp[k] += fd[k]; qm[k] -= fd[k]; clamp_q(qp, max_piE); clamp_q(qm, max_piE);
204
+ std::vector<double> rp, rm;
205
+ residuals(vbm, qp, time, flux, ferr, n, rp);
206
+ residuals(vbm, qm, time, flux, ferr, n, rm);
207
+ jac[k].resize(static_cast<size_t>(n));
208
+ const double inv = 1.0 / (qp[k] - qm[k]);
209
+ for (npy_intp i = 0; i < n; ++i) jac[k][static_cast<size_t>(i)] = (rp[static_cast<size_t>(i)] - rm[static_cast<size_t>(i)]) * inv;
210
+ }
211
+ double jtj[kNParam][kNParam] = {}, rhs[kNParam] = {};
212
+ for (int a = 0; a < kNParam; ++a) for (int b = 0; b < kNParam; ++b) {
213
+ double dot = 0.0;
214
+ for (npy_intp i = 0; i < n; ++i) dot += jac[a][static_cast<size_t>(i)] * jac[b][static_cast<size_t>(i)];
215
+ jtj[a][b] = dot;
216
+ if (b == 0) for (npy_intp i = 0; i < n; ++i) rhs[a] -= jac[a][static_cast<size_t>(i)] * residual[static_cast<size_t>(i)];
217
+ }
218
+ bool accepted = false;
219
+ double best_q[kNParam];
220
+ double best_chi2 = chi2;
221
+ for (int attempt = 0; attempt < 12; ++attempt) {
222
+ double mat[kNParam][kNParam], step[kNParam] = {};
223
+ for (int a = 0; a < kNParam; ++a) for (int b = 0; b < kNParam; ++b) {
224
+ mat[a][b] = jtj[a][b];
225
+ if (a == b) mat[a][b] += lambda * std::max(jtj[a][a], 1.0);
226
+ }
227
+ if (!solve_linear(mat, rhs, step)) { lambda *= 10.0; continue; }
228
+ // In the PSPL-like regime rho is only weakly identified. A
229
+ // finite-difference Jacobian can then propose an unphysical
230
+ // multi-decade logrho jump even though the other parameters
231
+ // are well constrained. Keep this coordinate in a local
232
+ // trust region; accepted LM iterations can still move rho.
233
+ step[3] = std::clamp(step[3], -0.25, 0.25);
234
+ double trial[kNParam];
235
+ for (int k = 0; k < kNParam; ++k) trial[k] = q[k] + step[k];
236
+ clamp_q(trial, max_piE);
237
+ std::vector<double> trial_residual;
238
+ residuals(vbm, trial, time, flux, ferr, n, trial_residual);
239
+ const double trial_chi2 = sumsq(trial_residual);
240
+ if (std::isfinite(trial_chi2) && trial_chi2 < best_chi2) {
241
+ std::copy(trial, trial + kNParam, best_q); best_chi2 = trial_chi2;
242
+ residual.swap(trial_residual); accepted = true; break;
243
+ }
244
+ lambda *= 10.0;
245
+ }
246
+ if (!accepted) break;
247
+ const double improvement = chi2 - best_chi2;
248
+ std::copy(best_q, best_q + kNParam, q); chi2 = best_chi2;
249
+ lambda = std::max(lambda * 0.3, 1e-12);
250
+ if (improvement < tol) break;
251
+ }
252
+ std::vector<double> A; LinearFit fit;
253
+ residuals(vbm, q, time, flux, ferr, n, residual, &A, &fit);
254
+ chi2 = sumsq(residual);
255
+ npy_intp pdims[1] = {kNParam}, ddims[1] = {n};
256
+ auto* params = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, pdims, NPY_DOUBLE));
257
+ auto* model = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, ddims, NPY_DOUBLE));
258
+ auto* raw_residual = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, ddims, NPY_DOUBLE));
259
+ if (!params || !model || !raw_residual) { Py_XDECREF(params); Py_XDECREF(model); Py_XDECREF(raw_residual); goto fail; }
260
+ double* po = static_cast<double*>(PyArray_DATA(params));
261
+ po[0] = q[0]; po[1] = std::exp(q[1]); po[2] = q[2]; po[3] = std::exp(q[3]); po[4] = q[4]; po[5] = q[5];
262
+ double* mo = static_cast<double*>(PyArray_DATA(model));
263
+ double* ro = static_cast<double*>(PyArray_DATA(raw_residual));
264
+ for (npy_intp i = 0; i < n; ++i) { mo[i] = fit.fs * A[static_cast<size_t>(i)] + fit.fb; ro[i] = flux[i] - mo[i]; }
265
+ Py_DECREF(time_arr); Py_DECREF(flux_arr); Py_DECREF(ferr_arr); Py_DECREF(p0_arr);
266
+ return Py_BuildValue("NdddNN", params, fit.fs, fit.fb, chi2, model, raw_residual);
267
+ }
268
+ fail:
269
+ Py_XDECREF(time_arr); Py_XDECREF(flux_arr); Py_XDECREF(ferr_arr); Py_XDECREF(p0_arr);
270
+ return nullptr;
271
+ }
272
+
273
+ PyMethodDef methods[] = {{"fit_fspl_parallax", reinterpret_cast<PyCFunction>(fit_fspl_parallax), METH_VARARGS | METH_KEYWORDS,
274
+ "Fit annual-parallax FSPL with VBMicrolensing and finite-difference C++ LM."}, {nullptr, nullptr, 0, nullptr}};
275
+ PyModuleDef module = {PyModuleDef_HEAD_INIT, "_vbm_cpp", "VBMicrolensing C++ backend.", -1, methods};
276
+ } // namespace
277
+
278
+ PyMODINIT_FUNC PyInit__vbm_cpp(void) { import_array(); return PyModule_Create(&module); }
@@ -288,23 +288,42 @@ class FinderConfig:
288
288
  falls below this value.
289
289
  """
290
290
 
291
- best_score_trim_percentile: float = 95.0
291
+ best_score_teff_ratio: float = 2.0
292
292
  """
293
- Upper percentile used when estimating the background spread of
294
- ``dchi2`` values for the best-candidate score.
293
+ Maximum timescale ratio used for best-score background clusters.
295
294
 
296
- When selecting the best candidate, the score is computed from the
297
- other cluster peaks after trimming values above this percentile.
298
- This makes the score less sensitive to a few strong secondary peaks
299
- that would otherwise inflate the background standard deviation.
295
+ The score compares a candidate only with clusters from the same season
296
+ whose ``teff`` differs by at most this factor. If too few such clusters
297
+ exist, the nearest timescales from the same season are added.
298
+ """
299
+
300
+ best_score_min_reference_clusters: int = 8
301
+ """
302
+ Preferred minimum number of same-season background clusters.
303
+
304
+ When the local ``teff`` band contains fewer clusters, the nearest
305
+ same-season timescales are added up to this count. A score still requires
306
+ at least two usable background clusters.
307
+ """
308
+
309
+ best_score_upper_clip_sigma: float = 5.0
310
+ """
311
+ One-sided robust clipping threshold for strong secondary candidates.
300
312
 
301
- Set to ``100`` to disable trimming.
313
+ Background clusters above ``median + value * robust_scale`` are excluded
314
+ iteratively. The center and scale are estimated with the median and MAD,
315
+ so strong secondary anomalies do not inflate the score normalization.
316
+ Set to ``inf`` to disable upper clipping.
302
317
  """
303
318
 
319
+ best_score_clip_maxiters: int = 3
320
+ """Maximum number of one-sided robust clipping iterations."""
321
+
304
322
  candidate_criteria: Optional[CandidateCriteria] = None
305
323
  """
306
- Optional criteria to reject anomaly candidates before best-candidate
307
- selection. If ``None``, no additional filtering is applied.
324
+ Optional criteria applied to raw cluster peaks before best-candidate
325
+ selection. The criteria do not alter cluster extraction or the score
326
+ background. If ``None``, no additional selection is applied.
308
327
  """
309
328
 
310
329
  # ==================================================
@@ -319,14 +338,38 @@ class FinderConfig:
319
338
  - ``"jax"`` uses the JAX vectorized/chunked implementation.
320
339
  """
321
340
 
322
- single_fit_backend: Literal["jax", "cpp"] = "cpp"
341
+ single_fit_backend: Literal["jax", "cpp", "vbm_cpp"] = "cpp"
323
342
  """
324
343
  Single-lens fit backend.
325
344
 
326
- ``"cpp"`` is implemented for ``fitter_kind="pspl"``. Other single-lens
327
- models continue to use the JAX fitters.
345
+ ``"cpp"`` is implemented for ``fitter_kind="pspl"``. ``"vbm_cpp"`` is
346
+ implemented for ``fitter_kind="fspl_parallax"`` and uses the native
347
+ VBMicrolensing finite-source magnification with the C++ LM solver.
348
+ Other combinations use the JAX fitters.
328
349
  """
329
350
 
351
+ vbm_cpp_piE_seed_values: tuple[float, ...] = (0.0,)
352
+ """Per-component piE values used for automatic VBM-C++ multistart fits.
353
+
354
+ When ``fitter_kind="fspl_parallax"`` and
355
+ ``single_fit_backend="vbm_cpp"``, jacscanomaly combines each automatic
356
+ ``(t0, tE, u0)`` seed with this Cartesian piE grid before C++ LM fitting.
357
+ The default is a single safe zero-parallax start. Supply, for example,
358
+ ``(-0.5, 0.0, 0.5)`` to opt into a Cartesian parallax multistart.
359
+ """
360
+
361
+ vbm_cpp_logrho_seed_values: tuple[float, ...] = (-3.0,)
362
+ """log-rho values combined with automatic VBM-C++ parallax seeds."""
363
+
364
+ vbm_cpp_maxiter: int = 200
365
+ """Maximum C++ LM iterations per VBM automatic-start trial."""
366
+
367
+ vbm_cpp_damping_parameter: float = 1.0e-4
368
+ """Initial LM damping parameter for the native VBM C++ backend."""
369
+
370
+ vbm_cpp_tol: float = 1.0e-5
371
+ """C++ LM convergence tolerance for the native VBM backend."""
372
+
330
373
  grid_chunked: bool = False
331
374
  """
332
375
  Force chunked execution of the grid scan.