pyAethra 0.1.0__py3-none-any.whl
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.
- pyAethra/__about__.py +5 -0
- pyAethra/__init__.py +80 -0
- pyAethra/achromatic.py +121 -0
- pyAethra/cli.py +122 -0
- pyAethra/config.py +40 -0
- pyAethra/detection.py +151 -0
- pyAethra/io.py +171 -0
- pyAethra/pipeline.py +236 -0
- pyAethra/pspl.py +134 -0
- pyAethra/schema.py +25 -0
- pyAethra/seasons.py +78 -0
- pyAethra/variability.py +151 -0
- pyaethra-0.1.0.dist-info/METADATA +227 -0
- pyaethra-0.1.0.dist-info/RECORD +17 -0
- pyaethra-0.1.0.dist-info/WHEEL +4 -0
- pyaethra-0.1.0.dist-info/entry_points.txt +2 -0
- pyaethra-0.1.0.dist-info/licenses/LICENSE +21 -0
pyAethra/__about__.py
ADDED
pyAethra/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pyAethra — Microlensing event-detection pipeline
|
|
3
|
+
===================================================
|
|
4
|
+
|
|
5
|
+
Works with any photometric dataset that has time, magnitude, and
|
|
6
|
+
magnitude-error columns (names are configurable).
|
|
7
|
+
|
|
8
|
+
Quick start
|
|
9
|
+
-----------
|
|
10
|
+
from pyAethra import load_and_run
|
|
11
|
+
|
|
12
|
+
config = {
|
|
13
|
+
"time_col": "bjd",
|
|
14
|
+
"mag_col": "mag",
|
|
15
|
+
"err_col": "mag_err",
|
|
16
|
+
# ... see the README for the full configuration reference
|
|
17
|
+
}
|
|
18
|
+
results_df = load_and_run("data.parquet", config)
|
|
19
|
+
|
|
20
|
+
The most common entry points are :func:`load_and_run` (auto-dispatches on the
|
|
21
|
+
input type) and :func:`run_pipeline_from_dataframe` (runs on an in-memory
|
|
22
|
+
DataFrame). The lower-level building blocks (bump detection, periodicity vetoes,
|
|
23
|
+
PSPL fitting, etc.) are also importable from their respective submodules.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from .achromatic import achromatic_test_from_event
|
|
27
|
+
from .config import load_config
|
|
28
|
+
from .detection import (
|
|
29
|
+
detect_bump,
|
|
30
|
+
flatness_chi2,
|
|
31
|
+
has_consecutive_outliers,
|
|
32
|
+
recurrent_bump_veto,
|
|
33
|
+
)
|
|
34
|
+
from .io import load_and_run
|
|
35
|
+
from .pipeline import run_pipeline_from_dataframe
|
|
36
|
+
from .pspl import (
|
|
37
|
+
fit_pspl,
|
|
38
|
+
fit_pspl_candidate,
|
|
39
|
+
pspl_magnification,
|
|
40
|
+
solve_fs_fb,
|
|
41
|
+
)
|
|
42
|
+
from .schema import OUTPUT_COLUMNS
|
|
43
|
+
from .seasons import analyze_season_scan, split_into_seasons
|
|
44
|
+
from .variability import (
|
|
45
|
+
is_non_flat_lightcurve,
|
|
46
|
+
is_periodic,
|
|
47
|
+
lomb_scargle_test,
|
|
48
|
+
periodic_veto_from_other_seasons,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__version__ = "0.1.0"
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"__version__",
|
|
55
|
+
"OUTPUT_COLUMNS",
|
|
56
|
+
# entry points
|
|
57
|
+
"load_and_run",
|
|
58
|
+
"run_pipeline_from_dataframe",
|
|
59
|
+
"load_config",
|
|
60
|
+
# detection
|
|
61
|
+
"has_consecutive_outliers",
|
|
62
|
+
"flatness_chi2",
|
|
63
|
+
"detect_bump",
|
|
64
|
+
"recurrent_bump_veto",
|
|
65
|
+
# variability / periodicity
|
|
66
|
+
"is_non_flat_lightcurve",
|
|
67
|
+
"lomb_scargle_test",
|
|
68
|
+
"is_periodic",
|
|
69
|
+
"periodic_veto_from_other_seasons",
|
|
70
|
+
# achromatic
|
|
71
|
+
"achromatic_test_from_event",
|
|
72
|
+
# PSPL
|
|
73
|
+
"pspl_magnification",
|
|
74
|
+
"solve_fs_fb",
|
|
75
|
+
"fit_pspl",
|
|
76
|
+
"fit_pspl_candidate",
|
|
77
|
+
# seasons
|
|
78
|
+
"split_into_seasons",
|
|
79
|
+
"analyze_season_scan",
|
|
80
|
+
]
|
pyAethra/achromatic.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Achromaticity test: compare the primary detection band to secondary bands."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
__all__ = ["achromatic_test_from_event"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def achromatic_test_from_event(
|
|
9
|
+
obj_df, time_col, mag_col, err_col, filter_col, season_col,
|
|
10
|
+
best_season, t0_guess_raw, best_window_days,
|
|
11
|
+
primary_filter="F146", secondary_filters=None, min_points=4,
|
|
12
|
+
):
|
|
13
|
+
"""
|
|
14
|
+
Test whether the event is achromatic by comparing the primary detection
|
|
15
|
+
band against one or more secondary bands.
|
|
16
|
+
|
|
17
|
+
secondary_filters can be a string (one band) or a list of strings
|
|
18
|
+
(multiple bands, e.g. ["F087", "F213"]). Missing or too-sparse bands
|
|
19
|
+
abstain (nan) rather than veto.
|
|
20
|
+
|
|
21
|
+
Return values
|
|
22
|
+
-------------
|
|
23
|
+
True : primary brightens AND at least one secondary confirms,
|
|
24
|
+
none clearly disagree.
|
|
25
|
+
False : primary brightens BUT at least one secondary clearly disagrees
|
|
26
|
+
(wrong direction or peak time offset > tolerance) → chromatic veto.
|
|
27
|
+
nan : cannot make a statement (no filter col, no t0, primary too sparse,
|
|
28
|
+
or all secondaries abstained).
|
|
29
|
+
"""
|
|
30
|
+
if filter_col is None or filter_col not in obj_df.columns:
|
|
31
|
+
return np.nan
|
|
32
|
+
|
|
33
|
+
if not np.isfinite(t0_guess_raw):
|
|
34
|
+
return np.nan
|
|
35
|
+
|
|
36
|
+
if secondary_filters is None:
|
|
37
|
+
return np.nan
|
|
38
|
+
if isinstance(secondary_filters, str):
|
|
39
|
+
secondary_filters = [secondary_filters]
|
|
40
|
+
|
|
41
|
+
season_df = obj_df[obj_df[season_col] == best_season].copy()
|
|
42
|
+
if len(season_df) == 0:
|
|
43
|
+
return np.nan
|
|
44
|
+
|
|
45
|
+
window = best_window_days
|
|
46
|
+
if not np.isfinite(window) or window <= 0:
|
|
47
|
+
window = 5.0
|
|
48
|
+
half_window = max(2.0, 1.5 * window)
|
|
49
|
+
time_tol = max(2.0, half_window)
|
|
50
|
+
|
|
51
|
+
def summarize(df_band):
|
|
52
|
+
"""Return summary dict, or None if the band is too sparse to judge."""
|
|
53
|
+
t = df_band[time_col].to_numpy(dtype=float)
|
|
54
|
+
m = df_band[mag_col].to_numpy(dtype=float)
|
|
55
|
+
e = df_band[err_col].to_numpy(dtype=float)
|
|
56
|
+
valid = np.isfinite(t) & np.isfinite(m) & np.isfinite(e) & (e > 0)
|
|
57
|
+
t, m, e = t[valid], m[valid], e[valid]
|
|
58
|
+
if len(t) < min_points:
|
|
59
|
+
return None
|
|
60
|
+
event_mask = np.abs(t - t0_guess_raw) <= half_window
|
|
61
|
+
base_mask = np.abs(t - t0_guess_raw) > half_window
|
|
62
|
+
if event_mask.sum() < 2 or base_mask.sum() < 3:
|
|
63
|
+
return None
|
|
64
|
+
baseline_mag = np.median(m[base_mask])
|
|
65
|
+
baseline_scatter = 1.4826 * np.median(np.abs(m[base_mask] - baseline_mag))
|
|
66
|
+
if not np.isfinite(baseline_scatter) or baseline_scatter <= 0:
|
|
67
|
+
baseline_scatter = np.std(m[base_mask])
|
|
68
|
+
event_mag = m[event_mask]
|
|
69
|
+
event_time = t[event_mask]
|
|
70
|
+
event_err = e[event_mask]
|
|
71
|
+
i_peak = np.argmin(event_mag)
|
|
72
|
+
delta_mag = baseline_mag - event_mag[i_peak]
|
|
73
|
+
local_err = np.median(event_err)
|
|
74
|
+
denom = max(local_err, baseline_scatter, 1e-6)
|
|
75
|
+
return {
|
|
76
|
+
"peak_time": event_time[i_peak],
|
|
77
|
+
"delta_mag": delta_mag,
|
|
78
|
+
"significance": delta_mag / denom,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
# ── primary band ──────────────────────────────────────────────────────────
|
|
82
|
+
df_primary = season_df[season_df[filter_col] == primary_filter].copy()
|
|
83
|
+
s_primary = summarize(df_primary)
|
|
84
|
+
if s_primary is None:
|
|
85
|
+
return np.nan
|
|
86
|
+
if s_primary["delta_mag"] <= 0:
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
# ── secondary bands ───────────────────────────────────────────────────────
|
|
90
|
+
band_votes = []
|
|
91
|
+
for filt in secondary_filters:
|
|
92
|
+
if filt not in season_df[filter_col].values:
|
|
93
|
+
band_votes.append(None)
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
s = summarize(season_df[season_df[filter_col] == filt].copy())
|
|
97
|
+
|
|
98
|
+
if s is None:
|
|
99
|
+
band_votes.append(None)
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
if s["delta_mag"] <= 0:
|
|
103
|
+
band_votes.append(False)
|
|
104
|
+
continue
|
|
105
|
+
|
|
106
|
+
if abs(s["peak_time"] - s_primary["peak_time"]) > time_tol:
|
|
107
|
+
band_votes.append(False)
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
if s["significance"] < 2.0:
|
|
111
|
+
band_votes.append(None)
|
|
112
|
+
continue
|
|
113
|
+
|
|
114
|
+
band_votes.append(True)
|
|
115
|
+
|
|
116
|
+
# ── combine votes ─────────────────────────────────────────────────────────
|
|
117
|
+
if any(v is False for v in band_votes):
|
|
118
|
+
return False
|
|
119
|
+
if any(v is True for v in band_votes):
|
|
120
|
+
return True
|
|
121
|
+
return np.nan
|
pyAethra/cli.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Command-line interface.
|
|
2
|
+
|
|
3
|
+
Two ways to configure a run:
|
|
4
|
+
|
|
5
|
+
# everything in a YAML file
|
|
6
|
+
pyAethra data.parquet --config config.yaml
|
|
7
|
+
|
|
8
|
+
# or via flags (flags override anything also set in --config)
|
|
9
|
+
pyAethra "lc/*.txt" --columns bjd mag mag_err -o results.csv
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from .config import load_config
|
|
16
|
+
from .io import load_and_run
|
|
17
|
+
|
|
18
|
+
# Maps an argparse destination to the config key it sets. Most match 1:1;
|
|
19
|
+
# ffp_te_max differs because config uses the mixed-case physics symbol tE.
|
|
20
|
+
_FLAG_TO_CONFIG = {
|
|
21
|
+
"time_col": "time_col",
|
|
22
|
+
"mag_col": "mag_col",
|
|
23
|
+
"err_col": "err_col",
|
|
24
|
+
"group_col": "group_col",
|
|
25
|
+
"filter_col": "filter_col",
|
|
26
|
+
"target_filter": "target_filter",
|
|
27
|
+
"primary_filter": "primary_filter",
|
|
28
|
+
"secondary_filters": "secondary_filters",
|
|
29
|
+
"min_points": "min_points",
|
|
30
|
+
"fap_threshold": "fap_threshold",
|
|
31
|
+
"season_gap_days": "season_gap_days",
|
|
32
|
+
"ffp_te_max": "ffp_tE_max",
|
|
33
|
+
"good_pspl_chi2": "good_pspl_chi2",
|
|
34
|
+
"chromatic_min_points": "chromatic_min_points",
|
|
35
|
+
"sep": "sep",
|
|
36
|
+
"columns": "columns",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
41
|
+
p = argparse.ArgumentParser(
|
|
42
|
+
prog="pyAethra",
|
|
43
|
+
description="Run the microlensing event-detection pipeline on a dataset.",
|
|
44
|
+
)
|
|
45
|
+
p.add_argument(
|
|
46
|
+
"input_path",
|
|
47
|
+
help="A table file (.parquet/.fits/.csv/.txt) or a glob pattern for "
|
|
48
|
+
"per-object files.",
|
|
49
|
+
)
|
|
50
|
+
p.add_argument(
|
|
51
|
+
"-c",
|
|
52
|
+
"--config",
|
|
53
|
+
default=None,
|
|
54
|
+
help="Path to a YAML config file. Any flags given below override it.",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# All config flags default to None so we can tell whether the user set them.
|
|
58
|
+
# Unset keys fall back to the pipeline's built-in defaults (shown below).
|
|
59
|
+
p.add_argument("--time-col", default=None, help="Time column name (default: bjd)")
|
|
60
|
+
p.add_argument("--mag-col", default=None, help="Magnitude column name (default: mag)")
|
|
61
|
+
p.add_argument("--err-col", default=None, help="Error column name (default: mag_err)")
|
|
62
|
+
p.add_argument("--group-col", default=None, help="Column identifying each object (e.g. 'name')")
|
|
63
|
+
p.add_argument("--filter-col", default=None, help="Filter/band column name (enables achromatic test)")
|
|
64
|
+
p.add_argument("--target-filter", default=None, help="Primary detection band (default: F146)")
|
|
65
|
+
p.add_argument("--primary-filter", default=None, help="Primary band for the achromatic test (default: F146)")
|
|
66
|
+
p.add_argument("--secondary-filters", default=None, nargs="*", help="Secondary bands for the achromatic test")
|
|
67
|
+
p.add_argument("--min-points", type=int, default=None, help="Minimum points per season (default: 10)")
|
|
68
|
+
p.add_argument("--fap-threshold", type=float, default=None, help="Periodicity false-alarm threshold (default: 0.01)")
|
|
69
|
+
p.add_argument("--season-gap-days", type=float, default=None, help="Day gap separating seasons (default: 100)")
|
|
70
|
+
p.add_argument("--ffp-te-max", type=float, default=None, help="Max tE (days) for an FFP candidate (default: 2.0)")
|
|
71
|
+
p.add_argument("--good-pspl-chi2", type=float, default=None, help="Reduced chi2 threshold for a good PSPL fit (default: 2.5)")
|
|
72
|
+
p.add_argument("--chromatic-min-points", type=int, default=None, help="Min points per band for the achromatic test (default: 5)")
|
|
73
|
+
p.add_argument("--sep", default=None, help="Column separator regex for text files (default: whitespace)")
|
|
74
|
+
p.add_argument("--header", default=None, help="Header row index for text/CSV files (e.g. 0)")
|
|
75
|
+
p.add_argument("--columns", default=None, nargs="*", help="Column names when the file has no header")
|
|
76
|
+
|
|
77
|
+
p.add_argument("-o", "--output", default=None, help="Path to write results as CSV")
|
|
78
|
+
p.add_argument("--debug", action="store_true", help="Print a per-object veto breakdown")
|
|
79
|
+
return p
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def build_config(args) -> dict:
|
|
83
|
+
"""Assemble the config dict. Precedence: CLI flag > --config YAML > defaults."""
|
|
84
|
+
config = {}
|
|
85
|
+
if args.config:
|
|
86
|
+
config.update(load_config(args.config))
|
|
87
|
+
|
|
88
|
+
for dest, key in _FLAG_TO_CONFIG.items():
|
|
89
|
+
value = getattr(args, dest)
|
|
90
|
+
if value is not None:
|
|
91
|
+
config[key] = value
|
|
92
|
+
|
|
93
|
+
if args.header is not None:
|
|
94
|
+
config["header"] = int(args.header)
|
|
95
|
+
|
|
96
|
+
# The three required columns must exist; fall back to conventional names.
|
|
97
|
+
config.setdefault("time_col", "bjd")
|
|
98
|
+
config.setdefault("mag_col", "mag")
|
|
99
|
+
config.setdefault("err_col", "mag_err")
|
|
100
|
+
return config
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def main(argv=None) -> int:
|
|
104
|
+
args = build_parser().parse_args(argv)
|
|
105
|
+
config = build_config(args)
|
|
106
|
+
|
|
107
|
+
results = load_and_run(args.input_path, config, debug=args.debug)
|
|
108
|
+
|
|
109
|
+
print(f"\nPipeline complete — {len(results)} object(s) processed.")
|
|
110
|
+
print(f" is_candidate: {int(results['is_candidate'].sum())}")
|
|
111
|
+
print(f" is_ffp_candidate: {int(results['is_ffp_candidate'].sum())}")
|
|
112
|
+
print(f" is_variable_star: {int(results['is_variable_star'].sum())}")
|
|
113
|
+
|
|
114
|
+
if args.output:
|
|
115
|
+
results.to_csv(args.output, index=False)
|
|
116
|
+
print(f"\nResults written to {args.output}")
|
|
117
|
+
|
|
118
|
+
return 0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
sys.exit(main())
|
pyAethra/config.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Load pipeline configuration from a YAML file."""
|
|
2
|
+
|
|
3
|
+
import yaml
|
|
4
|
+
|
|
5
|
+
__all__ = ["load_config"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def load_config(path):
|
|
9
|
+
"""Load a pipeline configuration from a YAML file into a plain dict.
|
|
10
|
+
|
|
11
|
+
The returned dict is suitable for passing straight to
|
|
12
|
+
:func:`pyAethra.load_and_run` or :func:`pyAethra.run_pipeline_from_dataframe`.
|
|
13
|
+
|
|
14
|
+
Keys omitted from the file fall back to the pipeline's built-in defaults
|
|
15
|
+
at run time, with one exception: the required column keys ``time_col``,
|
|
16
|
+
``mag_col``, and ``err_col`` must be present (either in the file or supplied
|
|
17
|
+
another way). YAML ``null`` maps to Python ``None`` (e.g. ``group_col: null``
|
|
18
|
+
means "one object per file").
|
|
19
|
+
|
|
20
|
+
Parameters
|
|
21
|
+
----------
|
|
22
|
+
path : str
|
|
23
|
+
Path to a YAML file.
|
|
24
|
+
|
|
25
|
+
Returns
|
|
26
|
+
-------
|
|
27
|
+
dict
|
|
28
|
+
Parsed configuration. An empty file yields an empty dict.
|
|
29
|
+
"""
|
|
30
|
+
with open(path) as fh:
|
|
31
|
+
data = yaml.safe_load(fh)
|
|
32
|
+
|
|
33
|
+
if data is None:
|
|
34
|
+
return {}
|
|
35
|
+
if not isinstance(data, dict):
|
|
36
|
+
raise ValueError(
|
|
37
|
+
f"Config file {path!r} must contain a YAML mapping (key: value pairs), "
|
|
38
|
+
f"got {type(data).__name__}."
|
|
39
|
+
)
|
|
40
|
+
return data
|
pyAethra/detection.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Outlier, flatness, and bump-detection routines."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"has_consecutive_outliers",
|
|
8
|
+
"flatness_chi2",
|
|
9
|
+
"detect_bump",
|
|
10
|
+
"recurrent_bump_veto",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def has_consecutive_outliers(threshold_mask, n_consecutive=3):
|
|
15
|
+
count = 0
|
|
16
|
+
for val in threshold_mask:
|
|
17
|
+
if val:
|
|
18
|
+
count += 1
|
|
19
|
+
if count >= n_consecutive:
|
|
20
|
+
return True
|
|
21
|
+
else:
|
|
22
|
+
count = 0
|
|
23
|
+
return False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def flatness_chi2(flux, flux_err):
|
|
27
|
+
flux = np.asarray(flux, dtype=float)
|
|
28
|
+
flux_err = np.asarray(flux_err, dtype=float)
|
|
29
|
+
|
|
30
|
+
valid = np.isfinite(flux) & np.isfinite(flux_err) & (flux_err > 0)
|
|
31
|
+
flux = flux[valid]
|
|
32
|
+
flux_err = flux_err[valid]
|
|
33
|
+
|
|
34
|
+
if len(flux) < 2:
|
|
35
|
+
return np.nan, np.nan, np.nan
|
|
36
|
+
|
|
37
|
+
w = 1.0 / flux_err**2
|
|
38
|
+
wsum = np.sum(w)
|
|
39
|
+
if not np.isfinite(wsum) or wsum <= 0:
|
|
40
|
+
return np.nan, np.nan, np.nan
|
|
41
|
+
|
|
42
|
+
c = np.sum(w * flux) / wsum
|
|
43
|
+
chi2 = np.sum(w * (flux - c) ** 2)
|
|
44
|
+
dof = len(flux) - 1
|
|
45
|
+
chi2_red = chi2 / dof if dof > 0 else np.nan
|
|
46
|
+
|
|
47
|
+
return chi2, dof, chi2_red
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def detect_bump(time, mags, mag_err, window_days=(1, 2, 5, 10, 20, 50),
|
|
51
|
+
snr_threshold=3.0, n_consecutive=3):
|
|
52
|
+
time = np.asarray(time, dtype=float)
|
|
53
|
+
mags = np.asarray(mags, dtype=float)
|
|
54
|
+
mag_err = np.asarray(mag_err, dtype=float)
|
|
55
|
+
|
|
56
|
+
valid = np.isfinite(time) & np.isfinite(mags) & np.isfinite(mag_err) & (mag_err > 0)
|
|
57
|
+
time, mags, mag_err = time[valid], mags[valid], mag_err[valid]
|
|
58
|
+
|
|
59
|
+
if len(mags) < 5:
|
|
60
|
+
return False, np.nan, np.nan
|
|
61
|
+
|
|
62
|
+
dt = np.diff(time)
|
|
63
|
+
dt = dt[np.isfinite(dt) & (dt > 0)]
|
|
64
|
+
if len(dt) == 0:
|
|
65
|
+
return False, np.nan, np.nan
|
|
66
|
+
|
|
67
|
+
cadence = np.median(dt)
|
|
68
|
+
|
|
69
|
+
flux = 10 ** (-0.4 * mags)
|
|
70
|
+
flux_err = 0.4 * np.log(10) * flux * mag_err
|
|
71
|
+
|
|
72
|
+
valid_flux = np.isfinite(flux) & np.isfinite(flux_err) & (flux_err > 0)
|
|
73
|
+
flux = flux[valid_flux]
|
|
74
|
+
flux_err = flux_err[valid_flux]
|
|
75
|
+
|
|
76
|
+
if len(flux) < 5:
|
|
77
|
+
return False, np.nan, np.nan
|
|
78
|
+
|
|
79
|
+
baseline_flux = np.percentile(flux, 30)
|
|
80
|
+
weighted_excess = (flux - baseline_flux) / flux_err
|
|
81
|
+
|
|
82
|
+
best_snr = -np.inf
|
|
83
|
+
best_window_days = np.nan
|
|
84
|
+
|
|
85
|
+
for w_days in window_days:
|
|
86
|
+
w_pts = max(n_consecutive, int(round(w_days / cadence)))
|
|
87
|
+
if w_pts >= len(flux):
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
rolling_snr = (
|
|
91
|
+
pd.Series(weighted_excess)
|
|
92
|
+
.rolling(w_pts, center=True, min_periods=w_pts)
|
|
93
|
+
.sum()
|
|
94
|
+
.to_numpy()
|
|
95
|
+
/ np.sqrt(w_pts)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
if len(rolling_snr) == 0 or not np.any(np.isfinite(rolling_snr)):
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
peak_snr = np.nanmax(rolling_snr)
|
|
102
|
+
if np.isfinite(peak_snr) and peak_snr > best_snr:
|
|
103
|
+
best_snr = peak_snr
|
|
104
|
+
best_window_days = float(w_days)
|
|
105
|
+
|
|
106
|
+
mask = rolling_snr > snr_threshold
|
|
107
|
+
if has_consecutive_outliers(mask, n_consecutive=n_consecutive):
|
|
108
|
+
return True, float(w_days), float(peak_snr)
|
|
109
|
+
|
|
110
|
+
return False, best_window_days, (best_snr if np.isfinite(best_snr) else np.nan)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def recurrent_bump_veto(
|
|
114
|
+
obj_df_primary,
|
|
115
|
+
best_season,
|
|
116
|
+
best_bump_snr,
|
|
117
|
+
time_col="bjd",
|
|
118
|
+
mag_col="mag",
|
|
119
|
+
err_col="mag_err",
|
|
120
|
+
season_col="season_id",
|
|
121
|
+
min_points=10,
|
|
122
|
+
min_other_bump_seasons=1,
|
|
123
|
+
):
|
|
124
|
+
other_hits = []
|
|
125
|
+
|
|
126
|
+
for season_id, season_df in obj_df_primary.groupby(season_col):
|
|
127
|
+
if season_id == best_season:
|
|
128
|
+
continue
|
|
129
|
+
if len(season_df) < min_points:
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
bump_flag, best_window, bump_snr = detect_bump(
|
|
133
|
+
season_df[time_col].to_numpy(),
|
|
134
|
+
season_df[mag_col].to_numpy(),
|
|
135
|
+
season_df[err_col].to_numpy(),
|
|
136
|
+
window_days=(5, 10, 20, 50),
|
|
137
|
+
snr_threshold=4.0,
|
|
138
|
+
n_consecutive=3,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
if not bump_flag or not np.isfinite(bump_snr):
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
strong_enough = bump_snr >= max(25.0, 0.25 * best_bump_snr)
|
|
145
|
+
broad_enough = np.isfinite(best_window) and (best_window >= 5)
|
|
146
|
+
|
|
147
|
+
if strong_enough and broad_enough:
|
|
148
|
+
other_hits.append((season_id, bump_snr, best_window))
|
|
149
|
+
|
|
150
|
+
veto = len(other_hits) >= min_other_bump_seasons
|
|
151
|
+
return veto, other_hits
|
pyAethra/io.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Input loaders and the auto-dispatching entry point."""
|
|
2
|
+
|
|
3
|
+
import glob
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from .pipeline import run_pipeline_from_dataframe
|
|
9
|
+
from .schema import OUTPUT_COLUMNS
|
|
10
|
+
|
|
11
|
+
__all__ = ["load_and_run"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _read_table_file(filepath, config):
|
|
15
|
+
"""
|
|
16
|
+
Read a single table file into a DataFrame.
|
|
17
|
+
Supports: .parquet, .fits / .fit, .csv, .tsv, and any whitespace-delimited
|
|
18
|
+
text file (including headerless .txt).
|
|
19
|
+
"""
|
|
20
|
+
ext = os.path.splitext(filepath)[1].lower()
|
|
21
|
+
|
|
22
|
+
if ext == ".parquet":
|
|
23
|
+
return pd.read_parquet(filepath)
|
|
24
|
+
|
|
25
|
+
if ext in (".fits", ".fit"):
|
|
26
|
+
from astropy.table import Table
|
|
27
|
+
return Table.read(filepath).to_pandas()
|
|
28
|
+
|
|
29
|
+
return pd.read_csv(
|
|
30
|
+
filepath,
|
|
31
|
+
sep=config.get("sep", r"\s+"),
|
|
32
|
+
names=config.get("columns"),
|
|
33
|
+
header=config.get("header", None),
|
|
34
|
+
engine="python",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _file_stem(path, primary_filter, secondary_filter):
|
|
39
|
+
"""Strip filter tags and extension to get a matchable object key."""
|
|
40
|
+
base = os.path.basename(path)
|
|
41
|
+
for tag in (f"_{primary_filter}", f"_{secondary_filter}",
|
|
42
|
+
f"-{primary_filter}", f"-{secondary_filter}"):
|
|
43
|
+
base = base.replace(tag, "")
|
|
44
|
+
return os.path.splitext(base)[0]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _run_single_table(filepath_or_df, config, debug=False):
|
|
48
|
+
"""One file (or DataFrame) that may contain many objects via group_col."""
|
|
49
|
+
if isinstance(filepath_or_df, pd.DataFrame):
|
|
50
|
+
df = filepath_or_df
|
|
51
|
+
label = "<DataFrame>"
|
|
52
|
+
else:
|
|
53
|
+
label = filepath_or_df
|
|
54
|
+
print(f"Reading {label} …")
|
|
55
|
+
df = _read_table_file(filepath_or_df, config)
|
|
56
|
+
|
|
57
|
+
print(f" {len(df):,} rows, columns: {list(df.columns)}")
|
|
58
|
+
return run_pipeline_from_dataframe(df, config, debug=debug)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _run_per_object_files(pattern, config, debug=False):
|
|
62
|
+
"""One lightcurve per file; filename becomes the object name."""
|
|
63
|
+
files = sorted(glob.glob(pattern))
|
|
64
|
+
if not files:
|
|
65
|
+
print(f"[WARNING] No files matched: {pattern!r}")
|
|
66
|
+
return pd.DataFrame(columns=OUTPUT_COLUMNS)
|
|
67
|
+
|
|
68
|
+
print(f"Found {len(files)} file(s) matching {pattern!r}")
|
|
69
|
+
all_results = []
|
|
70
|
+
for filepath in files:
|
|
71
|
+
try:
|
|
72
|
+
df = _read_table_file(filepath, config)
|
|
73
|
+
except Exception as exc:
|
|
74
|
+
print(f" [WARNING] Could not read {filepath}: {exc}")
|
|
75
|
+
continue
|
|
76
|
+
result = run_pipeline_from_dataframe(df, {**config, "group_col": None}, debug=debug)
|
|
77
|
+
result = result.copy()
|
|
78
|
+
result.loc[:, "name"] = os.path.basename(filepath)
|
|
79
|
+
all_results.append(result)
|
|
80
|
+
|
|
81
|
+
if not all_results:
|
|
82
|
+
return pd.DataFrame(columns=OUTPUT_COLUMNS)
|
|
83
|
+
return pd.concat(all_results, ignore_index=True)[OUTPUT_COLUMNS]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _run_paired_files(primary_pattern, secondary_pattern, config, debug=False):
|
|
87
|
+
"""Two per-filter files per object, matched by filename stem."""
|
|
88
|
+
pf = config.get("primary_filter", "W149")
|
|
89
|
+
sf = config.get("secondary_filter", "Z087")
|
|
90
|
+
fc = config.get("filter_col", "filt")
|
|
91
|
+
|
|
92
|
+
primary_files = {_file_stem(f, pf, sf): f for f in glob.glob(primary_pattern)}
|
|
93
|
+
secondary_files = {_file_stem(f, pf, sf): f for f in glob.glob(secondary_pattern)}
|
|
94
|
+
all_keys = sorted(set(primary_files) | set(secondary_files))
|
|
95
|
+
|
|
96
|
+
if not all_keys:
|
|
97
|
+
print(f"[WARNING] No files matched: {primary_pattern!r} / {secondary_pattern!r}")
|
|
98
|
+
return pd.DataFrame(columns=OUTPUT_COLUMNS)
|
|
99
|
+
|
|
100
|
+
print(f"Found {len(all_keys)} object(s) across paired filter files")
|
|
101
|
+
all_results = []
|
|
102
|
+
for key in all_keys:
|
|
103
|
+
pieces = []
|
|
104
|
+
for filt, fmap in [(pf, primary_files), (sf, secondary_files)]:
|
|
105
|
+
if key not in fmap:
|
|
106
|
+
continue
|
|
107
|
+
try:
|
|
108
|
+
part = _read_table_file(fmap[key], config)
|
|
109
|
+
except Exception as exc:
|
|
110
|
+
print(f" [WARNING] Could not read {fmap[key]}: {exc}")
|
|
111
|
+
continue
|
|
112
|
+
part[fc] = filt
|
|
113
|
+
pieces.append(part)
|
|
114
|
+
if not pieces:
|
|
115
|
+
continue
|
|
116
|
+
df_obj = pd.concat(pieces, ignore_index=True)
|
|
117
|
+
df_obj["name"] = key
|
|
118
|
+
result = run_pipeline_from_dataframe(df_obj, config, debug=debug)
|
|
119
|
+
result = result.copy()
|
|
120
|
+
result.loc[:, "name"] = key
|
|
121
|
+
all_results.append(result)
|
|
122
|
+
|
|
123
|
+
if not all_results:
|
|
124
|
+
return pd.DataFrame(columns=OUTPUT_COLUMNS)
|
|
125
|
+
return pd.concat(all_results, ignore_index=True)[OUTPUT_COLUMNS]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def load_and_run(input_path, config, debug=False):
|
|
129
|
+
"""
|
|
130
|
+
Auto-dispatch based on the type / value of input_path.
|
|
131
|
+
|
|
132
|
+
Parameters
|
|
133
|
+
----------
|
|
134
|
+
input_path : str, tuple, or pd.DataFrame
|
|
135
|
+
- pd.DataFrame → single table; objects identified by group_col
|
|
136
|
+
- tuple of two strings → paired per-filter glob patterns
|
|
137
|
+
e.g. ("lc/*_W149.txt", "lc/*_Z087.txt")
|
|
138
|
+
- str (no wildcards) → single table file (.parquet, .fits, .csv, .txt …)
|
|
139
|
+
- str (with wildcards) → one lightcurve per matched file
|
|
140
|
+
config : dict
|
|
141
|
+
Pipeline configuration. See example_run.ipynb for all keys.
|
|
142
|
+
debug : bool
|
|
143
|
+
If True, print per-object veto breakdown while running.
|
|
144
|
+
|
|
145
|
+
Returns
|
|
146
|
+
-------
|
|
147
|
+
pd.DataFrame with OUTPUT_COLUMNS.
|
|
148
|
+
"""
|
|
149
|
+
if isinstance(input_path, pd.DataFrame):
|
|
150
|
+
return _run_single_table(input_path, config, debug=debug)
|
|
151
|
+
|
|
152
|
+
if isinstance(input_path, tuple):
|
|
153
|
+
if len(input_path) != 2:
|
|
154
|
+
raise ValueError("When input_path is a tuple it must have exactly two elements: "
|
|
155
|
+
"(primary_glob, secondary_glob).")
|
|
156
|
+
return _run_paired_files(input_path[0], input_path[1], config, debug=debug)
|
|
157
|
+
|
|
158
|
+
if not isinstance(input_path, str):
|
|
159
|
+
raise TypeError(f"input_path must be a str, tuple, or DataFrame; got {type(input_path).__name__}")
|
|
160
|
+
|
|
161
|
+
TABLE_EXTS = {".parquet", ".fits", ".fit", ".csv", ".tsv"}
|
|
162
|
+
ext = os.path.splitext(input_path)[1].lower()
|
|
163
|
+
has_wildcards = any(c in input_path for c in ("*", "?", "["))
|
|
164
|
+
|
|
165
|
+
if not has_wildcards and ext in TABLE_EXTS:
|
|
166
|
+
return _run_single_table(input_path, config, debug=debug)
|
|
167
|
+
|
|
168
|
+
if not has_wildcards:
|
|
169
|
+
return _run_single_table(input_path, config, debug=debug)
|
|
170
|
+
|
|
171
|
+
return _run_per_object_files(input_path, config, debug=debug)
|