griffingoodwin04 commited on
Commit
cc80bed
·
1 Parent(s): 1ae6b56

Refactor code structure for improved readability and maintainability

Browse files
data/build_dataset_config.yaml CHANGED
@@ -52,6 +52,7 @@ split:
52
  # across boundaries: train covers solar cycle 24's rise/max/decline, val
53
  # lands on the cycle-24 minimum/transition, test is cycle-25's rise --
54
  # genuinely unseen solar-cycle conditions, matching real forecasting deployment.
 
55
  train_range: ["2010-01-01", "2020-10-31"]
56
  val_range: ["2020-12-01", "2022-10-31"]
57
  test_range: ["2022-12-01", "2023-12-31"]
 
52
  # across boundaries: train covers solar cycle 24's rise/max/decline, val
53
  # lands on the cycle-24 minimum/transition, test is cycle-25's rise --
54
  # genuinely unseen solar-cycle conditions, matching real forecasting deployment.
55
+ # NOTE: these ranges are placeholders and don't match the released checkpoint.
56
  train_range: ["2010-01-01", "2020-10-31"]
57
  val_range: ["2020-12-01", "2022-10-31"]
58
  test_range: ["2022-12-01", "2023-12-31"]
docs/_templates/sidebar/brand.html CHANGED
@@ -2,5 +2,5 @@
2
 
3
  {% block brand_content %}
4
  <span class="foxes-brand-name">FOXES <span class="foxes-version">{{ release }}</span></span>
5
- <span class="foxes-brand-description">Python documentation</span>
6
  {% endblock brand_content %}
 
2
 
3
  {% block brand_content %}
4
  <span class="foxes-brand-name">FOXES <span class="foxes-version">{{ release }}</span></span>
5
+ <span class="foxes-brand-description">The Python Documentation</span>
6
  {% endblock brand_content %}
docs/api_reference.md CHANGED
@@ -1,139 +1,131 @@
1
- # API reference
2
 
3
- Use [Getting started](python_api.md) for examples. The reference below reads
4
  signatures, defaults, and docstrings directly from the code. Each definition
5
  links to its source.
6
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  ```{eval-rst}
8
  .. currentmodule:: helio_foxes
9
 
10
  .. autosummary::
11
  :nosignatures:
12
 
 
13
  Observation
14
- ObservationMetadata
15
- ObservationProcessor
 
 
16
  AIAProcessor
17
  HARPProcessor
18
  SXRProcessor
19
- Prediction
20
- Predictor
21
- load_model
22
- predict
23
- plot_flux_map
24
- plot_uncertainty_map
25
  parse_timestamp
26
- PredictionSeries
27
- load_observations
28
  ```
29
 
30
- ## Observation
31
-
32
- ```{eval-rst}
33
- .. autoclass:: helio_foxes.Observation
34
- :members:
35
- :member-order: bysource
36
- ```
37
 
38
- ## ObservationMetadata
39
 
40
  ```{eval-rst}
41
- .. autoclass:: helio_foxes.ObservationMetadata
42
  :members:
43
  :member-order: bysource
 
44
  ```
45
 
46
- ## ObservationProcessor
47
 
48
  ```{eval-rst}
49
- .. autoclass:: helio_foxes.ObservationProcessor
50
  :members:
51
  :member-order: bysource
52
- :class-doc-from: both
53
  ```
54
 
55
- ## AIAProcessor
56
 
57
  ```{eval-rst}
58
- .. autoclass:: helio_foxes.AIAProcessor
59
  :members:
60
  :member-order: bysource
61
  ```
62
 
63
- ## HARPProcessor
64
 
65
  ```{eval-rst}
66
- .. autoclass:: helio_foxes.HARPProcessor
67
- :members:
68
- :member-order: bysource
69
- :class-doc-from: both
70
  ```
71
 
72
- ## SXRProcessor
 
 
73
 
74
  ```{eval-rst}
75
- .. autoclass:: helio_foxes.SXRProcessor
76
  :members:
77
  :member-order: bysource
78
- :class-doc-from: both
79
  ```
80
 
81
- ## Prediction
 
 
82
 
83
  ```{eval-rst}
84
  .. autoclass:: helio_foxes.Prediction
85
  :members:
86
  :member-order: bysource
 
87
  ```
88
 
89
- ## Predictor
90
 
91
  ```{eval-rst}
92
- .. autoclass:: helio_foxes.Predictor
93
  :members:
94
  :member-order: bysource
95
  ```
96
 
97
- ## load_model
98
-
99
- ```{eval-rst}
100
- .. autofunction:: helio_foxes.load_model
101
- ```
102
-
103
- ## predict
104
-
105
- ```{eval-rst}
106
- .. autofunction:: helio_foxes.predict
107
- ```
108
-
109
- ## plot_flux_map
110
-
111
- ```{eval-rst}
112
- .. autofunction:: helio_foxes.plot_flux_map
113
- ```
114
 
115
- ## plot_uncertainty_map
116
 
117
  ```{eval-rst}
118
- .. autofunction:: helio_foxes.plot_uncertainty_map
 
 
119
  ```
120
 
121
- ## parse_timestamp
122
 
123
  ```{eval-rst}
124
- .. autofunction:: helio_foxes.parse_timestamp
 
 
 
125
  ```
126
 
127
- ## PredictionSeries
128
 
129
  ```{eval-rst}
130
- .. autoclass:: helio_foxes.PredictionSeries
131
  :members:
132
  :member-order: bysource
 
133
  ```
134
 
135
- ## load_observations
136
 
137
  ```{eval-rst}
138
- .. autofunction:: helio_foxes.load_observations
139
  ```
 
1
+ # API Reference
2
 
3
+ Use [Getting Started](python_api.md) for examples. The reference below reads
4
  signatures, defaults, and docstrings directly from the code. Each definition
5
  links to its source.
6
 
7
+ The API is a short pipeline, and this page follows it in order:
8
+
9
+ | Step | Use | You get |
10
+ | --- | --- | --- |
11
+ | 1. Get data | {py:class}`~helio_foxes.ObservationFetcher`, {py:func}`~helio_foxes.load_observations`, or {py:meth}`Observation.from_array <helio_foxes.Observation.from_array>` | {py:class}`~helio_foxes.Observation` |
12
+ | 2. Load a model | {py:class}`FOXESModel(checkpoint) <helio_foxes.FOXESModel>` | {py:class}`~helio_foxes.FOXESModel` |
13
+ | 3. Predict | {py:meth}`FOXESModel.predict <helio_foxes.FOXESModel.predict>` / {py:meth}`~helio_foxes.FOXESModel.predict_time_series` | {py:class}`~helio_foxes.Prediction` / {py:class}`~helio_foxes.PredictionTimeSeries` |
14
+ | 4. Look at the results | attributes and `plot_*` methods on the result | numbers and figures |
15
+
16
+ The AIA, HARP, and SXR processors at the end are the building blocks the
17
+ fetcher uses; most people won't need them directly.
18
+
19
  ```{eval-rst}
20
  .. currentmodule:: helio_foxes
21
 
22
  .. autosummary::
23
  :nosignatures:
24
 
25
+ ObservationFetcher
26
  Observation
27
+ load_observations
28
+ FOXESModel
29
+ Prediction
30
+ PredictionTimeSeries
31
  AIAProcessor
32
  HARPProcessor
33
  SXRProcessor
 
 
 
 
 
 
34
  parse_timestamp
 
 
35
  ```
36
 
37
+ ## 1. Get Data
 
 
 
 
 
 
38
 
39
+ ### ObservationFetcher
40
 
41
  ```{eval-rst}
42
+ .. autoclass:: helio_foxes.ObservationFetcher
43
  :members:
44
  :member-order: bysource
45
+ :class-doc-from: both
46
  ```
47
 
48
+ ### Observation
49
 
50
  ```{eval-rst}
51
+ .. autoclass:: helio_foxes.Observation
52
  :members:
53
  :member-order: bysource
 
54
  ```
55
 
56
+ #### ObservationMetadata
57
 
58
  ```{eval-rst}
59
+ .. autoclass:: helio_foxes.api.ObservationMetadata
60
  :members:
61
  :member-order: bysource
62
  ```
63
 
64
+ ### load_observations
65
 
66
  ```{eval-rst}
67
+ .. autofunction:: helio_foxes.load_observations
 
 
 
68
  ```
69
 
70
+ ## 2. Load a Model and Predict
71
+
72
+ ### FOXESModel
73
 
74
  ```{eval-rst}
75
+ .. autoclass:: helio_foxes.FOXESModel
76
  :members:
77
  :member-order: bysource
 
78
  ```
79
 
80
+ ## 3. Results and Plotting
81
+
82
+ ### Prediction
83
 
84
  ```{eval-rst}
85
  .. autoclass:: helio_foxes.Prediction
86
  :members:
87
  :member-order: bysource
88
+ :exclude-members: observed_flux
89
  ```
90
 
91
+ ### PredictionTimeSeries
92
 
93
  ```{eval-rst}
94
+ .. autoclass:: helio_foxes.PredictionTimeSeries
95
  :members:
96
  :member-order: bysource
97
  ```
98
 
99
+ ## Lower-Level Building Blocks
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ ### AIAProcessor
102
 
103
  ```{eval-rst}
104
+ .. autoclass:: helio_foxes.AIAProcessor
105
+ :members:
106
+ :member-order: bysource
107
  ```
108
 
109
+ ### HARPProcessor
110
 
111
  ```{eval-rst}
112
+ .. autoclass:: helio_foxes.HARPProcessor
113
+ :members:
114
+ :member-order: bysource
115
+ :class-doc-from: both
116
  ```
117
 
118
+ ### SXRProcessor
119
 
120
  ```{eval-rst}
121
+ .. autoclass:: helio_foxes.SXRProcessor
122
  :members:
123
  :member-order: bysource
124
+ :class-doc-from: both
125
  ```
126
 
127
+ ### parse_timestamp
128
 
129
  ```{eval-rst}
130
+ .. autofunction:: helio_foxes.parse_timestamp
131
  ```
docs/citation.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Citing FOXES
2
+
3
+ The method and results are described in our paper:
4
+
5
+ > Goodwin, G. T., March, A. J., Biradar, J., Schirninger, C., Jarolim, R.,
6
+ > Vourlidas, A., Sadykov, V. M., & Pratt, L. (2026). Improving Solar Flare Soft
7
+ > X-Ray Classification with FOXES: A Framework for Operational X-Ray Emission
8
+ > Synthesis. *The Astrophysical Journal*, 1003(1), 48.
9
+ > [doi:10.3847/1538-4357/ae5e4a](https://doi.org/10.3847/1538-4357/ae5e4a)
10
+
11
+ If FOXES helps your work, please cite the paper:
12
+
13
+ ```bibtex
14
+ @article{Goodwin_2026,
15
+ title = {Improving Solar Flare Soft X-Ray Classification with FOXES:
16
+ A Framework for Operational X-Ray Emission Synthesis},
17
+ author = {Goodwin, Griffin T. and March, Alison J. and Biradar, Jayant and
18
+ Schirninger, Christoph and Jarolim, Robert and Vourlidas, Angelos and
19
+ Sadykov, Viacheslav M. and Pratt, Lorien},
20
+ journal = {The Astrophysical Journal},
21
+ volume = {1003},
22
+ number = {1},
23
+ pages = {48},
24
+ year = {2026},
25
+ publisher = {American Astronomical Society},
26
+ doi = {10.3847/1538-4357/ae5e4a}
27
+ }
28
+ ```
29
+
30
+ If you use the code or data directly, you can cite the software as well:
31
+
32
+ ```bibtex
33
+ @software{FOXES,
34
+ title = {{FOXES: A Framework For Operational X-ray Emission Synthesis}},
35
+ institution = {Frontier Development Lab (FDL)},
36
+ repository-code = {https://github.com/griffin-goodwin/FOXES},
37
+ version = {v1.0},
38
+ year = {2026}
39
+ }
40
+ ```
41
+
42
+ ## Team
43
+
44
+ Griffin Goodwin, Alison March, Jayant Biradar, Christoph Schirninger,
45
+ Robert Jarolim, Angelos Vourlidas, Viacheslav Sadykov, and Lorien Pratt.
46
+
47
+ ## Acknowledgements
48
+
49
+ This work is a research product of [Heliolab](https://heliolab.ai), an
50
+ initiative of the [Frontier Development Lab](https://fdl.ai). FDL is a
51
+ public–private partnership between NASA, [Trillium Technologies](https://trillium.tech),
52
+ and commercial AI partners including Google Cloud and NVIDIA. Heliolab was
53
+ designed, delivered, and managed by Trillium Technologies Inc., a research and
54
+ development company focused on intelligent systems and collaborative
55
+ communities for heliophysics, planetary stewardship, and space exploration.
56
+ We gratefully acknowledge Google Cloud for extensive computational resources
57
+ and NVIDIA Corporation.
58
+
59
+ This material is based upon work supported by NASA under award number
60
+ No. 80GSFC23CA040. Any opinions, findings, conclusions or recommendations
61
+ expressed are those of the authors and do not necessarily reflect the views of
62
+ the National Aeronautics and Space Administration.
docs/conf.py CHANGED
@@ -14,8 +14,8 @@ with (ROOT / "pyproject.toml").open("rb") as project_file:
14
  metadata = tomllib.load(project_file)["project"]
15
 
16
  project = "FOXES"
17
- author = "FOXES contributors"
18
- copyright = "2026, FOXES contributors"
19
  release = metadata["version"]
20
  version = release
21
 
 
14
  metadata = tomllib.load(project_file)["project"]
15
 
16
  project = "FOXES"
17
+ author = "Griffin Goodwin"
18
+ copyright = "2026"
19
  release = metadata["version"]
20
  version = release
21
 
docs/images/notebook-aia-inputs.png DELETED

Git LFS Details

  • SHA256: f64a42fb164d68a68355c28d76c473dbba7c55152ba5ef1c1063fcb80ff581d5
  • Pointer size: 131 Bytes
  • Size of remote file: 758 kB
docs/images/notebook-flux-map.png DELETED

Git LFS Details

  • SHA256: 2a5dbb3592bf57469357489c910c3537ad7a2f4afc4612c6ed643c2996deb771
  • Pointer size: 130 Bytes
  • Size of remote file: 60.1 kB
docs/images/notebook-light-curves.png DELETED

Git LFS Details

  • SHA256: 292b78e2c85de32fa2e4b412036d8f5bc946797efeaf1f9cf84f3cf8915bd757
  • Pointer size: 131 Bytes
  • Size of remote file: 603 kB
docs/index.md CHANGED
@@ -9,12 +9,18 @@
9
  Framework For Operational X-ray Emission Synthesis
10
  ```
11
 
12
- FOXES uses seven-channel SDO/AIA images to predict full-disk solar soft X-ray
13
- flux and each image patch's contribution to that total.
 
 
14
 
15
- Start with [Getting started](python_api.md) to install the package and make
16
- one prediction. [Models and checkpoints](models.md) lists the available weights,
17
- and [Results](results.md) shows the saved evaluation.
 
 
 
 
18
 
19
  ```{toctree}
20
  :maxdepth: 1
@@ -25,8 +31,12 @@ models
25
  results
26
  workflows
27
  api_reference
 
28
  ```
29
 
30
- [Source repository](https://github.com/griffin-goodwin/FOXES) ·
 
31
  [PyPI](https://pypi.org/project/helio-foxes/) ·
32
- [Notebook walkthrough](https://github.com/griffin-goodwin/FOXES/blob/main/tutorials/heliofoxes_demo/heliofoxes.ipynb)
 
 
 
9
  Framework For Operational X-ray Emission Synthesis
10
  ```
11
 
12
+ FOXES estimates the Sun's full-disk soft X-ray flux (analogous to GOES) based on a provided seven channel stack of SDO/AIA
13
+ images. It also provides an estimate of the flux coming from individual regions through the resulting flux maps.
14
+ The original method and its evaluation are described in
15
+ [Goodwin et al. (2026), *ApJ* 1003, 48](https://doi.org/10.3847/1538-4357/ae5e4a).
16
 
17
+ If you're new here, [Getting Started](python_api.md) walks you through
18
+ installing the package and making your first prediction. After that,
19
+ [Models and Checkpoints](models.md) covers the available weights and
20
+ [Results](results.md) shows how the current model performs on the held-out
21
+ test set.
22
+ If you want to retrain the model or run batch jobs from a clone of the repo,
23
+ see [Command-Line Workflows](workflows.md).
24
 
25
  ```{toctree}
26
  :maxdepth: 1
 
31
  results
32
  workflows
33
  api_reference
34
+ citation
35
  ```
36
 
37
+ [Paper](https://doi.org/10.3847/1538-4357/ae5e4a) ·
38
+ [Source Repository](https://github.com/griffin-goodwin/FOXES) ·
39
  [PyPI](https://pypi.org/project/helio-foxes/) ·
40
+ [Notebook Walkthrough](https://github.com/griffin-goodwin/FOXES/blob/main/tutorials/heliofoxes_demo/heliofoxes.ipynb) ·
41
+ [Live Demo](https://huggingface.co/spaces/griffingoodwin04/FOXES-model) ·
42
+ [Dataset](https://huggingface.co/datasets/griffingoodwin04/FOXES-Data)
docs/models.md CHANGED
@@ -1,62 +1,45 @@
1
- # Models and checkpoints
2
 
3
- FOXES predicts a flux contribution for each image patch. These contributions
4
- sum to the full-disk soft X-ray flux. HARP regions summarize contributions
5
- inside active-region boxes; overlapping boxes can count the same patches.
6
 
7
- ## Download a checkpoint
 
 
 
 
8
 
9
- Save weights under `model_assets/`, using the paths below. They are separate
10
- from the Python package; after cloning this repository, `git lfs pull` retrieves
11
- the checkpoint files.
 
 
 
12
 
13
- | Checkpoint path | Model | Download |
14
- | --- | --- | --- |
15
- | `model_assets/UncertaintyModel.ckpt` | Current local + global model, with Gaussian uncertainty | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/UncertaintyModel.ckpt) |
16
- | `model_assets/LegacyModels/inverted-attention-mask.ckpt` | Legacy deterministic, distant-patch attention | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/LegacyModels/inverted-attention-mask.ckpt) |
17
- | `model_assets/LegacyModels/localized-attention-mask.ckpt` | Legacy deterministic, local attention | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/LegacyModels/localized-attention-mask.ckpt) |
18
- | `model_assets/LegacyModels/no-attention-mask.ckpt` | Legacy deterministic, full attention | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/LegacyModels/no-attention-mask.ckpt) |
19
 
20
- ## Current uncertainty model
21
 
22
- `UncertaintyModel.ckpt` combines local patch features with shared global
23
- context. A seven-channel `(7, 512, 512)` AIA input produces a 64 × 64 flux map,
24
- full-disk flux, and Gaussian prediction intervals.
25
 
26
- Load it with the default `legacy_model=False`. Its SXR normalization is embedded
27
- in the checkpoint; no separate SXR normalization file is needed.
28
 
29
- Patch variances add to the full-disk variance. The patch uncertainty map
30
- attributes that variance across the image; there are no local SXR labels to
31
- validate regional error bars. See [Results](results.md) for full-disk metrics,
32
- figures, and measured interval coverage.
33
-
34
- ## Legacy models
35
-
36
- The three deterministic checkpoints use the older SXR targets and do not
37
- produce uncertainty estimates. Enable their approximate output correction
38
- when loading them:
39
 
40
  ```python
41
  import helio_foxes
42
 
43
- model = helio_foxes.load_model(
44
- "model_assets/LegacyModels/inverted-attention-mask.ckpt",
45
- legacy_model=True,
46
- )
47
  ```
48
 
49
- Predictions strictly before **2016-11-19 00:00 UTC** receive a **0.7** flux
50
- factor; later predictions use 1.0. The same factor applies to full-disk and
51
- patch flux, preserving their sum. Timestamps are required; an `Observation`
52
- supplies its time automatically.
53
-
54
- This date rule approximates the older mixed-satellite targets and does not
55
- establish predictive calibration. Keep each checkpoint's original weights
56
- and embedded normalization. The original normalization artifact is
57
- `model_assets/LegacyModels/normalized_sxr_FOXES_paper.npy`.
58
-
59
- ## Team
60
 
61
- Griffin Goodwin, Alison March, Jayant Biradar, Christopher Schirninger,
62
- Robert Jarolim, Angelos Vourlidas, Viacheslav Sadykov, and Lorien Pratt.
 
 
 
 
1
+ # Models and Checkpoints
2
 
3
+ ## Download a Checkpoint
 
 
4
 
5
+ Checkpoints are distributed separately from the Python package. Pass a name
6
+ from the first column to `FOXESModel` and it's downloaded the first time and
7
+ cached in `~/.cache/helio_foxes` (or `HELIO_FOXES_CACHE`). You can also
8
+ download a file yourself, or run `git lfs pull` from a clone of the repository,
9
+ and pass its path instead.
10
 
11
+ | Name | Repository path | Model | Download |
12
+ | --- | --- | --- | --- |
13
+ | `"uncertainty"` (default) | `model_assets/UncertaintyModel.ckpt` | Current model: local + global attention, with Gaussian uncertainty | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/UncertaintyModel.ckpt) |
14
+ | `"inverted-attention-mask"` | `model_assets/LegacyModels/inverted-attention-mask.ckpt` | Legacy deterministic, distant-patch attention *(paper model)* | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/LegacyModels/inverted-attention-mask.ckpt) |
15
+ | `"localized-attention-mask"` | `model_assets/LegacyModels/localized-attention-mask.ckpt` | Legacy deterministic, local attention | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/LegacyModels/localized-attention-mask.ckpt) |
16
+ | `"no-attention-mask"` | `model_assets/LegacyModels/no-attention-mask.ckpt` | Legacy deterministic, full attention | [Weights](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/LegacyModels/no-attention-mask.ckpt) |
17
 
18
+ ## Current Uncertainty Model
 
 
 
 
 
19
 
20
+ `UncertaintyModel.ckpt` consists of a local transformer backbone (3 x 3 attention) + a global attention transformer with an uncertainty MLP head.
21
 
22
+ No legacy correction is applied to it. The SXR normalization is stored
23
+ inside the checkpoint, so you don't need a separate normalization file.
 
24
 
25
+ ## Legacy Models
 
26
 
27
+ The three deterministic checkpoints were trained on an older version of the
28
+ SXR targets and don't produce uncertainty estimates. Loading one by name turns
29
+ on the legacy correction automatically:
 
 
 
 
 
 
 
30
 
31
  ```python
32
  import helio_foxes
33
 
34
+ model = helio_foxes.FOXESModel("inverted-attention-mask")
 
 
 
35
  ```
36
 
37
+ If you load a legacy checkpoint from a file path instead, pass
38
+ `legacy_model=True` yourself, since FOXES can't tell from the path. Pass
39
+ `legacy_model=False` to see the uncorrected output.
 
 
 
 
 
 
 
 
40
 
41
+ With the correction on, any prediction before **2016-11-19 00:00 UTC** is
42
+ multiplied by **0.7** (to remove a SWPC scaling bias), and anything after is left alone. The factor applies to
43
+ both the full-disk flux and the patch map, so they still add up. Each
44
+ prediction needs a timestamp for this to work; an `Observation` already
45
+ carries one.
docs/python_api.md CHANGED
@@ -1,104 +1,155 @@
1
- # Getting started
2
 
3
- Make one prediction, plot its flux map, then try a time range.
4
- For every parameter and default, see the [API reference](api_reference.md).
5
 
6
- ## Install and get a checkpoint
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  ```bash
9
  python -m pip install helio-foxes
10
  ```
11
 
12
- Download [UncertaintyModel.ckpt](https://media.githubusercontent.com/media/griffin-goodwin/FOXES/main/model_assets/UncertaintyModel.ckpt)
13
- and save it as `model_assets/UncertaintyModel.ckpt` in your working directory.
14
- Checkpoints are separate from the Python package. For a repository clone,
15
- `git lfs pull` downloads the weights. Other weights are listed under
16
- [Models and checkpoints](models.md).
17
 
18
- ## Predict one observation
 
 
 
 
 
 
 
 
19
 
20
- Use your registered JSOC email to download AIA data. Load the model once and
21
- reuse it for later observations.
 
 
 
22
 
23
  ```python
24
  import matplotlib.pyplot as plt
25
  import helio_foxes
26
 
27
- model = helio_foxes.load_model("model_assets/UncertaintyModel.ckpt")
28
- processor = helio_foxes.ObservationProcessor(email="you@example.com")
29
- observation = processor.fetch_observation("2023-08-01T00:00:00Z")
30
  result = model.predict(observation)
31
 
32
  print(f"Predicted SXR flux: {result.flux:.3e} W/m²")
 
33
  print("68% interval:", result.intervals["68"])
34
- helio_foxes.plot_flux_map(result, show_harp_boxes=True)
35
  plt.show()
36
  ```
37
 
38
- `result.flux_map` contains patch contributions that sum to `result.flux`.
39
- HARP boxes identify active regions; their flux sums are in `result.harp_regions`.
40
- When measured GOES data is available, compare `result.flux` with
41
- `result.sxr["xrsb_flux"]`. GOES measurements are not model inputs.
 
42
 
43
- The current checkpoint also returns Gaussian intervals and
44
- `result.patch_uncertainty_map`. Patch and HARP uncertainties attribute the
45
- model's global variance; they are not validated regional error bars.
46
- See [Results](results.md) for measured interval coverage.
47
 
48
- ## Predict a time range
49
 
50
- Continue with the same `model` and `processor`:
51
 
52
  ```python
53
- observations = processor.iter_observations(
54
  "2023-08-01 00:00", "2023-08-01 01:00",
55
  cadence="12min", save_dir="saved_observations", progress=True,
56
  )
57
- series = model.predict_series(observations)
58
- series.plot(include_full_disk=True, include_sxr=True)
59
  plt.show()
60
 
61
- series.to_dataframe().to_csv("predictions.csv")
62
  harp_curves = series.harp_light_curves()
63
  ```
64
 
65
- The iterator processes one observation at a time and reuses existing files in
66
- `save_dir`. Times without an explicit timezone are interpreted as UTC.
 
 
 
 
 
 
67
 
68
- ## Reuse saved observations
 
 
 
69
 
70
  ```python
71
  saved = helio_foxes.load_observations("saved_observations")
72
- series = model.predict_series(saved)
73
  ```
74
 
75
- This avoids downloading and preprocessing the same data again. Refresh the
76
- saved files if your preprocessing or source settings change.
77
-
78
- ## Predicting your own observations
79
 
80
- For an already processed AIA stack:
81
 
82
  ```python
83
- observation = helio_foxes.Observation.from_npy(
84
- "my_processed_stack.npy", timestamp="2023-08-01 12:00",
 
 
85
  )
86
  result = model.predict(observation)
87
  ```
88
 
89
- For the current checkpoint, use shape `(7, 512, 512)` and wavelength order
90
- `[94, 131, 171, 193, 211, 304, 335]` Å. Match the training preprocessing:
91
- `from_npy` does not resize, crop, or normalize the array. If a checkpoint needs
92
- an AIA normalization artifact, apply it once, either during preprocessing or
93
- with `load_model(..., aia_norm_path=...)`.
94
 
95
- For local raw FITS files, use
96
- {py:meth}`helio_foxes.AIAProcessor.process_files` before prediction.
97
- The [notebook walkthrough](https://github.com/griffin-goodwin/FOXES/blob/main/tutorials/heliofoxes_demo/heliofoxes.ipynb)
98
- contains more plotting and observation examples.
99
 
100
- ## Legacy checkpoint correction
101
 
102
- For older deterministic weights, use `legacy_model=True` when loading the
103
- model. See [Legacy models](models.md#legacy-models) for the correction rule.
104
- Leave the default `legacy_model=False` for `UncertaintyModel.ckpt`.
 
 
 
1
+ # Getting Started
2
 
3
+ This page takes gives you a nice overview on how to get started with the FOXES package. Every method and their default kwargs is listed in the
4
+ [API Reference](api_reference.md).
5
 
6
+ ## How the Pieces Fit
7
+
8
+ Every workflow follows the same four steps:
9
+
10
+ ```text
11
+ ObservationFetcher().fetch(time) ──► Observation
12
+ │
13
+ FOXESModel().predict(observation) ◄─────────┘
14
+ │
15
+ ▼
16
+ Prediction ──► .flux, .observed_flux, .flux_map, .harp_regions
17
+ .plot_flux_map(), .plot_uncertainty_map()
18
+ ```
19
+
20
+ 1. **Get data.** An {py:class}`~helio_foxes.Observation` is one processed AIA
21
+ stack plus any HARP and GOES data. Get it from
22
+ {py:class}`~helio_foxes.ObservationFetcher`, load saved ones with
23
+ {py:func}`~helio_foxes.load_observations`, or wrap your own array with
24
+ {py:meth}`Observation.from_array <helio_foxes.Observation.from_array>`.
25
+ 2. **Load a model.** Create a {py:class}`~helio_foxes.FOXESModel`. It
26
+ downloads the current checkpoint the first time. Load it once and reuse it.
27
+ 3. **Predict.** {py:meth}`FOXESModel.predict <helio_foxes.FOXESModel.predict>`
28
+ turns an `Observation` into a {py:class}`~helio_foxes.Prediction`. For a
29
+ time range, {py:meth}`~helio_foxes.FOXESModel.predict_time_series` turns
30
+ many observations into a {py:class}`~helio_foxes.PredictionTimeSeries`.
31
+ 4. **Look at the results.** Read the numbers from the `Prediction` and call
32
+ `plot_flux_map` or `plot_uncertainty_map`. For a `PredictionTimeSeries`,
33
+ get the light curves as DataFrames and call `plot_light_curves`.
34
+
35
+ ## Install
36
+
37
+ FOXES needs Python 3.10 or newer.
38
 
39
  ```bash
40
  python -m pip install helio-foxes
41
  ```
42
 
43
+ The model weights aren't bundled with the package. `FOXESModel()` downloads
44
+ the current checkpoint the first time you use it and caches it in
45
+ `~/.cache/helio_foxes` (set `HELIO_FOXES_CACHE` to use another folder). The
46
+ older checkpoints are listed under [Models and Checkpoints](models.md).
 
47
 
48
+ You'll also need an email address registered with JSOC to download AIA data.
49
+ If you don't have one yet, you can
50
+ [register here](http://jsoc.stanford.edu/ajax/register_email.html); it only
51
+ takes a minute. Set it once in your environment so you don't have to pass it
52
+ every time:
53
+
54
+ ```bash
55
+ export JSOC_EMAIL="you@example.com"
56
+ ```
57
 
58
+ Or pass `email="you@example.com"` to `ObservationFetcher`.
59
+
60
+ ## Predict One Observation
61
+
62
+ Loading the model is probably the slowest part, so do it once and reuse it.
63
 
64
  ```python
65
  import matplotlib.pyplot as plt
66
  import helio_foxes
67
 
68
+ model = helio_foxes.FOXESModel()
69
+ fetcher = helio_foxes.ObservationFetcher()
70
+ observation = fetcher.fetch("2023-08-01T00:00:00Z")
71
  result = model.predict(observation)
72
 
73
  print(f"Predicted SXR flux: {result.flux:.3e} W/m²")
74
+ print(f"Observed GOES flux: {result.observed_flux:.3e} W/m²")
75
  print("68% interval:", result.intervals["68"])
76
+ result.plot_flux_map()
77
  plt.show()
78
  ```
79
 
80
+ `result.flux_map` holds the per-patch contribution to the soft x-ray flux... they add up to
81
+ `result.flux`. The boxes drawn on the map are HARP active regions; the flux
82
+ inside each HARP is saved in `result.harp_regions`. `result.observed_flux` is
83
+ the measured GOES XRS-B flux at the same time, for comparison (`None` if GOES
84
+ had no data).
85
 
86
+ The current checkpoint also gives you Gaussian uncertainty estimates per prediction, along with a
87
+ per-patch uncertainty map (`result.patch_uncertainty_map`), which you can
88
+ plot with `result.plot_uncertainty_map()`.
 
89
 
90
+ ## Predict a Time Range
91
 
92
+ Using the same `model` and `fetcher`:
93
 
94
  ```python
95
+ observations = fetcher.fetch_range(
96
  "2023-08-01 00:00", "2023-08-01 01:00",
97
  cadence="12min", save_dir="saved_observations", progress=True,
98
  )
99
+ series = model.predict_time_series(observations)
100
+ series.plot_light_curves(show_full_disk=True, show_observed=True)
101
  plt.show()
102
 
103
+ series.full_disk_light_curve().to_csv("predictions.csv")
104
  harp_curves = series.harp_light_curves()
105
  ```
106
 
107
+ Observations are downloaded and processed one at a time, so long ranges won't
108
+ fill up your memory. Anything already in `save_dir` is reused instead of
109
+ downloaded again.
110
+
111
+ `fetch_range` returns a generator, so it can only be looped over once. After
112
+ `predict_time_series` has used it, `observations` is empty. Call `fetch_range`
113
+ again (it reuses `save_dir`), or use `list(observations)` if you need them more
114
+ than once and they fit in memory.
115
 
116
+ ## Reuse Saved Observations
117
+
118
+ Once you've saved a range, you can run the model on it again without
119
+ downloading anything:
120
 
121
  ```python
122
  saved = helio_foxes.load_observations("saved_observations")
123
+ series = model.predict_time_series(saved)
124
  ```
125
 
126
+ ## Use Your Own Data
 
 
 
127
 
128
+ If you already have a processed AIA stack:
129
 
130
  ```python
131
+ import numpy as np
132
+
133
+ observation = helio_foxes.Observation.from_array(
134
+ np.load("my_processed_stack.npy"), timestamp="2023-08-01 12:00",
135
  )
136
  result = model.predict(observation)
137
  ```
138
 
139
+ The current checkpoint expects an array of shape `(7, 512, 512)` with channels
140
+ in the order `[94, 131, 171, 193, 211, 304, 335]` Å. `from_array` uses the array
141
+ as is, with no resizing, cropping, or normalization, so it needs to match the
142
+ training preprocessing already.
 
143
 
144
+ For raw FITS files on disk, run them through
145
+ {py:meth}`helio_foxes.AIAProcessor.process_files` first. The
146
+ [notebook walkthrough](https://github.com/griffin-goodwin/FOXES/blob/main/tutorials/heliofoxes_demo/heliofoxes.ipynb)
147
+ has more plotting and data-loading examples.
148
 
149
+ ## Older Checkpoints
150
 
151
+ The older deterministic checkpoints need a correction for their outdated
152
+ training targets. Loading one by name, e.g.
153
+ `FOXESModel("inverted-attention-mask")`, turns it on for you; if you load one
154
+ from a file path, pass `legacy_model=True`. [Legacy Models](models.md#legacy-models)
155
+ explains what the correction does.
docs/results.md CHANGED
@@ -1,9 +1,8 @@
1
  # Results
2
 
3
- These saved results are for `model_assets/UncertaintyModel.ckpt`, evaluated on
4
- **100,058 timestamps** from **2023-08-01 00:00:00** through
5
- **2025-09-26 20:21:00 UTC**. They measure full-disk predictions at individual
6
- timestamps, rather than independent flare events.
7
 
8
  ## Metrics
9
 
@@ -15,23 +14,26 @@ timestamps, rather than independent flare events.
15
  | M | 22,386 | 0.1317 | 0.0932 | 0.7173 | 0.8734 | 62.01% | 89.08% |
16
  | X | 1,082 | 0.2181 | 0.1667 | −0.1556 | 0.5969 | 30.87% | 58.69% |
17
 
18
- Regression metrics use `log10(flux)`; errors are in dex. Coverage counts
19
- targets within 1 or 1.96 predicted standard deviations in the checkpoint's
20
- normalized `log10(flux + 1e-8)` space.
 
21
 
22
- Download the full summaries:
 
 
23
 
24
  - {download}`Regression metrics <../model_assets/UncertaintyModelResults/evaluation/metrics/performance_metrics.csv>`
25
  - {download}`Uncertainty metrics <../model_assets/UncertaintyModelResults/evaluation/metrics/uncertainty_metrics.csv>`
26
 
27
- ## Predicted versus measured flux
28
 
29
  ```{figure} ../model_assets/UncertaintyModelResults/evaluation/plots/regression_plot.png
30
  :alt: Density of predicted versus measured SXR flux, with a perfect-agreement line and class-specific MAE band.
31
  :width: 100%
32
 
33
- Full-disk flux in W/m². The red line marks perfect agreement; shading shows
34
- class-specific log-space MAE.
35
  ```
36
 
37
  ## Calibration
@@ -40,7 +42,9 @@ class-specific log-space MAE.
40
  :alt: Nominal versus empirical coverage by class and a histogram of standardized residuals.
41
  :width: 100%
42
 
43
- Nominal versus measured coverage (left) and standardized residuals (right).
 
44
  ```
45
 
46
- To evaluate your own predictions, follow the [command-line workflow](workflows.md#evaluate-predictions).
 
 
1
  # Results
2
 
3
+ These numbers come from `model_assets/UncertaintyModel.ckpt`, evaluated on the
4
+ held-out test set: **100,058 timestamps** between **2023-08-01 00:00** and
5
+ **2025-09-26 20:21 UTC**.
 
6
 
7
  ## Metrics
8
 
 
14
  | M | 22,386 | 0.1317 | 0.0932 | 0.7173 | 0.8734 | 62.01% | 89.08% |
15
  | X | 1,082 | 0.2181 | 0.1667 | −0.1556 | 0.5969 | 30.87% | 58.69% |
16
 
17
+ Errors are computed on `log10(flux)`, so they're in dex. Coverage is the
18
+ fraction of measured values that land within 1 (68%) or 1.96 (95%) predicted
19
+ standard deviations, measured in the checkpoint's normalized
20
+ `log10(flux + 1e-8)` space.
21
 
22
+ The model does well on B through M class, but X-class flux is its weak spot.Keep that in mind if you're using FOXES during large events.
23
+
24
+ Full summaries:
25
 
26
  - {download}`Regression metrics <../model_assets/UncertaintyModelResults/evaluation/metrics/performance_metrics.csv>`
27
  - {download}`Uncertainty metrics <../model_assets/UncertaintyModelResults/evaluation/metrics/uncertainty_metrics.csv>`
28
 
29
+ ## Predicted Versus Measured Flux
30
 
31
  ```{figure} ../model_assets/UncertaintyModelResults/evaluation/plots/regression_plot.png
32
  :alt: Density of predicted versus measured SXR flux, with a perfect-agreement line and class-specific MAE band.
33
  :width: 100%
34
 
35
+ Full-disk flux in W/m². The red line is perfect agreement, and the shading
36
+ shows the mean absolute error (in log space) for each flare class.
37
  ```
38
 
39
  ## Calibration
 
42
  :alt: Nominal versus empirical coverage by class and a histogram of standardized residuals.
43
  :width: 100%
44
 
45
+ Left: how often the measured flux actually falls inside each nominal interval.
46
+ Right: the distribution of standardized residuals.
47
  ```
48
 
49
+ To run the same evaluation on your own predictions, see the
50
+ [Evaluate Predictions](workflows.md#evaluate-predictions) workflow.
docs/workflows.md CHANGED
@@ -1,10 +1,12 @@
1
- # Development and command-line workflows
2
 
3
- Use the [Python guide](python_api.md) for individual observations. The scripts
4
- below prepare datasets, run batch predictions, evaluate results, or train models.
5
- Run commands from the repository root and edit each YAML config before use.
 
 
6
 
7
- ## Set up a checkout
8
 
9
  ```bash
10
  git clone https://github.com/griffin-goodwin/FOXES.git
@@ -15,30 +17,34 @@ python -m pip install -e ".[dev,evaluation,training]"
15
  git lfs pull
16
  ```
17
 
18
- For raw-data processing, also install `requirements.txt`. In notebooks, select
19
- this environment's kernel and restart it after changing imported source.
20
- Run `python -m pytest -q` when checking code changes.
 
21
 
22
- Paths inside a YAML config are relative to that file, rather than your terminal
23
- or notebook's working directory. The bundled configs set `path_root: ..` so
24
- `./foxes_data/` and `./foxes_outputs/` refer to folders in the repository root.
25
- You can set `path_root` to your data drive instead, or use absolute paths;
26
- `~` and environment variables such as `${FOXES_DATA}` also work. When launching
27
- from elsewhere, pass the script and `--config` locations explicitly.
28
- The example data folders must exist or be replaced with your actual dataset paths.
 
29
 
30
- ## Get data
31
 
32
- Download the released dataset into paired AIA/SXR `.npy` files:
33
 
34
  ```bash
35
  python download/hugging_face_data_download.py --config download/hf_download_config.yaml
36
  ```
37
 
38
- Set the output directories and desired splits in `download/hf_download_config.yaml`.
39
- If you already have local Parquet files, set `local_parquet_dir` in that config.
 
40
 
41
- For raw AIA and GOES data instead, edit the corresponding configs, then run:
 
42
 
43
  ```bash
44
  python download/download_sdo.py --config download/sdo_download_config.yaml
@@ -46,47 +52,51 @@ python download/download_sxr.py --config download/sxr_download_config.yaml
46
  python data/build_dataset.py --config data/build_dataset_config.yaml
47
  ```
48
 
49
- AIA downloads require a registered JSOC email. The build script cleans and
50
- converts AIA, then combines and aligns GOES measurements with the images.
 
51
 
52
- ## Run inference
53
 
54
- Edit `forecasting/inference_config.yaml` to set `data.aia_dir`, `data.sxr_dir`,
55
- `data.checkpoint_path`, and `output_path`. AIA files are processed
56
- `(7, 512, 512)` arrays; matching SXR files contain scalar flux values and use
57
- the same timestamp filenames. Set `prediction_only: "true"` when SXR targets
58
- are unavailable.
59
 
60
- The default checkpoint is `model_assets/UncertaintyModel.ckpt` with
61
- `legacy_model: false`. Leave `data.sxr_norm_path: null` to use its embedded
62
- normalization. See [Models and checkpoints](models.md) for other weights.
 
63
 
64
  ```bash
65
  python forecasting/inference.py --config forecasting/inference_config.yaml
66
  ```
67
 
68
- The script writes a prediction CSV. Flux maps and patch uncertainty outputs
69
- are controlled by the output paths and `model_params` settings in the config.
70
- Inference uses one device selected by `device`; CUDA uses the first visible GPU.
 
71
 
72
- ## Evaluate predictions
73
 
74
- Set the prediction CSV and output directory in
75
- `forecasting/evaluation_config.yaml`, then run:
76
 
77
  ```bash
78
  python forecasting/evaluation.py --config forecasting/evaluation_config.yaml
79
  ```
80
 
81
- Evaluation writes regression metrics and figures, plus interval coverage and
82
- calibration plots when Gaussian uncertainty is present. See the bundled
83
- [Results](results.md) for an example.
84
 
85
- ## Train a model
86
 
87
- Training expects paired AIA/SXR files in `train/`, `val/`, and `test/` folders.
88
- For raw-data builds, enable `steps.split` and `sxr_normalization.compute` in
89
- `data/build_dataset_config.yaml` to prepare these inputs.
 
90
 
91
  Edit the data paths, model, and training settings, then run:
92
 
@@ -94,5 +104,6 @@ Edit the data paths, model, and training settings, then run:
94
  python training/train.py --config training/train_coupled_gaussian.yaml
95
  ```
96
 
97
- Use `training/train_deterministic.yaml` for a deterministic model. The Gaussian
98
- config matches the current checkpoint's architecture and losses.
 
 
1
+ # Command-Line Workflows
2
 
3
+ For single observations or short time ranges, the [Python Guide](python_api.md)
4
+ is the easier route. The scripts on this page are for heavier jobs: building
5
+ datasets, running batch predictions, evaluating results, and training. Each
6
+ script reads a YAML config, so open and edit the config before running
7
+ anything. Run all commands from the repository root.
8
 
9
+ ## Set Up a Checkout
10
 
11
  ```bash
12
  git clone https://github.com/griffin-goodwin/FOXES.git
 
17
  git lfs pull
18
  ```
19
 
20
+ If you plan to process raw data, install `requirements.txt` as well. When
21
+ working in a notebook, pick this environment's kernel, and restart the kernel
22
+ after editing any source it imports. Run `python -m pytest -q` to check your
23
+ changes.
24
 
25
+ Paths in a YAML config are resolved relative to the config file itself, not
26
+ to wherever your terminal or notebook happens to be. The bundled configs set
27
+ `path_root: ..`, which makes `./foxes_data/` and `./foxes_outputs/` point to
28
+ folders in the repository root. If your data lives somewhere else, point
29
+ `path_root` at it or use absolute paths; `~` and environment variables like
30
+ `${FOXES_DATA}` work too. If you launch a script from a different directory,
31
+ give the full paths to both the script and its `--config`. The data folders in
32
+ the example configs need to exist, so create them or swap in your own paths.
33
 
34
+ ## Get Data
35
 
36
+ To download the released dataset as paired AIA/SXR `.npy` files:
37
 
38
  ```bash
39
  python download/hugging_face_data_download.py --config download/hf_download_config.yaml
40
  ```
41
 
42
+ Set the output directories and the splits you want in
43
+ `download/hf_download_config.yaml`. If you already have the Parquet files
44
+ locally, set `local_parquet_dir` in that config to skip the download.
45
 
46
+ To build the dataset from raw AIA and GOES data instead, edit the matching
47
+ configs and run:
48
 
49
  ```bash
50
  python download/download_sdo.py --config download/sdo_download_config.yaml
 
52
  python data/build_dataset.py --config data/build_dataset_config.yaml
53
  ```
54
 
55
+ AIA downloads need a [registered JSOC email](http://jsoc.stanford.edu/ajax/register_email.html).
56
+ The build script cleans and processes the AIA images, then lines the GOES
57
+ measurements up with them.
58
 
59
+ ## Run Inference
60
 
61
+ In `forecasting/inference_config.yaml`, set `data.aia_dir`, `data.sxr_dir`,
62
+ `data.checkpoint_path`, and `output_path`. The AIA files should be processed
63
+ `(7, 512, 512) -> (C, H, W)` arrays, and each matching SXR file holds a single flux value
64
+ under the same timestamp filename. If you don't have SXR targets, set
65
+ `prediction_only: "true"`.
66
 
67
+ By default the config uses `model_assets/UncertaintyModel.ckpt` with
68
+ `legacy_model: false`. Leave `data.sxr_norm_path: null` so it uses the
69
+ normalization stored in the checkpoint. Other weights are listed under
70
+ [Models and Checkpoints](models.md).
71
 
72
  ```bash
73
  python forecasting/inference.py --config forecasting/inference_config.yaml
74
  ```
75
 
76
+ The script writes a CSV of predictions. Whether it also saves flux maps and
77
+ patch uncertainty maps depends on the output paths and `model_params` in the
78
+ config. Inference runs on the single device set by `device`; with CUDA, that's
79
+ the first visible GPU.
80
 
81
+ ## Evaluate Predictions
82
 
83
+ Point `forecasting/evaluation_config.yaml` at your prediction CSV and an
84
+ output directory, then run:
85
 
86
  ```bash
87
  python forecasting/evaluation.py --config forecasting/evaluation_config.yaml
88
  ```
89
 
90
+ You'll get regression metrics and figures, plus interval coverage and
91
+ calibration plots if the predictions include Gaussian uncertainty. The
92
+ [Results](results.md) page is an example of the output.
93
 
94
+ ## Train a Model
95
 
96
+ Training expects paired AIA/SXR files split into `train/`, `val/`, and `test/`
97
+ folders. If you're building from raw data, turn on `steps.split` and
98
+ `sxr_normalization.compute` in `data/build_dataset_config.yaml` to set those
99
+ up.
100
 
101
  Edit the data paths, model, and training settings, then run:
102
 
 
104
  python training/train.py --config training/train_coupled_gaussian.yaml
105
  ```
106
 
107
+ The Gaussian config matches the architecture and losses of the current
108
+ checkpoint. For a deterministic model, use `training/train_deterministic.yaml`
109
+ instead.
helio_foxes/__init__.py CHANGED
@@ -1,13 +1,23 @@
1
- """Small Python API for FOXES inference and visualization."""
 
 
 
 
2
 
3
  from .api import (
4
- Observation, ObservationMetadata, ObservationProcessor, AIAProcessor,
5
- HARPProcessor, SXRProcessor, Prediction, Predictor, load_model, predict,
6
- plot_flux_map, plot_uncertainty_map, parse_timestamp, PredictionSeries, load_observations,
 
 
 
 
 
7
  )
8
 
9
  __all__ = [
10
- "Observation", "ObservationMetadata", "ObservationProcessor", "AIAProcessor",
11
- "HARPProcessor", "SXRProcessor", "Prediction", "Predictor", "load_model", "predict",
12
- "plot_flux_map", "plot_uncertainty_map", "parse_timestamp", "PredictionSeries", "load_observations",
 
13
  ]
 
1
+ """Small Python API for FOXES inference and visualization.
2
+
3
+ Fetch an :class:`Observation`, predict on it with a :class:`FOXESModel`, and
4
+ read or plot the resulting :class:`Prediction`. See :mod:`helio_foxes.api`.
5
+ """
6
 
7
  from .api import (
8
+ # 1. Get data
9
+ ObservationFetcher, Observation, load_observations,
10
+ # 2. Load a model and predict
11
+ FOXESModel,
12
+ # 3. Results
13
+ Prediction, PredictionTimeSeries,
14
+ # Lower-level building blocks
15
+ AIAProcessor, HARPProcessor, SXRProcessor, parse_timestamp,
16
  )
17
 
18
  __all__ = [
19
+ "ObservationFetcher", "Observation", "load_observations",
20
+ "FOXESModel",
21
+ "Prediction", "PredictionTimeSeries",
22
+ "AIAProcessor", "HARPProcessor", "SXRProcessor", "parse_timestamp",
23
  ]
helio_foxes/api.py CHANGED
The diff for this file is too large to render. See raw diff
 
tests/test_harp_api.py CHANGED
@@ -70,7 +70,7 @@ def test_fetch_returns_raw_rows_from_selected_good_sweep(monkeypatch):
70
  "top_pct": 20.0, "left_pct": 30.0, "width_pct": 10.0, "height_pct": 5.0,
71
  })
72
 
73
- assert processor.fetch_date(datetime(2023, 8, 1)) == [
74
  {"T_REC": "2023.08.01_00:12:00_TAI", "QUALITY": 0,
75
  "HARPNUM": 2, "NOAA_ARS": "10002,10003",
76
  "top_pct": 20.0, "left_pct": 30.0,
@@ -94,7 +94,7 @@ def test_fetch_accepts_aia_timestamp_formats(monkeypatch, timestamp):
94
 
95
  monkeypatch.setattr(processor, "_query_sharp", query)
96
  monkeypatch.setattr(processor, "_bbox_to_pixel_fractions", lambda row: {"top_pct": 20.0})
97
- assert processor.fetch_date(timestamp)[0]["HARPNUM"] == 2
98
  assert seen == [(datetime(2023, 8, 1), "test@example.com")]
99
 
100
 
 
70
  "top_pct": 20.0, "left_pct": 30.0, "width_pct": 10.0, "height_pct": 5.0,
71
  })
72
 
73
+ assert processor.fetch(datetime(2023, 8, 1)) == [
74
  {"T_REC": "2023.08.01_00:12:00_TAI", "QUALITY": 0,
75
  "HARPNUM": 2, "NOAA_ARS": "10002,10003",
76
  "top_pct": 20.0, "left_pct": 30.0,
 
94
 
95
  monkeypatch.setattr(processor, "_query_sharp", query)
96
  monkeypatch.setattr(processor, "_bbox_to_pixel_fractions", lambda row: {"top_pct": 20.0})
97
+ assert processor.fetch(timestamp)[0]["HARPNUM"] == 2
98
  assert seen == [(datetime(2023, 8, 1), "test@example.com")]
99
 
100
 
tests/test_harp_uncertainty.py CHANGED
@@ -65,8 +65,9 @@ def test_prediction_rejects_invalid_uncertainty_maps(uncertainty, match):
65
  @pytest.mark.parametrize("with_uncertainty", [False, True])
66
  def test_uncertainty_label_toggle_does_not_change_results(show_uncertainty, with_uncertainty):
67
  result = prediction([box()], with_uncertainty=with_uncertainty)
68
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0,
69
- show_harp_uncertainty=show_uncertainty)
 
70
  text = "#1234\n1.00e-07"
71
  if show_uncertainty and with_uncertainty:
72
  text += "\n± 1.30e-08"
@@ -75,21 +76,12 @@ def test_uncertainty_label_toggle_does_not_change_results(show_uncertainty, with
75
  plt.close(ax.figure)
76
 
77
 
78
- @pytest.mark.parametrize("deferred", [False, True])
79
- def test_explicit_and_deferred_boxes_get_uncertainty_from_prediction_map(monkeypatch, deferred):
80
- metadata = helio_foxes.ObservationMetadata(timestamp="2023-08-01", image_shape=(7, 2, 2))
81
  result = prediction(None, metadata=metadata)
82
- calls = []
83
-
84
- def fetch(self, timestamp):
85
- calls.append(timestamp)
86
- return [box(top=50, height=50)]
87
-
88
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", fetch)
89
- kwargs = {} if deferred else {"harp_regions": [box(top=50, height=50)]}
90
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0, **kwargs)
91
  assert ax.texts[0].get_text() == "#1234\n3.00e-08\n± 5.00e-09"
92
- assert calls == ([metadata.timestamp] if deferred else [])
93
  assert result.harp_regions is None
94
  plt.close(ax.figure)
95
 
@@ -100,8 +92,9 @@ def test_manual_offsets_keep_uncertainty_labels_readable_after_resize():
100
  result = helio_foxes.Prediction(flux=4.096e-6, flux_map=np.full((64, 64), 1e-9),
101
  patch_uncertainty_map=np.full((64, 64), 2e-10), harp_regions=regions)
102
  offsets = {10000: (-100, 30), 10001: (0, -70), 10002: (100, 30)}
103
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0,
104
- harp_label_offsets=offsets, harp_label_fontsize=10)
 
105
  for size, dpi in [((7, 6), 100), ((5.5, 5.5), 150)]:
106
  ax.figure.set_size_inches(*size)
107
  ax.figure.set_dpi(dpi)
@@ -127,7 +120,7 @@ def test_colliding_labels_shift_without_overlap_or_font_shrinking(top, left, wit
127
  flux=4.096e-6, flux_map=np.full((64, 64), 1e-9), harp_regions=regions,
128
  patch_uncertainty_map=np.full((64, 64), 2e-10) if with_uncertainty else None,
129
  )
130
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0, harp_label_fontsize=10)
131
  ax.figure.canvas.draw()
132
  renderer = ax.figure.canvas.get_renderer()
133
  bounds = [label.get_bbox_patch().get_window_extent(renderer) for label in ax.texts]
@@ -146,7 +139,7 @@ def test_colliding_labels_shift_without_overlap_or_font_shrinking(top, left, wit
146
  def test_small_label_overlap_gets_a_small_nudge_instead_of_a_full_height_jump():
147
  result = prediction([box(10000, top=30, left=20, width=5, height=5),
148
  box(10001, top=30, left=20, width=5, height=5)])
149
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0, harp_label_max_shift=0)
150
  ax.figure.canvas.draw()
151
  renderer = ax.figure.canvas.get_renderer()
152
  height = ax.texts[0].get_bbox_patch().get_window_extent(renderer).height / renderer.points_to_pixels(1)
@@ -154,8 +147,9 @@ def test_small_label_overlap_gets_a_small_nudge_instead_of_a_full_height_jump():
154
 
155
  # Start the second label just one point inside the first label's bottom edge.
156
  start = (3, -3 - height + 1)
157
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0,
158
- harp_label_offsets={10001: start})
 
159
  ax.figure.canvas.draw()
160
  renderer = ax.figure.canvas.get_renderer()
161
  first, second = [label.get_bbox_patch().get_window_extent(renderer) for label in ax.texts]
@@ -170,8 +164,9 @@ def test_small_label_overlap_gets_a_small_nudge_instead_of_a_full_height_jump():
170
  def test_automatic_label_movement_stays_within_limit(max_shift):
171
  regions = [box(10000 + i, top=45, left=45, width=3, height=3) for i in range(6)]
172
  result = prediction(regions)
173
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0,
174
- harp_label_max_shift=max_shift)
 
175
  for label in ax.texts:
176
  corner_offset = (-3 if label.get_ha() == "right" else 3,
177
  3 if label.get_va() == "bottom" else -3)
@@ -183,13 +178,13 @@ def test_automatic_label_movement_stays_within_limit(max_shift):
183
  @pytest.mark.parametrize("max_shift", [-1, np.inf, np.nan])
184
  def test_invalid_label_shift_limit_is_rejected(max_shift):
185
  with pytest.raises(ValueError, match="harp_label_max_shift must be finite and nonnegative"):
186
- helio_foxes.plot_flux_map(np.ones((2, 2)), harp_label_max_shift=max_shift)
187
 
188
 
189
  @pytest.mark.parametrize("top,left", [(10, 10), (10, 75), (75, 10), (75, 75)])
190
  def test_default_label_is_outside_its_box_at_a_corner(top, left):
191
- ax = helio_foxes.plot_flux_map(prediction([box(top=top, left=left, width=10, height=10)]),
192
- show_harp_boxes=True, min_harp_flux=0)
193
  ax.figure.canvas.draw()
194
  renderer = ax.figure.canvas.get_renderer()
195
  label = ax.texts[0]
@@ -204,9 +199,9 @@ def test_default_label_is_outside_its_box_at_a_corner(top, left):
204
 
205
 
206
  def test_other_corners_are_tried_before_nudges():
207
- ax = helio_foxes.plot_flux_map(prediction([box(10000, top=40, left=40, width=20, height=20),
208
- box(10001, top=40, left=40, width=20, height=20)]),
209
- show_harp_boxes=True, min_harp_flux=0, harp_label_fontsize=10)
210
  ax.figure.canvas.draw()
211
  renderer = ax.figure.canvas.get_renderer()
212
  first, second = ax.texts
@@ -221,7 +216,7 @@ def test_other_corners_are_tried_before_nudges():
221
  def test_small_harp_label_avoids_a_larger_preceding_box():
222
  result = prediction([box(10000, top=40, left=40, width=20, height=20),
223
  box(10001, top=39, left=61, width=2, height=2)])
224
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0)
225
  ax.figure.canvas.draw()
226
  renderer = ax.figure.canvas.get_renderer()
227
  for label in ax.texts:
 
65
  @pytest.mark.parametrize("with_uncertainty", [False, True])
66
  def test_uncertainty_label_toggle_does_not_change_results(show_uncertainty, with_uncertainty):
67
  result = prediction([box()], with_uncertainty=with_uncertainty)
68
+ ax = result.plot_flux_map(
69
+ show_harp_boxes=True, min_harp_flux=0,
70
+ show_harp_uncertainty=show_uncertainty)
71
  text = "#1234\n1.00e-07"
72
  if show_uncertainty and with_uncertainty:
73
  text += "\n± 1.30e-08"
 
76
  plt.close(ax.figure)
77
 
78
 
79
+ def test_explicit_boxes_get_uncertainty_from_prediction_map(monkeypatch):
80
+ metadata = helio_foxes.api.ObservationMetadata(timestamp="2023-08-01", image_shape=(7, 2, 2))
 
81
  result = prediction(None, metadata=metadata)
82
+ monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch", lambda *a, **kw: pytest.fail("Plot must not query"))
83
+ ax = result.plot_flux_map(min_harp_flux=0, harp_regions=[box(top=50, height=50)])
 
 
 
 
 
 
 
84
  assert ax.texts[0].get_text() == "#1234\n3.00e-08\n± 5.00e-09"
 
85
  assert result.harp_regions is None
86
  plt.close(ax.figure)
87
 
 
92
  result = helio_foxes.Prediction(flux=4.096e-6, flux_map=np.full((64, 64), 1e-9),
93
  patch_uncertainty_map=np.full((64, 64), 2e-10), harp_regions=regions)
94
  offsets = {10000: (-100, 30), 10001: (0, -70), 10002: (100, 30)}
95
+ ax = result.plot_flux_map(
96
+ show_harp_boxes=True, min_harp_flux=0,
97
+ harp_label_offsets=offsets, harp_label_fontsize=10)
98
  for size, dpi in [((7, 6), 100), ((5.5, 5.5), 150)]:
99
  ax.figure.set_size_inches(*size)
100
  ax.figure.set_dpi(dpi)
 
120
  flux=4.096e-6, flux_map=np.full((64, 64), 1e-9), harp_regions=regions,
121
  patch_uncertainty_map=np.full((64, 64), 2e-10) if with_uncertainty else None,
122
  )
123
+ ax = result.plot_flux_map(show_harp_boxes=True, min_harp_flux=0, harp_label_fontsize=10)
124
  ax.figure.canvas.draw()
125
  renderer = ax.figure.canvas.get_renderer()
126
  bounds = [label.get_bbox_patch().get_window_extent(renderer) for label in ax.texts]
 
139
  def test_small_label_overlap_gets_a_small_nudge_instead_of_a_full_height_jump():
140
  result = prediction([box(10000, top=30, left=20, width=5, height=5),
141
  box(10001, top=30, left=20, width=5, height=5)])
142
+ ax = result.plot_flux_map(show_harp_boxes=True, min_harp_flux=0, harp_label_max_shift=0)
143
  ax.figure.canvas.draw()
144
  renderer = ax.figure.canvas.get_renderer()
145
  height = ax.texts[0].get_bbox_patch().get_window_extent(renderer).height / renderer.points_to_pixels(1)
 
147
 
148
  # Start the second label just one point inside the first label's bottom edge.
149
  start = (3, -3 - height + 1)
150
+ ax = result.plot_flux_map(
151
+ show_harp_boxes=True, min_harp_flux=0,
152
+ harp_label_offsets={10001: start})
153
  ax.figure.canvas.draw()
154
  renderer = ax.figure.canvas.get_renderer()
155
  first, second = [label.get_bbox_patch().get_window_extent(renderer) for label in ax.texts]
 
164
  def test_automatic_label_movement_stays_within_limit(max_shift):
165
  regions = [box(10000 + i, top=45, left=45, width=3, height=3) for i in range(6)]
166
  result = prediction(regions)
167
+ ax = result.plot_flux_map(
168
+ show_harp_boxes=True, min_harp_flux=0,
169
+ harp_label_max_shift=max_shift)
170
  for label in ax.texts:
171
  corner_offset = (-3 if label.get_ha() == "right" else 3,
172
  3 if label.get_va() == "bottom" else -3)
 
178
  @pytest.mark.parametrize("max_shift", [-1, np.inf, np.nan])
179
  def test_invalid_label_shift_limit_is_rejected(max_shift):
180
  with pytest.raises(ValueError, match="harp_label_max_shift must be finite and nonnegative"):
181
+ prediction([]).plot_flux_map(harp_label_max_shift=max_shift)
182
 
183
 
184
  @pytest.mark.parametrize("top,left", [(10, 10), (10, 75), (75, 10), (75, 75)])
185
  def test_default_label_is_outside_its_box_at_a_corner(top, left):
186
+ ax = prediction([box(top=top, left=left, width=10, height=10)]).plot_flux_map(
187
+ show_harp_boxes=True, min_harp_flux=0)
188
  ax.figure.canvas.draw()
189
  renderer = ax.figure.canvas.get_renderer()
190
  label = ax.texts[0]
 
199
 
200
 
201
  def test_other_corners_are_tried_before_nudges():
202
+ ax = prediction([box(10000, top=40, left=40, width=20, height=20),
203
+ box(10001, top=40, left=40, width=20, height=20)]).plot_flux_map(
204
+ show_harp_boxes=True, min_harp_flux=0, harp_label_fontsize=10)
205
  ax.figure.canvas.draw()
206
  renderer = ax.figure.canvas.get_renderer()
207
  first, second = ax.texts
 
216
  def test_small_harp_label_avoids_a_larger_preceding_box():
217
  result = prediction([box(10000, top=40, left=40, width=20, height=20),
218
  box(10001, top=39, left=61, width=2, height=2)])
219
+ ax = result.plot_flux_map(show_harp_boxes=True, min_harp_flux=0)
220
  ax.figure.canvas.draw()
221
  renderer = ax.figure.canvas.get_renderer()
222
  for label in ax.texts:
tests/test_legacy_calibration.py CHANGED
@@ -34,8 +34,8 @@ def predictors(model, monkeypatch, tmp_path, **options):
34
  checkpoint = tmp_path / "model.ckpt"
35
  checkpoint.touch()
36
  return (
37
- helio_foxes.load_model(checkpoint, device="cpu"),
38
- helio_foxes.load_model(checkpoint, device="cpu", legacy_model=True, **options),
39
  )
40
 
41
 
@@ -70,26 +70,27 @@ def test_public_prediction_scales_all_physical_outputs(model, monkeypatch, tmp_p
70
  np.testing.assert_array_equal(np.asarray(model.sxr_norm), norm)
71
  assert corrected.intervals is None
72
  assert corrected.patch_uncertainty_map is None
73
- frame = helio_foxes.PredictionSeries((corrected,)).to_dataframe()
74
  assert frame.iloc[0].flux_scale_factor == scale
75
- assert frame.iloc[0].observed_xrsb_flux == 1e-6
76
 
77
 
78
- def test_timestamp_requirement_and_custom_cutoff(model, monkeypatch, tmp_path):
79
  native, legacy = predictors(model, monkeypatch, tmp_path, legacy_cutoff="2019-01-01")
80
  image = np.ones((7, 16, 16), dtype=np.float32)
81
- assert native.predict(image).flux_scale_factor == 1
82
- with pytest.raises(ValueError, match="timestamp is required"):
83
- legacy.predict(image)
84
- corrected = legacy.predict(image, timestamp="2018-12-31T23:59:59Z")
85
- assert corrected.flux_scale_factor == .7
86
- assert legacy.predict(image, timestamp="2019-01-01").flux_scale_factor == 1
87
 
 
 
88
 
89
- @pytest.mark.parametrize("bad", ["true", "false", None, 1])
 
 
 
 
 
90
  def test_invalid_legacy_flag_rejected_before_loading(bad):
91
  with pytest.raises(ValueError, match="legacy_model must be a boolean"):
92
- helio_foxes.load_model("missing.ckpt", legacy_model=bad)
93
 
94
 
95
  def test_timestamp_stems_and_invalid_dates():
@@ -192,10 +193,30 @@ def test_gaussian_checkpoints_reject_legacy_correction(tmp_path, checkpoint_form
192
  checkpoint = tmp_path / 'gaussian.pt'
193
  torch.save({'model': gaussian}, checkpoint)
194
  with pytest.raises(ValueError, match="only supported for deterministic"):
195
- helio_foxes.load_model(checkpoint, device="cpu", legacy_model=True)
196
  dataset = TensorDataset(torch.ones(1, 2, 2, 7), torch.tensor([1e-6]))
197
  with pytest.raises(ValueError, match="only supported for deterministic"):
198
  next(evaluate_model_on_dataset(
199
  gaussian, dataset, times=["2015-01-01"],
200
  config_data={"legacy_model": True, "num_workers": 0},
201
  ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  checkpoint = tmp_path / "model.ckpt"
35
  checkpoint.touch()
36
  return (
37
+ helio_foxes.FOXESModel(checkpoint, device="cpu"),
38
+ helio_foxes.FOXESModel(checkpoint, device="cpu", legacy_model=True, **options),
39
  )
40
 
41
 
 
70
  np.testing.assert_array_equal(np.asarray(model.sxr_norm), norm)
71
  assert corrected.intervals is None
72
  assert corrected.patch_uncertainty_map is None
73
+ frame = helio_foxes.PredictionTimeSeries((corrected,)).full_disk_light_curve()
74
  assert frame.iloc[0].flux_scale_factor == scale
75
+ assert frame.iloc[0].observed_flux == 1e-6
76
 
77
 
78
+ def test_custom_cutoff(model, monkeypatch, tmp_path):
79
  native, legacy = predictors(model, monkeypatch, tmp_path, legacy_cutoff="2019-01-01")
80
  image = np.ones((7, 16, 16), dtype=np.float32)
 
 
 
 
 
 
81
 
82
+ def at(timestamp):
83
+ return helio_foxes.Observation.from_array(image, timestamp=timestamp)
84
 
85
+ assert native.predict(at("2018-12-31T23:59:59Z")).flux_scale_factor == 1
86
+ assert legacy.predict(at("2018-12-31T23:59:59Z")).flux_scale_factor == .7
87
+ assert legacy.predict(at("2019-01-01")).flux_scale_factor == 1
88
+
89
+
90
+ @pytest.mark.parametrize("bad", ["true", "false", 1])
91
  def test_invalid_legacy_flag_rejected_before_loading(bad):
92
  with pytest.raises(ValueError, match="legacy_model must be a boolean"):
93
+ helio_foxes.FOXESModel("missing.ckpt", legacy_model=bad)
94
 
95
 
96
  def test_timestamp_stems_and_invalid_dates():
 
193
  checkpoint = tmp_path / 'gaussian.pt'
194
  torch.save({'model': gaussian}, checkpoint)
195
  with pytest.raises(ValueError, match="only supported for deterministic"):
196
+ helio_foxes.FOXESModel(checkpoint, device="cpu", legacy_model=True)
197
  dataset = TensorDataset(torch.ones(1, 2, 2, 7), torch.tensor([1e-6]))
198
  with pytest.raises(ValueError, match="only supported for deterministic"):
199
  next(evaluate_model_on_dataset(
200
  gaussian, dataset, times=["2015-01-01"],
201
  config_data={"legacy_model": True, "num_workers": 0},
202
  ))
203
+
204
+
205
+ @pytest.mark.parametrize("checkpoint,legacy_model,expected", [
206
+ ("uncertainty", None, False),
207
+ ("inverted-attention-mask", None, True),
208
+ ("localized-attention-mask", None, True),
209
+ ("no-attention-mask", None, True),
210
+ ("no-attention-mask", False, False),
211
+ ("uncertainty", True, True),
212
+ ])
213
+ def test_legacy_correction_defaults_by_checkpoint_name(model, monkeypatch, checkpoint, legacy_model, expected):
214
+ monkeypatch.setattr("forecasting.inference.load_model_from_config", lambda config: model)
215
+ monkeypatch.setattr("helio_foxes.api._resolve_checkpoint", lambda checkpoint: "model.ckpt")
216
+ options = {} if legacy_model is None else {"legacy_model": legacy_model}
217
+ assert helio_foxes.FOXESModel(checkpoint, device="cpu", **options).legacy_model is expected
218
+
219
+
220
+ def test_checkpoint_files_default_to_no_legacy_correction(model, monkeypatch, tmp_path):
221
+ native, _ = predictors(model, monkeypatch, tmp_path)
222
+ assert native.legacy_model is False
tests/test_observation_persistence.py CHANGED
@@ -15,7 +15,7 @@ import helio_foxes as foxes
15
  @pytest.mark.parametrize("include_data", [False, True])
16
  def test_full_observation_roundtrip(tmp_path, regions, include_data):
17
  timestamp = datetime(2023, 8, 1, tzinfo=timezone.utc)
18
- metadata = foxes.ObservationMetadata(timestamp, (7, 2, 2), padding_factor=0.2, harp_bbox_expansion=0.15)
19
  data = np.arange(28, dtype=np.float64).reshape(7, 2, 2) if include_data else None
20
  sxr = {"timestamp": timestamp, "xrsb_flux": np.float64(1e-6), "satellites": ["GOES-18"],
21
  "measurements": [{"timestamp": timestamp, "xrsa_flux": None, "satellite": "GOES-18"}]}
@@ -82,7 +82,7 @@ def test_bad_archives_and_invalid_input(tmp_path):
82
 
83
 
84
  def test_iterator_saves_before_yield_and_reload_has_no_queries(tmp_path, monkeypatch):
85
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
86
  progress_options = []
87
 
88
  def samples(times, *, on_error, progress):
@@ -91,14 +91,14 @@ def test_iterator_saves_before_yield_and_reload_has_no_queries(tmp_path, monkeyp
91
  yield stamp, np.full((7, 2, 2), stamp.hour, dtype=np.float32)
92
 
93
  monkeypatch.setattr(processor.aia_processor, "_iter_range", samples)
94
- observations = processor.iter_observations("2023-08-01", "2023-08-01 02:00", save_dir=tmp_path, progress=True)
95
  first = next(observations)
96
  assert len(list(tmp_path.glob("*.npz"))) == 1
97
  remainder = list(observations)
98
  assert progress_options == [True]
99
  assert len(remainder) == 2
100
  assert len(list(tmp_path.glob("*.npz"))) == 3
101
- monkeypatch.setattr(processor, "fetch_observation", lambda *a, **kw: pytest.fail("no network expected"))
102
  loaded = list(foxes.load_observations(tmp_path))
103
  assert [o.metadata.timestamp.hour for o in loaded] == [0, 1, 2]
104
  np.testing.assert_array_equal(loaded[0].data, first.data)
@@ -107,7 +107,7 @@ def test_iterator_saves_before_yield_and_reload_has_no_queries(tmp_path, monkeyp
107
 
108
 
109
  def test_existing_archive_skips_download_and_preprocessing(tmp_path, monkeypatch):
110
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
111
  closed = []
112
 
113
  def samples(times, **kwargs):
@@ -118,20 +118,20 @@ def test_existing_archive_skips_download_and_preprocessing(tmp_path, monkeypatch
118
  closed.append(True)
119
 
120
  monkeypatch.setattr(processor.aia_processor, "_iter_range", samples)
121
- list(processor.iter_observations("2023-08-01", "2023-08-01", save_dir=tmp_path))
122
  assert closed == [True]
123
  with monkeypatch.context() as patch:
124
  patch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("No AIA query/preprocessing"))
125
- patch.setattr(processor, "fetch_observation", lambda *a, **kw: pytest.fail("No supplementary query"))
126
- restored = list(processor.iter_observations("2023-08-01", "2023-08-01", save_dir=tmp_path, on_error="skip", progress=True))
127
  assert len(restored) == 1
128
  assert restored[0].data.shape == (7, 2, 2)
129
- list(processor.iter_observations("2023-08-01", "2023-08-01", save_dir=tmp_path, overwrite=True))
130
  assert closed == [True, True]
131
 
132
 
133
  def test_partial_cache_only_fetches_missing_and_preserves_order_with_skips(tmp_path, monkeypatch):
134
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
135
  for hour in (1, 3):
136
  observation = foxes.Observation.from_array(np.full((7, 2, 2), hour), timestamp=f"2023-08-01 0{hour}:00")
137
  observation.save(tmp_path / f"observation_20230801T0{hour}0000.000000Z.npz")
@@ -144,7 +144,7 @@ def test_partial_cache_only_fetches_missing_and_preserves_order_with_skips(tmp_p
144
  yield stamp, np.full((7, 2, 2), stamp.hour)
145
 
146
  monkeypatch.setattr(processor.aia_processor, "_iter_range", samples)
147
- observations = list(processor.iter_observations("2023-08-01", "2023-08-01 04:00", save_dir=tmp_path, on_error="skip"))
148
  assert [stamp.hour for stamp in requested] == [0, 2, 4]
149
  assert [o.metadata.timestamp.hour for o in observations] == [1, 2, 3, 4]
150
  assert [o.data[0, 0, 0] for o in observations] == [1, 2, 3, 4]
@@ -152,26 +152,26 @@ def test_partial_cache_only_fetches_missing_and_preserves_order_with_skips(tmp_p
152
 
153
 
154
  def test_corrupt_cache_does_not_trigger_download(tmp_path, monkeypatch):
155
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
156
  (tmp_path / "observation_20230801T000000.000000Z.npz").write_bytes(b"broken")
157
  monkeypatch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("No download"))
158
  with pytest.raises(ValueError):
159
- list(processor.iter_observations("2023-08-01", "2023-08-01", save_dir=tmp_path, on_error="skip"))
160
 
161
 
162
  def test_cached_observation_honors_disabled_sources(tmp_path, monkeypatch):
163
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
164
  observation = foxes.Observation.from_array(np.ones((7, 2, 2)), timestamp="2023-08-01", harp_regions=[], sxr={"xrsb_flux": 1e-6})
165
  observation.save(tmp_path / "observation_20230801T000000.000000Z.npz")
166
- monkeypatch.setattr(processor, "fetch_observation", lambda *a, **kw: pytest.fail("No query"))
167
- restored = list(processor.iter_observations("2023-08-01", "2023-08-01", save_dir=tmp_path, include_aia=False))[0]
168
  assert restored.data is None and restored.harp_regions is None and restored.sxr is None
169
 
170
 
171
  def test_cache_timestamp_must_match_requested_time(tmp_path, monkeypatch):
172
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
173
  observation = foxes.Observation.from_array(np.ones((7, 2, 2)), timestamp="2023-08-02")
174
  observation.save(tmp_path / "observation_20230801T000000.000000Z.npz")
175
  monkeypatch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("No query"))
176
  with pytest.raises(ValueError, match="timestamp does not match"):
177
- list(processor.iter_observations("2023-08-01", "2023-08-01", save_dir=tmp_path))
 
15
  @pytest.mark.parametrize("include_data", [False, True])
16
  def test_full_observation_roundtrip(tmp_path, regions, include_data):
17
  timestamp = datetime(2023, 8, 1, tzinfo=timezone.utc)
18
+ metadata = foxes.api.ObservationMetadata(timestamp, (7, 2, 2), padding_factor=0.2, harp_bbox_expansion=0.15)
19
  data = np.arange(28, dtype=np.float64).reshape(7, 2, 2) if include_data else None
20
  sxr = {"timestamp": timestamp, "xrsb_flux": np.float64(1e-6), "satellites": ["GOES-18"],
21
  "measurements": [{"timestamp": timestamp, "xrsa_flux": None, "satellite": "GOES-18"}]}
 
82
 
83
 
84
  def test_iterator_saves_before_yield_and_reload_has_no_queries(tmp_path, monkeypatch):
85
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
86
  progress_options = []
87
 
88
  def samples(times, *, on_error, progress):
 
91
  yield stamp, np.full((7, 2, 2), stamp.hour, dtype=np.float32)
92
 
93
  monkeypatch.setattr(processor.aia_processor, "_iter_range", samples)
94
+ observations = processor.fetch_range("2023-08-01", "2023-08-01 02:00", save_dir=tmp_path, progress=True)
95
  first = next(observations)
96
  assert len(list(tmp_path.glob("*.npz"))) == 1
97
  remainder = list(observations)
98
  assert progress_options == [True]
99
  assert len(remainder) == 2
100
  assert len(list(tmp_path.glob("*.npz"))) == 3
101
+ monkeypatch.setattr(processor, "fetch", lambda *a, **kw: pytest.fail("no network expected"))
102
  loaded = list(foxes.load_observations(tmp_path))
103
  assert [o.metadata.timestamp.hour for o in loaded] == [0, 1, 2]
104
  np.testing.assert_array_equal(loaded[0].data, first.data)
 
107
 
108
 
109
  def test_existing_archive_skips_download_and_preprocessing(tmp_path, monkeypatch):
110
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
111
  closed = []
112
 
113
  def samples(times, **kwargs):
 
118
  closed.append(True)
119
 
120
  monkeypatch.setattr(processor.aia_processor, "_iter_range", samples)
121
+ list(processor.fetch_range("2023-08-01", "2023-08-01", save_dir=tmp_path))
122
  assert closed == [True]
123
  with monkeypatch.context() as patch:
124
  patch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("No AIA query/preprocessing"))
125
+ patch.setattr(processor, "fetch", lambda *a, **kw: pytest.fail("No supplementary query"))
126
+ restored = list(processor.fetch_range("2023-08-01", "2023-08-01", save_dir=tmp_path, on_error="skip", progress=True))
127
  assert len(restored) == 1
128
  assert restored[0].data.shape == (7, 2, 2)
129
+ list(processor.fetch_range("2023-08-01", "2023-08-01", save_dir=tmp_path, overwrite=True))
130
  assert closed == [True, True]
131
 
132
 
133
  def test_partial_cache_only_fetches_missing_and_preserves_order_with_skips(tmp_path, monkeypatch):
134
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
135
  for hour in (1, 3):
136
  observation = foxes.Observation.from_array(np.full((7, 2, 2), hour), timestamp=f"2023-08-01 0{hour}:00")
137
  observation.save(tmp_path / f"observation_20230801T0{hour}0000.000000Z.npz")
 
144
  yield stamp, np.full((7, 2, 2), stamp.hour)
145
 
146
  monkeypatch.setattr(processor.aia_processor, "_iter_range", samples)
147
+ observations = list(processor.fetch_range("2023-08-01", "2023-08-01 04:00", save_dir=tmp_path, on_error="skip"))
148
  assert [stamp.hour for stamp in requested] == [0, 2, 4]
149
  assert [o.metadata.timestamp.hour for o in observations] == [1, 2, 3, 4]
150
  assert [o.data[0, 0, 0] for o in observations] == [1, 2, 3, 4]
 
152
 
153
 
154
  def test_corrupt_cache_does_not_trigger_download(tmp_path, monkeypatch):
155
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
156
  (tmp_path / "observation_20230801T000000.000000Z.npz").write_bytes(b"broken")
157
  monkeypatch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("No download"))
158
  with pytest.raises(ValueError):
159
+ list(processor.fetch_range("2023-08-01", "2023-08-01", save_dir=tmp_path, on_error="skip"))
160
 
161
 
162
  def test_cached_observation_honors_disabled_sources(tmp_path, monkeypatch):
163
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
164
  observation = foxes.Observation.from_array(np.ones((7, 2, 2)), timestamp="2023-08-01", harp_regions=[], sxr={"xrsb_flux": 1e-6})
165
  observation.save(tmp_path / "observation_20230801T000000.000000Z.npz")
166
+ monkeypatch.setattr(processor, "fetch", lambda *a, **kw: pytest.fail("No query"))
167
+ restored = list(processor.fetch_range("2023-08-01", "2023-08-01", save_dir=tmp_path, include_aia=False))[0]
168
  assert restored.data is None and restored.harp_regions is None and restored.sxr is None
169
 
170
 
171
  def test_cache_timestamp_must_match_requested_time(tmp_path, monkeypatch):
172
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
173
  observation = foxes.Observation.from_array(np.ones((7, 2, 2)), timestamp="2023-08-02")
174
  observation.save(tmp_path / "observation_20230801T000000.000000Z.npz")
175
  monkeypatch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("No query"))
176
  with pytest.raises(ValueError, match="timestamp does not match"):
177
+ list(processor.fetch_range("2023-08-01", "2023-08-01", save_dir=tmp_path))
tests/test_observation_series.py CHANGED
@@ -37,17 +37,12 @@ def test_numeric_timestamp_rejected():
37
  foxes.parse_timestamp(1690848000)
38
 
39
 
40
- def test_local_array_and_npy(tmp_path):
41
  data = np.ones((7, 2, 2))
42
  observation = foxes.Observation.from_array(data, timestamp="2023/08/01", harp_regions=[])
43
  assert observation.data.dtype == np.float32
44
  data[:] = 2
45
  assert np.all(observation.data == 1)
46
- path = tmp_path / "stack.npy"
47
- np.save(path, observation.data)
48
- loaded = foxes.Observation.from_npy(path, timestamp="August 1, 2023")
49
- assert loaded.metadata == observation.metadata
50
- np.testing.assert_array_equal(loaded.data, observation.data)
51
  for bad in [np.zeros((2, 2)), np.full((7, 2, 2), np.nan), np.ones((7, 2, 2), dtype=complex)]:
52
  with pytest.raises(ValueError, match="channel-first"):
53
  foxes.Observation.from_array(bad, timestamp="2023-08-01")
@@ -75,7 +70,7 @@ def test_local_fits_preprocessing_preserves_files(monkeypatch, tmp_path):
75
 
76
 
77
  def test_range_grid_and_bulk_dispatch(monkeypatch):
78
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
79
  calls = []
80
 
81
  def bulk(times, *, on_error, progress=False):
@@ -84,16 +79,16 @@ def test_range_grid_and_bulk_dispatch(monkeypatch):
84
  yield stamp, np.zeros((7, 2, 2))
85
 
86
  monkeypatch.setattr(processor.aia_processor, "_iter_range", bulk)
87
- monkeypatch.setattr(processor.aia_processor, "fetch_date", lambda *a: pytest.fail("single fetch"))
88
- observations = list(processor.iter_observations("2023/08/01", "2023-08-01T00:25Z", cadence="12min"))
89
  assert len(calls) == 1
90
  assert [o.metadata.timestamp.minute for o in observations] == [0, 12, 24]
91
  assert all(o.data.shape == (7, 2, 2) for o in observations)
92
  for cadence in [0, -1, "NaT", "nonsense", True, float("inf"), "500ms"]:
93
  with pytest.raises(ValueError, match="cadence"):
94
- list(processor.iter_observations("2023-08-01", "2023-08-02", cadence=cadence))
95
  with pytest.raises(ValueError, match="end"):
96
- list(processor.iter_observations("2023-08-02", "2023-08-01"))
97
 
98
 
99
  def test_bulk_query_once_and_bounded_selection(monkeypatch, tmp_path, capsys):
@@ -164,9 +159,9 @@ def test_bulk_preprocessing_cleanup(monkeypatch):
164
 
165
 
166
  def test_range_without_aia_never_downloads(monkeypatch):
167
- processor = foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False)
168
  monkeypatch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("download"))
169
- observations = list(processor.iter_observations("2023-08-01", "2023-08-01", include_aia=False))
170
  assert len(observations) == 1
171
  assert observations[0].data is None
172
 
@@ -184,16 +179,16 @@ def test_harp_series_gaps_and_model_reuse():
184
  harp_regions=[region] if len(calls) != 2 else [],
185
  )
186
 
187
- series = foxes.Predictor.predict_series(Model(), iter(observations))
188
  assert len(calls) == 3
189
  curve = series.harp_light_curves()[12]
190
  np.testing.assert_allclose(curve.flux_sum, [4e-6, np.nan, 4e-6], equal_nan=True)
191
  assert curve.flux_sum_uncertainty.isna().all()
192
  assert str(curve.index.tz) == "UTC"
193
- ax = series.plot(include_full_disk=True)
194
  assert len(ax.lines) == 2
195
  assert np.isnan(ax.lines[0].get_ydata()[1])
196
  plt.close(ax.figure)
197
  with pytest.raises(ValueError, match="unique"):
198
- foxes.PredictionSeries((series.predictions[0], series.predictions[0]))
199
- assert foxes.PredictionSeries(()).to_dataframe().empty
 
37
  foxes.parse_timestamp(1690848000)
38
 
39
 
40
+ def test_local_array():
41
  data = np.ones((7, 2, 2))
42
  observation = foxes.Observation.from_array(data, timestamp="2023/08/01", harp_regions=[])
43
  assert observation.data.dtype == np.float32
44
  data[:] = 2
45
  assert np.all(observation.data == 1)
 
 
 
 
 
46
  for bad in [np.zeros((2, 2)), np.full((7, 2, 2), np.nan), np.ones((7, 2, 2), dtype=complex)]:
47
  with pytest.raises(ValueError, match="channel-first"):
48
  foxes.Observation.from_array(bad, timestamp="2023-08-01")
 
70
 
71
 
72
  def test_range_grid_and_bulk_dispatch(monkeypatch):
73
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
74
  calls = []
75
 
76
  def bulk(times, *, on_error, progress=False):
 
79
  yield stamp, np.zeros((7, 2, 2))
80
 
81
  monkeypatch.setattr(processor.aia_processor, "_iter_range", bulk)
82
+ monkeypatch.setattr(processor.aia_processor, "fetch", lambda *a: pytest.fail("single fetch"))
83
+ observations = list(processor.fetch_range("2023/08/01", "2023-08-01T00:25Z", cadence="12min"))
84
  assert len(calls) == 1
85
  assert [o.metadata.timestamp.minute for o in observations] == [0, 12, 24]
86
  assert all(o.data.shape == (7, 2, 2) for o in observations)
87
  for cadence in [0, -1, "NaT", "nonsense", True, float("inf"), "500ms"]:
88
  with pytest.raises(ValueError, match="cadence"):
89
+ list(processor.fetch_range("2023-08-01", "2023-08-02", cadence=cadence))
90
  with pytest.raises(ValueError, match="end"):
91
+ list(processor.fetch_range("2023-08-02", "2023-08-01"))
92
 
93
 
94
  def test_bulk_query_once_and_bounded_selection(monkeypatch, tmp_path, capsys):
 
159
 
160
 
161
  def test_range_without_aia_never_downloads(monkeypatch):
162
+ processor = foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False)
163
  monkeypatch.setattr(processor.aia_processor, "_iter_range", lambda *a, **kw: pytest.fail("download"))
164
+ observations = list(processor.fetch_range("2023-08-01", "2023-08-01", include_aia=False))
165
  assert len(observations) == 1
166
  assert observations[0].data is None
167
 
 
179
  harp_regions=[region] if len(calls) != 2 else [],
180
  )
181
 
182
+ series = foxes.FOXESModel.predict_time_series(Model(), iter(observations))
183
  assert len(calls) == 3
184
  curve = series.harp_light_curves()[12]
185
  np.testing.assert_allclose(curve.flux_sum, [4e-6, np.nan, 4e-6], equal_nan=True)
186
  assert curve.flux_sum_uncertainty.isna().all()
187
  assert str(curve.index.tz) == "UTC"
188
+ ax = series.plot_light_curves(show_full_disk=True)
189
  assert len(ax.lines) == 2
190
  assert np.isnan(ax.lines[0].get_ydata()[1])
191
  plt.close(ax.figure)
192
  with pytest.raises(ValueError, match="unique"):
193
+ foxes.PredictionTimeSeries((series.predictions[0], series.predictions[0]))
194
+ assert foxes.PredictionTimeSeries(()).full_disk_light_curve().empty
tests/test_public_api.py CHANGED
@@ -14,6 +14,12 @@ import helio_foxes
14
  from forecasting.model import CoupledGaussianViTLocal, ViTLocal
15
 
16
 
 
 
 
 
 
 
17
  def test_aia_processor_uses_temporary_files_and_returns_stack(monkeypatch):
18
  staged = []
19
 
@@ -42,11 +48,11 @@ def test_aia_processor_uses_temporary_files_and_returns_stack(monkeypatch):
42
 
43
  monkeypatch.setitem(sys.modules, "download.download_sdo", types.SimpleNamespace(SDODownloader=Downloader))
44
  monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=Stacker))
45
- stack = helio_foxes.AIAProcessor(resolution=2).fetch_date("2023-08-01T00:00:00Z")
46
  assert stack.shape == (7, 2, 2)
47
  assert stack.dtype == np.float32
48
  assert not __import__("os").path.exists(staged[0])
49
- observation = helio_foxes.ObservationProcessor(resolution=2, include_harps=False, include_sxr=False).fetch_observation(
50
  "2023-07-31T20:00:00-04:00"
51
  )
52
  assert isinstance(observation, helio_foxes.Observation)
@@ -72,13 +78,12 @@ def test_aia_processor_rejects_partial_download_and_cleans_up(monkeypatch):
72
  monkeypatch.setitem(sys.modules, "download.download_sdo", types.SimpleNamespace(SDODownloader=Downloader))
73
  monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=object))
74
  with pytest.raises(FileNotFoundError, match="wavelengths"):
75
- helio_foxes.AIAProcessor(resolution=2).fetch_date("2023-08-01T00:00:00")
76
  assert not __import__("os").path.exists(staged[0])
77
 
78
 
79
  @pytest.mark.parametrize("model_class", [ViTLocal, CoupledGaussianViTLocal])
80
- @pytest.mark.parametrize("input_kind", ["array", "observation", "timestamped_array"])
81
- def test_predict_matches_model_outputs(model_class, input_kind, monkeypatch, tmp_path):
82
  kwargs = dict(
83
  embed_dim=8, hidden_dim=16, num_channels=7,
84
  num_heads=2, num_layers=1, patch_size=1,
@@ -95,100 +100,86 @@ def test_predict_matches_model_outputs(model_class, input_kind, monkeypatch, tmp
95
  )
96
  checkpoint = tmp_path / "model.ckpt"
97
  checkpoint.touch()
98
- predictor = helio_foxes.load_model(checkpoint, device="cpu")
99
  assert predictor.model_kwargs == kwargs
100
 
101
  image = np.zeros((7, 2, 2), dtype=np.float32)
102
- timestamp = "2023-08-01T00:00:00Z"
103
- metadata = None
104
  regions = [{"HARPNUM": 1234, "top_pct": 0, "left_pct": 0,
105
  "width_pct": 50, "height_pct": 50}]
106
  sxr = {"xrsb_flux": 1e-6, "xrsa_flux": 1e-8, "satellite": "GOES-18"}
107
- if input_kind == "observation":
108
- metadata = helio_foxes.ObservationMetadata(
109
- timestamp=timestamp, image_shape=image.shape, padding_factor=0.2,
110
- )
111
- image = helio_foxes.Observation(data=image, metadata=metadata, harp_regions=regions, sxr=sxr)
112
- result = helio_foxes.predict(
113
- image, model=predictor,
114
- **({"timestamp": timestamp} if input_kind == "timestamped_array" else {}),
115
  )
116
- if input_kind == "observation":
117
- assert result.metadata is metadata
118
- assert result.sxr is sxr
119
- assert result.harp_regions is not regions
120
- assert result.harp_regions[0]["harpnum"] == 1234
121
- assert result.harp_regions[0]["flux_sum"] == pytest.approx(float(max(result.flux_map[1, 0], 0)))
122
- assert result.harp_regions[0]["top_pct"] == regions[0]["top_pct"]
123
- assert "flux_sum" not in regions[0]
124
- monkeypatch.setattr(
125
- helio_foxes.HARPProcessor, "fetch_date",
126
- lambda *args, **kwargs: pytest.fail("Plot must reuse observation HARPs"),
127
- )
128
- with pytest.raises(ValueError, match="timestamp conflicts"):
129
- helio_foxes.predict(image, model=predictor, timestamp="2023-08-02T00:00:00Z")
130
- with pytest.raises(ValueError, match="Observation has no AIA data"):
131
- helio_foxes.predict(helio_foxes.Observation(data=None, metadata=metadata), model=predictor)
132
- elif input_kind == "timestamped_array":
133
- assert result.metadata.timestamp == datetime(2023, 8, 1, tzinfo=timezone.utc)
134
- assert result.metadata.image_shape == image.shape
135
- assert result.metadata.wavelengths == helio_foxes.AIAProcessor.WAVELENGTHS
136
- else:
137
- assert result.metadata is None
138
- if input_kind != "observation":
139
- assert result.harp_regions is None
140
- assert result.sxr is None
141
  assert result.flux_map.shape == (2, 2)
142
  assert np.isclose(result.flux_map.sum(), result.flux, rtol=1e-5)
143
  if model_class is CoupledGaussianViTLocal:
144
  assert set(result.intervals) == {"68", "95"}
145
  assert result.patch_uncertainty_map.shape == (2, 2)
146
- if input_kind == "observation":
147
- assert result.harp_regions[0]["flux_sum_uncertainty"] == pytest.approx(
148
- float(result.patch_uncertainty_map[1, 0]),
149
- )
150
  else:
151
  assert result.intervals is None
152
  assert result.patch_uncertainty_map is None
153
- if input_kind == "observation":
154
- assert result.harp_regions[0]["flux_sum_uncertainty"] is None
155
 
156
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=input_kind == "observation", min_harp_flux=0)
 
 
 
 
157
  assert ax.images[0].origin == "lower"
158
  predicted_title = f"Predicted FOXES: {result.flux:.2e}"
159
  if result.patch_uncertainty_map is not None:
160
  full_disk_uncertainty = np.sqrt(np.sum(np.square(result.patch_uncertainty_map)))
161
  predicted_title += f" ± {full_disk_uncertainty:.2e}"
162
  assert f"{predicted_title} W/m²" in ax.get_title()
163
- if input_kind == "observation":
164
- assert "Observed SXR-B: 1.00e-06 W/m²" in ax.get_title()
165
- if input_kind == "observation":
166
- assert len(ax.patches) == 1
167
- expected_label = f'#1234\n{result.harp_regions[0]["flux_sum"]:.2e}'
168
- if result.patch_uncertainty_map is not None:
169
- expected_label += f'\n± {result.harp_regions[0]["flux_sum_uncertainty"]:.2e}'
170
- assert ax.texts[0].get_text() == expected_label
171
  plt.close(ax.figure)
172
 
 
 
 
 
 
 
 
173
  with pytest.raises(ValueError, match="shape"):
174
- helio_foxes.predict(np.zeros((2, 2, 7)), model=predictor)
175
 
176
 
177
- @pytest.mark.parametrize("plotter", [helio_foxes.plot_flux_map, helio_foxes.plot_uncertainty_map])
178
- def test_plot_map_color_limits(plotter):
179
  values = np.array([[1e-9, 1e-8], [0, 1e-7]])
180
- ax = plotter(values)
 
 
181
  assert ax.images[0].norm.vmin == 1e-9
182
  assert ax.images[0].norm.vmax == 1e-7
183
  plt.close(ax.figure)
184
 
185
- ax = plotter(values, vmin=1e-10, vmax=1e-6)
186
  assert ax.images[0].norm.vmin == 1e-10
187
  assert ax.images[0].norm.vmax == 1e-6
188
  plt.close(ax.figure)
189
 
190
  with pytest.raises(ValueError, match="vmin and vmax"):
191
- plotter(values, vmin=0)
192
 
193
 
194
  def test_plot_flux_map_harp_toggle_draws_boxes_and_patch_sums():
@@ -198,81 +189,37 @@ def test_plot_flux_map_harp_toggle_draws_boxes_and_patch_sums():
198
  "width_pct": 50, "height_pct": 50,
199
  }]
200
 
201
- ax = helio_foxes.plot_flux_map(flux_map, harp_regions=regions)
202
  assert not ax.patches and not ax.texts
203
  assert not any(panel.tables for panel in ax.figure.axes)
204
  plt.close(ax.figure)
205
 
206
- ax = helio_foxes.plot_flux_map(
207
- flux_map, show_harp_boxes=True, harp_regions=regions, min_harp_flux=0,
208
  )
209
  assert len(ax.patches) == 1
210
  assert np.allclose(ax.patches[0].get_bbox().bounds, (-0.5, 0.5, 1, 1))
211
  assert ax.texts[0].get_text() == "#1234\n3.00e-09"
212
  plt.close(ax.figure)
213
 
214
- with pytest.raises(ValueError, match="timestamp is required"):
215
- helio_foxes.plot_flux_map(flux_map, show_harp_boxes=True)
216
-
217
-
218
- def test_plot_flux_map_queries_harps_when_regions_omitted(monkeypatch):
219
- calls = []
220
- region = {
221
- "HARPNUM": 1234, "top_pct": 0, "left_pct": 0,
222
- "width_pct": 50, "height_pct": 50,
223
- }
224
-
225
- def fetch(self, timestamp):
226
- calls.append((self.email, timestamp))
227
- return [region]
228
-
229
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", fetch)
230
- flux_map = np.array([[1e-9, 2e-9], [3e-9, 4e-9]])
231
- ax = helio_foxes.plot_flux_map(
232
- flux_map, show_harp_boxes=True, min_harp_flux=0,
233
- timestamp="2023-08-01T00:00:00Z", jsoc_email="test@example.com",
234
- )
235
- assert calls == [("test@example.com", "2023-08-01T00:00:00Z")]
236
- assert len(ax.patches) == 1
237
- assert ax.texts[0].get_text() == "#1234\n3.00e-09"
238
- plt.close(ax.figure)
239
-
240
- ax = helio_foxes.plot_flux_map(
241
- flux_map, show_harp_boxes=True, harp_regions=[],
242
- )
243
- assert len(ax.patches) == 0
244
- assert len(calls) == 1
245
  plt.close(ax.figure)
246
 
247
 
248
- def test_plot_flux_map_uses_prediction_metadata_for_harp_query(monkeypatch):
249
- calls = []
250
-
251
- def fetch(self, timestamp):
252
- calls.append((self.email, timestamp, self.resolution, self.padding_factor))
253
- return [{"HARPNUM": 1234, "top_pct": 0, "left_pct": 0,
254
- "width_pct": 50, "height_pct": 50}]
255
-
256
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", fetch)
257
- metadata = helio_foxes.ObservationMetadata(
258
- timestamp="2023-07-31T20:00:00-04:00",
259
- image_shape=(7, 1024, 1024), padding_factor=0.25,
260
- )
261
  result = helio_foxes.Prediction(
262
- flux=1e-8, flux_map=np.array([[1e-9, 2e-9], [3e-9, 4e-9]]),
263
- metadata=metadata,
264
  )
265
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, jsoc_email="test@example.com", min_harp_flux=0)
266
- assert calls == [("test@example.com", metadata.timestamp, 1024, 0.25)]
267
- assert ax.texts[0].get_text() == "#1234\n3.00e-09"
268
  plt.close(ax.figure)
269
- with pytest.raises(ValueError, match="timestamp conflicts"):
270
- helio_foxes.plot_flux_map(result, show_harp_boxes=True, timestamp="2024-01-01")
271
- assert len(calls) == 1
272
 
273
 
274
  def test_observation_rejects_metadata_with_wrong_image_shape():
275
- metadata = helio_foxes.ObservationMetadata(timestamp="2023-08-01", image_shape=(7, 2, 2))
276
  with pytest.raises(ValueError, match="shape does not match"):
277
  helio_foxes.Observation(data=np.zeros((7, 4, 4)), metadata=metadata)
278
 
@@ -303,16 +250,16 @@ def test_observation_processor_source_toggles(monkeypatch, include_aia, include_
303
  calls.append(("sxr", timestamp, self.tolerance, self.satellite))
304
  return sxr
305
 
306
- monkeypatch.setattr(helio_foxes.AIAProcessor, "fetch_date", fetch_aia)
307
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", fetch_harp)
308
- monkeypatch.setattr(helio_foxes.SXRProcessor, "fetch_date", fetch_sxr)
309
  toggles = {"include_aia": include_aia, "include_harps": include_harps, "include_sxr": include_sxr}
310
  # Per-call values override the opposite configuration without changing it.
311
  configured = {key: not value for key, value in toggles.items()} if per_call else toggles
312
- processor = helio_foxes.ObservationProcessor(
313
  email="test@example.com", resolution=2, sxr_tolerance=90, sxr_satellite=16, **configured,
314
  )
315
- observation = processor.fetch_observation(
316
  "2023-07-31T20:00:00-04:00", **(toggles if per_call else {}),
317
  )
318
  timestamp = datetime(2023, 8, 1, tzinfo=timezone.utc)
@@ -350,19 +297,19 @@ def test_observation_processor_defaults_to_all_and_keeps_aia_when_supplements_mi
350
  calls.append("sxr")
351
  return None
352
 
353
- monkeypatch.setattr(helio_foxes.AIAProcessor, "fetch_date", fetch_aia)
354
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", fetch_harp)
355
- monkeypatch.setattr(helio_foxes.SXRProcessor, "fetch_date", fetch_sxr)
356
- observation = helio_foxes.ObservationProcessor(resolution=2).fetch_observation("2023-08-01")
357
  assert calls == ["aia", "harp", "sxr"]
358
  assert observation.data is stack
359
  assert observation.harp_regions == []
360
  assert observation.sxr is None
361
 
362
 
363
- def test_observation_records_harp_expansion_for_deferred_query(monkeypatch):
364
  monkeypatch.setattr(
365
- helio_foxes.AIAProcessor, "fetch_date", lambda self, timestamp: np.zeros((7, 2, 2), dtype=np.float32),
366
  )
367
  calls = []
368
 
@@ -370,17 +317,17 @@ def test_observation_records_harp_expansion_for_deferred_query(monkeypatch):
370
  calls.append((self.bbox_expansion, timestamp))
371
  return []
372
 
373
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", fetch)
374
- processor = helio_foxes.ObservationProcessor(resolution=2, harp_bbox_expansion=0.1, include_sxr=False)
375
- observation = processor.fetch_observation("2023-08-01", include_harps=False)
376
  assert calls == []
377
  assert observation.metadata.harp_bbox_expansion == 0.1
378
  result = helio_foxes.Prediction(flux=4e-9, flux_map=np.full((2, 2), 1e-9), metadata=observation.metadata)
379
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True)
380
- assert calls == [(0.1, observation.metadata.timestamp)]
381
  plt.close(ax.figure)
382
- processor.fetch_observation("2023-08-01")
383
- assert calls == [(0.1, observation.metadata.timestamp)] * 2
384
 
385
 
386
  @pytest.mark.parametrize("regions", [[], [
@@ -388,7 +335,7 @@ def test_observation_records_harp_expansion_for_deferred_query(monkeypatch):
388
  ]])
389
  def test_plot_does_not_repeat_fetched_harp_queries(monkeypatch, regions):
390
  monkeypatch.setattr(
391
- helio_foxes.HARPProcessor, "fetch_date",
392
  lambda *args, **kwargs: pytest.fail("Already-fetched HARPs must not be queried again"),
393
  )
394
  result = helio_foxes.Prediction(
@@ -396,10 +343,10 @@ def test_plot_does_not_repeat_fetched_harp_queries(monkeypatch, regions):
396
  harp_regions=regions,
397
  )
398
  for _ in range(2):
399
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=0)
400
  assert len(ax.patches) == len(regions)
401
  plt.close(ax.figure)
402
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, harp_regions=[])
403
  assert not ax.patches
404
  plt.close(ax.figure)
405
 
@@ -435,7 +382,7 @@ def test_harp_labels_include_sorted_fluxes_and_match_fixed_rank_colors():
435
  {"HARPNUM": 2002, "top_pct": 0, "left_pct": 50, "width_pct": 50, "height_pct": 50},
436
  {"HARPNUM": 3003, "top_pct": 0, "left_pct": 0, "width_pct": 50, "height_pct": 50},
437
  ]
438
- ax = helio_foxes.plot_flux_map(flux_map, show_harp_boxes=True, harp_regions=regions, min_harp_flux=0)
439
  assert [text.get_text() for text in ax.texts] == ["#2002\n4.00e-09", "#3003\n3.00e-09", "#1001\n1.00e-09"]
440
  assert not any(panel.tables for panel in ax.figure.axes)
441
  for index, color in enumerate(("#56B4E9", "#E69F00", "#009E73")):
@@ -444,7 +391,7 @@ def test_harp_labels_include_sorted_fluxes_and_match_fixed_rank_colors():
444
  plt.close(ax.figure)
445
 
446
  # Removing the weakest HARP does not change the colors of ranks 1 and 2.
447
- ax = helio_foxes.plot_flux_map(flux_map, show_harp_boxes=True, harp_regions=regions[1:], min_harp_flux=0)
448
  assert np.allclose(ax.patches[0].get_edgecolor(), to_rgba("#56B4E9"))
449
  assert np.allclose(ax.patches[1].get_edgecolor(), to_rgba("#E69F00"))
450
  plt.close(ax.figure)
@@ -454,8 +401,8 @@ def test_harp_labels_use_caller_supplied_axes():
454
  _, ax = plt.subplots()
455
  regions = [{"HARPNUM": 1234, "top_pct": 0, "left_pct": 0,
456
  "width_pct": 50, "height_pct": 50}]
457
- returned = helio_foxes.plot_flux_map(
458
- np.array([[1e-9, 2e-9], [3e-9, 4e-9]]), ax=ax,
459
  show_harp_boxes=True, harp_regions=regions, min_harp_flux=0,
460
  )
461
  assert returned is ax
@@ -474,8 +421,8 @@ def test_harp_labels_remain_readable_after_resize_and_dpi_changes(supplied_axes)
474
  {"HARPNUM": 45678, "top_pct": 99, "left_pct": 0, "width_pct": 1, "height_pct": 1},
475
  ]
476
  ax = plt.subplots()[1] if supplied_axes else None
477
- ax = helio_foxes.plot_flux_map(
478
- np.ones((32, 32)) * 1e-9, ax=ax,
479
  show_harp_boxes=True, harp_regions=regions, min_harp_flux=0, harp_label_fontsize=10,
480
  )
481
  for size, dpi in [((7, 6), 100), ((4.2, 4.2), 150)]:
@@ -501,8 +448,8 @@ def test_harp_labels_accept_explicit_offsets_for_crowded_regions():
501
  {"HARPNUM": harpnum, "top_pct": 48, "left_pct": left, "width_pct": 1, "height_pct": 1}
502
  for harpnum, left in [(12345, 48), (23456, 50), (34567, 52)]
503
  ]
504
- ax = helio_foxes.plot_flux_map(
505
- np.ones((64, 64)) * 1e-9, show_harp_boxes=True,
506
  harp_regions=regions, harp_label_fontsize=12, min_harp_flux=0,
507
  harp_label_offsets={12345: (-100, 30), 23456: (0, -70), 34567: (100, 30)},
508
  )
@@ -526,7 +473,7 @@ def test_harp_flux_threshold_filters_only_plot(threshold, visible):
526
  result = helio_foxes.Prediction(
527
  flux=1e-8, flux_map=np.array([[1e-9, 2e-9], [3e-9, 4e-9]]), harp_regions=regions,
528
  )
529
- ax = helio_foxes.plot_flux_map(result, show_harp_boxes=True, min_harp_flux=threshold)
530
  assert len(ax.patches) == visible
531
  assert len(ax.texts) == visible
532
  assert len(result.harp_regions) == 3
@@ -535,10 +482,68 @@ def test_harp_flux_threshold_filters_only_plot(threshold, visible):
535
 
536
 
537
  @pytest.mark.parametrize("threshold", [-1, np.nan, np.inf])
538
- def test_plot_rejects_invalid_harp_flux_threshold_before_query(monkeypatch, threshold):
539
- monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch_date", lambda *a, **kw: pytest.fail("Unexpected query"))
540
  with pytest.raises(ValueError, match="min_harp_flux must be finite and nonnegative"):
541
- helio_foxes.plot_flux_map(
542
- np.ones((2, 2)), show_harp_boxes=True,
543
- timestamp="2023-08-01", min_harp_flux=threshold,
544
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  from forecasting.model import CoupledGaussianViTLocal, ViTLocal
15
 
16
 
17
+ def _prediction(flux_map):
18
+ """Wrap a bare flux map so it can be plotted."""
19
+ flux_map = np.asarray(flux_map)
20
+ return helio_foxes.Prediction(flux=float(flux_map.sum()), flux_map=flux_map)
21
+
22
+
23
  def test_aia_processor_uses_temporary_files_and_returns_stack(monkeypatch):
24
  staged = []
25
 
 
48
 
49
  monkeypatch.setitem(sys.modules, "download.download_sdo", types.SimpleNamespace(SDODownloader=Downloader))
50
  monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=Stacker))
51
+ stack = helio_foxes.AIAProcessor(resolution=2).fetch("2023-08-01T00:00:00Z")
52
  assert stack.shape == (7, 2, 2)
53
  assert stack.dtype == np.float32
54
  assert not __import__("os").path.exists(staged[0])
55
+ observation = helio_foxes.ObservationFetcher(resolution=2, include_harps=False, include_sxr=False).fetch(
56
  "2023-07-31T20:00:00-04:00"
57
  )
58
  assert isinstance(observation, helio_foxes.Observation)
 
78
  monkeypatch.setitem(sys.modules, "download.download_sdo", types.SimpleNamespace(SDODownloader=Downloader))
79
  monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=object))
80
  with pytest.raises(FileNotFoundError, match="wavelengths"):
81
+ helio_foxes.AIAProcessor(resolution=2).fetch("2023-08-01T00:00:00")
82
  assert not __import__("os").path.exists(staged[0])
83
 
84
 
85
  @pytest.mark.parametrize("model_class", [ViTLocal, CoupledGaussianViTLocal])
86
+ def test_predict_matches_model_outputs(model_class, monkeypatch, tmp_path):
 
87
  kwargs = dict(
88
  embed_dim=8, hidden_dim=16, num_channels=7,
89
  num_heads=2, num_layers=1, patch_size=1,
 
100
  )
101
  checkpoint = tmp_path / "model.ckpt"
102
  checkpoint.touch()
103
+ predictor = helio_foxes.FOXESModel(checkpoint, device="cpu")
104
  assert predictor.model_kwargs == kwargs
105
 
106
  image = np.zeros((7, 2, 2), dtype=np.float32)
 
 
107
  regions = [{"HARPNUM": 1234, "top_pct": 0, "left_pct": 0,
108
  "width_pct": 50, "height_pct": 50}]
109
  sxr = {"xrsb_flux": 1e-6, "xrsa_flux": 1e-8, "satellite": "GOES-18"}
110
+ metadata = helio_foxes.api.ObservationMetadata(
111
+ timestamp="2023-08-01T00:00:00Z", image_shape=image.shape, padding_factor=0.2,
 
 
 
 
 
 
112
  )
113
+ observation = helio_foxes.Observation(data=image, metadata=metadata, harp_regions=regions, sxr=sxr)
114
+ result = predictor.predict(observation)
115
+ assert result.metadata is metadata
116
+ assert result.sxr is sxr
117
+ assert result.observed_flux == 1e-6
118
+ assert result.harp_regions is not regions
119
+ assert result.harp_regions[0]["harpnum"] == 1234
120
+ assert result.harp_regions[0]["flux_sum"] == pytest.approx(float(max(result.flux_map[1, 0], 0)))
121
+ assert result.harp_regions[0]["top_pct"] == regions[0]["top_pct"]
122
+ assert "flux_sum" not in regions[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  assert result.flux_map.shape == (2, 2)
124
  assert np.isclose(result.flux_map.sum(), result.flux, rtol=1e-5)
125
  if model_class is CoupledGaussianViTLocal:
126
  assert set(result.intervals) == {"68", "95"}
127
  assert result.patch_uncertainty_map.shape == (2, 2)
128
+ assert result.harp_regions[0]["flux_sum_uncertainty"] == pytest.approx(
129
+ float(result.patch_uncertainty_map[1, 0]),
130
+ )
 
131
  else:
132
  assert result.intervals is None
133
  assert result.patch_uncertainty_map is None
134
+ assert result.harp_regions[0]["flux_sum_uncertainty"] is None
 
135
 
136
+ monkeypatch.setattr(
137
+ helio_foxes.HARPProcessor, "fetch",
138
+ lambda *args, **kwargs: pytest.fail("Plot must reuse observation HARPs"),
139
+ )
140
+ ax = result.plot_flux_map(min_harp_flux=0)
141
  assert ax.images[0].origin == "lower"
142
  predicted_title = f"Predicted FOXES: {result.flux:.2e}"
143
  if result.patch_uncertainty_map is not None:
144
  full_disk_uncertainty = np.sqrt(np.sum(np.square(result.patch_uncertainty_map)))
145
  predicted_title += f" ± {full_disk_uncertainty:.2e}"
146
  assert f"{predicted_title} W/m²" in ax.get_title()
147
+ assert "Observed SXR-B: 1.00e-06 W/m²" in ax.get_title()
148
+ assert len(ax.patches) == 1
149
+ expected_label = f'#1234\n{result.harp_regions[0]["flux_sum"]:.2e}'
150
+ if result.patch_uncertainty_map is not None:
151
+ expected_label += f'\n± {result.harp_regions[0]["flux_sum_uncertainty"]:.2e}'
152
+ assert ax.texts[0].get_text() == expected_label
 
 
153
  plt.close(ax.figure)
154
 
155
+ wrapped = predictor.predict(helio_foxes.Observation.from_array(image, timestamp="2023-08-01"))
156
+ assert wrapped.metadata.timestamp == datetime(2023, 8, 1, tzinfo=timezone.utc)
157
+ assert wrapped.harp_regions is None and wrapped.sxr is None and wrapped.observed_flux is None
158
+ with pytest.raises(TypeError, match="Observation.from_array"):
159
+ predictor.predict(image)
160
+ with pytest.raises(ValueError, match="Observation has no AIA data"):
161
+ predictor.predict(helio_foxes.Observation(data=None, metadata=metadata))
162
  with pytest.raises(ValueError, match="shape"):
163
+ predictor.predict(helio_foxes.Observation.from_array(np.zeros((7, 4, 4)), timestamp="2023-08-01"))
164
 
165
 
166
+ @pytest.mark.parametrize("method", ["plot_flux_map", "plot_uncertainty_map"])
167
+ def test_plot_map_color_limits(method):
168
  values = np.array([[1e-9, 1e-8], [0, 1e-7]])
169
+ result = helio_foxes.Prediction(flux=float(values.sum()), flux_map=values, patch_uncertainty_map=values)
170
+ plotter = getattr(result, method)
171
+ ax = plotter()
172
  assert ax.images[0].norm.vmin == 1e-9
173
  assert ax.images[0].norm.vmax == 1e-7
174
  plt.close(ax.figure)
175
 
176
+ ax = plotter(vmin=1e-10, vmax=1e-6)
177
  assert ax.images[0].norm.vmin == 1e-10
178
  assert ax.images[0].norm.vmax == 1e-6
179
  plt.close(ax.figure)
180
 
181
  with pytest.raises(ValueError, match="vmin and vmax"):
182
+ plotter(vmin=0)
183
 
184
 
185
  def test_plot_flux_map_harp_toggle_draws_boxes_and_patch_sums():
 
189
  "width_pct": 50, "height_pct": 50,
190
  }]
191
 
192
+ ax = _prediction(flux_map).plot_flux_map(show_harp_boxes=False, harp_regions=regions)
193
  assert not ax.patches and not ax.texts
194
  assert not any(panel.tables for panel in ax.figure.axes)
195
  plt.close(ax.figure)
196
 
197
+ ax = _prediction(flux_map).plot_flux_map(
198
+ show_harp_boxes=True, harp_regions=regions, min_harp_flux=0,
199
  )
200
  assert len(ax.patches) == 1
201
  assert np.allclose(ax.patches[0].get_bbox().bounds, (-0.5, 0.5, 1, 1))
202
  assert ax.texts[0].get_text() == "#1234\n3.00e-09"
203
  plt.close(ax.figure)
204
 
205
+ ax = _prediction(flux_map).plot_flux_map()
206
+ assert not ax.patches and not ax.texts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  plt.close(ax.figure)
208
 
209
 
210
+ def test_plot_flux_map_never_queries_jsoc(monkeypatch):
211
+ monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch", lambda *a, **kw: pytest.fail("Plot must not query"))
212
+ metadata = helio_foxes.api.ObservationMetadata(timestamp="2023-08-01", image_shape=(7, 2, 2))
 
 
 
 
 
 
 
 
 
 
213
  result = helio_foxes.Prediction(
214
+ flux=1e-8, flux_map=np.array([[1e-9, 2e-9], [3e-9, 4e-9]]), metadata=metadata,
 
215
  )
216
+ ax = result.plot_flux_map(show_harp_boxes=True)
217
+ assert not ax.patches
 
218
  plt.close(ax.figure)
 
 
 
219
 
220
 
221
  def test_observation_rejects_metadata_with_wrong_image_shape():
222
+ metadata = helio_foxes.api.ObservationMetadata(timestamp="2023-08-01", image_shape=(7, 2, 2))
223
  with pytest.raises(ValueError, match="shape does not match"):
224
  helio_foxes.Observation(data=np.zeros((7, 4, 4)), metadata=metadata)
225
 
 
250
  calls.append(("sxr", timestamp, self.tolerance, self.satellite))
251
  return sxr
252
 
253
+ monkeypatch.setattr(helio_foxes.AIAProcessor, "fetch", fetch_aia)
254
+ monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch", fetch_harp)
255
+ monkeypatch.setattr(helio_foxes.SXRProcessor, "fetch", fetch_sxr)
256
  toggles = {"include_aia": include_aia, "include_harps": include_harps, "include_sxr": include_sxr}
257
  # Per-call values override the opposite configuration without changing it.
258
  configured = {key: not value for key, value in toggles.items()} if per_call else toggles
259
+ processor = helio_foxes.ObservationFetcher(
260
  email="test@example.com", resolution=2, sxr_tolerance=90, sxr_satellite=16, **configured,
261
  )
262
+ observation = processor.fetch(
263
  "2023-07-31T20:00:00-04:00", **(toggles if per_call else {}),
264
  )
265
  timestamp = datetime(2023, 8, 1, tzinfo=timezone.utc)
 
297
  calls.append("sxr")
298
  return None
299
 
300
+ monkeypatch.setattr(helio_foxes.AIAProcessor, "fetch", fetch_aia)
301
+ monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch", fetch_harp)
302
+ monkeypatch.setattr(helio_foxes.SXRProcessor, "fetch", fetch_sxr)
303
+ observation = helio_foxes.ObservationFetcher(resolution=2).fetch("2023-08-01")
304
  assert calls == ["aia", "harp", "sxr"]
305
  assert observation.data is stack
306
  assert observation.harp_regions == []
307
  assert observation.sxr is None
308
 
309
 
310
+ def test_observation_records_harp_expansion(monkeypatch):
311
  monkeypatch.setattr(
312
+ helio_foxes.AIAProcessor, "fetch", lambda self, timestamp: np.zeros((7, 2, 2), dtype=np.float32),
313
  )
314
  calls = []
315
 
 
317
  calls.append((self.bbox_expansion, timestamp))
318
  return []
319
 
320
+ monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch", fetch)
321
+ processor = helio_foxes.ObservationFetcher(resolution=2, harp_bbox_expansion=0.1, include_sxr=False)
322
+ observation = processor.fetch("2023-08-01", include_harps=False)
323
  assert calls == []
324
  assert observation.metadata.harp_bbox_expansion == 0.1
325
  result = helio_foxes.Prediction(flux=4e-9, flux_map=np.full((2, 2), 1e-9), metadata=observation.metadata)
326
+ ax = result.plot_flux_map()
327
+ assert calls == []
328
  plt.close(ax.figure)
329
+ processor.fetch("2023-08-01")
330
+ assert calls == [(0.1, observation.metadata.timestamp)]
331
 
332
 
333
  @pytest.mark.parametrize("regions", [[], [
 
335
  ]])
336
  def test_plot_does_not_repeat_fetched_harp_queries(monkeypatch, regions):
337
  monkeypatch.setattr(
338
+ helio_foxes.HARPProcessor, "fetch",
339
  lambda *args, **kwargs: pytest.fail("Already-fetched HARPs must not be queried again"),
340
  )
341
  result = helio_foxes.Prediction(
 
343
  harp_regions=regions,
344
  )
345
  for _ in range(2):
346
+ ax = result.plot_flux_map(show_harp_boxes=True, min_harp_flux=0)
347
  assert len(ax.patches) == len(regions)
348
  plt.close(ax.figure)
349
+ ax = result.plot_flux_map(show_harp_boxes=True, harp_regions=[])
350
  assert not ax.patches
351
  plt.close(ax.figure)
352
 
 
382
  {"HARPNUM": 2002, "top_pct": 0, "left_pct": 50, "width_pct": 50, "height_pct": 50},
383
  {"HARPNUM": 3003, "top_pct": 0, "left_pct": 0, "width_pct": 50, "height_pct": 50},
384
  ]
385
+ ax = _prediction(flux_map).plot_flux_map(show_harp_boxes=True, harp_regions=regions, min_harp_flux=0)
386
  assert [text.get_text() for text in ax.texts] == ["#2002\n4.00e-09", "#3003\n3.00e-09", "#1001\n1.00e-09"]
387
  assert not any(panel.tables for panel in ax.figure.axes)
388
  for index, color in enumerate(("#56B4E9", "#E69F00", "#009E73")):
 
391
  plt.close(ax.figure)
392
 
393
  # Removing the weakest HARP does not change the colors of ranks 1 and 2.
394
+ ax = _prediction(flux_map).plot_flux_map(show_harp_boxes=True, harp_regions=regions[1:], min_harp_flux=0)
395
  assert np.allclose(ax.patches[0].get_edgecolor(), to_rgba("#56B4E9"))
396
  assert np.allclose(ax.patches[1].get_edgecolor(), to_rgba("#E69F00"))
397
  plt.close(ax.figure)
 
401
  _, ax = plt.subplots()
402
  regions = [{"HARPNUM": 1234, "top_pct": 0, "left_pct": 0,
403
  "width_pct": 50, "height_pct": 50}]
404
+ returned = _prediction(np.array([[1e-9, 2e-9], [3e-9, 4e-9]])).plot_flux_map(
405
+ ax=ax,
406
  show_harp_boxes=True, harp_regions=regions, min_harp_flux=0,
407
  )
408
  assert returned is ax
 
421
  {"HARPNUM": 45678, "top_pct": 99, "left_pct": 0, "width_pct": 1, "height_pct": 1},
422
  ]
423
  ax = plt.subplots()[1] if supplied_axes else None
424
+ ax = _prediction(np.ones((32, 32)) * 1e-9).plot_flux_map(
425
+ ax=ax,
426
  show_harp_boxes=True, harp_regions=regions, min_harp_flux=0, harp_label_fontsize=10,
427
  )
428
  for size, dpi in [((7, 6), 100), ((4.2, 4.2), 150)]:
 
448
  {"HARPNUM": harpnum, "top_pct": 48, "left_pct": left, "width_pct": 1, "height_pct": 1}
449
  for harpnum, left in [(12345, 48), (23456, 50), (34567, 52)]
450
  ]
451
+ ax = _prediction(np.ones((64, 64)) * 1e-9).plot_flux_map(
452
+ show_harp_boxes=True,
453
  harp_regions=regions, harp_label_fontsize=12, min_harp_flux=0,
454
  harp_label_offsets={12345: (-100, 30), 23456: (0, -70), 34567: (100, 30)},
455
  )
 
473
  result = helio_foxes.Prediction(
474
  flux=1e-8, flux_map=np.array([[1e-9, 2e-9], [3e-9, 4e-9]]), harp_regions=regions,
475
  )
476
+ ax = result.plot_flux_map(show_harp_boxes=True, min_harp_flux=threshold)
477
  assert len(ax.patches) == visible
478
  assert len(ax.texts) == visible
479
  assert len(result.harp_regions) == 3
 
482
 
483
 
484
  @pytest.mark.parametrize("threshold", [-1, np.nan, np.inf])
485
+ def test_plot_rejects_invalid_harp_flux_threshold(monkeypatch, threshold):
486
+ monkeypatch.setattr(helio_foxes.HARPProcessor, "fetch", lambda *a, **kw: pytest.fail("Unexpected query"))
487
  with pytest.raises(ValueError, match="min_harp_flux must be finite and nonnegative"):
488
+ _prediction(np.ones((2, 2))).plot_flux_map(
489
+ show_harp_boxes=True, min_harp_flux=threshold,
 
490
  )
491
+
492
+
493
+ class _Response:
494
+ def __init__(self, payload):
495
+ self.payload, self.headers = payload, {"Content-Length": str(len(payload))}
496
+
497
+ def read(self, size):
498
+ chunk, self.payload = self.payload[:size], self.payload[size:]
499
+ return chunk
500
+
501
+ def __enter__(self):
502
+ return self
503
+
504
+ def __exit__(self, *exc):
505
+ return False
506
+
507
+
508
+ def test_named_checkpoint_downloads_once_into_cache(monkeypatch, tmp_path):
509
+ urls = []
510
+
511
+ def urlopen(url):
512
+ urls.append(url)
513
+ return _Response(b"weights")
514
+
515
+ monkeypatch.setattr("urllib.request.urlopen", urlopen)
516
+ monkeypatch.setenv("HELIO_FOXES_CACHE", str(tmp_path))
517
+ monkeypatch.chdir(tmp_path)
518
+ path = helio_foxes.api._resolve_checkpoint("uncertainty")
519
+ assert path == tmp_path / "UncertaintyModel.ckpt"
520
+ assert path.read_bytes() == b"weights"
521
+ assert helio_foxes.api._resolve_checkpoint("no-attention-mask").parent == tmp_path / "LegacyModels"
522
+ assert helio_foxes.api._resolve_checkpoint("uncertainty") == path
523
+ assert urls == [
524
+ helio_foxes.api._CHECKPOINT_URL + "UncertaintyModel.ckpt",
525
+ helio_foxes.api._CHECKPOINT_URL + "LegacyModels/no-attention-mask.ckpt",
526
+ ]
527
+
528
+
529
+ def test_checkpoint_paths_win_and_bad_downloads_leave_nothing(monkeypatch, tmp_path):
530
+ monkeypatch.setenv("HELIO_FOXES_CACHE", str(tmp_path / "cache"))
531
+ monkeypatch.chdir(tmp_path)
532
+ (tmp_path / "uncertainty").write_bytes(b"local")
533
+ assert helio_foxes.api._resolve_checkpoint("uncertainty") == tmp_path / "uncertainty"
534
+ (tmp_path / "uncertainty").unlink()
535
+ with pytest.raises(FileNotFoundError, match="released checkpoint name"):
536
+ helio_foxes.api._resolve_checkpoint("missing.ckpt")
537
+ monkeypatch.setattr("urllib.request.urlopen", lambda url: _Response(b"version https://git-lfs.github.com/spec/v1\n"))
538
+ with pytest.raises(RuntimeError, match="LFS pointer"):
539
+ helio_foxes.api._resolve_checkpoint("uncertainty")
540
+ assert not any((tmp_path / "cache").iterdir())
541
+
542
+
543
+ def test_jsoc_email_defaults_to_environment(monkeypatch):
544
+ monkeypatch.setenv("JSOC_EMAIL", "env@example.com")
545
+ fetcher = helio_foxes.ObservationFetcher()
546
+ assert fetcher.aia_processor.email == fetcher.harp_processor.email == "env@example.com"
547
+ assert helio_foxes.ObservationFetcher(email="given@example.com").aia_processor.email == "given@example.com"
548
+ monkeypatch.delenv("JSOC_EMAIL")
549
+ assert helio_foxes.HARPProcessor().email is None
tests/test_series_plot_filtering.py CHANGED
@@ -12,7 +12,7 @@ import helio_foxes as foxes
12
  def make_series():
13
  predictions = []
14
  for minute, values in enumerate(([0, 2e-7], [1e-6, 2e-7], [0, 2e-7])):
15
- metadata = foxes.ObservationMetadata(f"2023-08-01 00:0{minute}", (7, 2, 2))
16
  predictions.append(foxes.Prediction(
17
  metadata=metadata, flux=[0, 1e-6, 0][minute], flux_map=np.array([values]),
18
  patch_uncertainty_map=np.array([[2e-7, 3e-7]]),
@@ -23,12 +23,12 @@ def make_series():
23
  ],
24
  ))
25
  snapshot = foxes.Observation.from_array(np.ones((1, 2, 2)), timestamp="2023-08-01 00:01", wavelengths=(193,))
26
- return foxes.PredictionSeries(tuple(predictions), snapshot=snapshot)
27
 
28
 
29
  def test_log_lines_mask_nonpositive_values_and_preserve_data():
30
  series = make_series()
31
- ax = series.plot(include_full_disk=True, include_sxr=True)
32
  assert ax.get_yscale() == "log"
33
  assert np.diff(ax.get_xlim())[0] == pytest.approx(2 / (24 * 60))
34
  lines = {line.get_label(): line for line in ax.lines}
@@ -46,9 +46,9 @@ def test_log_lines_mask_nonpositive_values_and_preserve_data():
46
 
47
  def test_peak_threshold_filters_curves_and_snapshot_without_changing_colors():
48
  series = make_series()
49
- original = series.plot(show_uncertainty=False)
50
  color = original.lines[0].get_color()
51
- ax = series.plot(show_snapshot=True, min_peak_flux=5e-7)
52
  assert [line.get_label() for line in ax.lines] == ["HARP 100", "AIA snapshot"]
53
  assert ax.lines[0].get_color() == color
54
  assert len(ax.figure.axes[1].patches) == 1
@@ -64,22 +64,22 @@ def test_peak_threshold_is_over_entire_series_and_can_hide_all():
64
  series = make_series()
65
  # The last snapshot has zero HARP-100 flux, but its earlier peak qualifies.
66
  last_snapshot = foxes.Observation.from_array(np.ones((1, 2, 2)), timestamp="2023-08-01 00:02", wavelengths=(193,))
67
- series = foxes.PredictionSeries(series.predictions, snapshot=last_snapshot)
68
- ax = series.plot(show_snapshot=True, min_peak_flux=1e-6)
69
  assert any(line.get_label() == "HARP 100" for line in ax.lines)
70
  assert not ax.figure.axes[1].patches # Zero instantaneous flux is not labeled.
71
  plt.close(ax.figure)
72
- ax = series.plot(min_peak_flux=2e-6)
73
  assert not ax.lines and ax.get_legend() is None
74
  plt.close(ax.figure)
75
 
76
 
77
  def test_legend_overrides():
78
  series = make_series()
79
- ax = series.plot(show_snapshot=True, legend="full")
80
  assert "HARP 100" in [text.get_text() for text in ax.get_legend().texts]
81
  plt.close(ax.figure)
82
- ax = series.plot(legend="none")
83
  assert ax.get_legend() is None
84
  plt.close(ax.figure)
85
 
@@ -87,4 +87,4 @@ def test_legend_overrides():
87
  @pytest.mark.parametrize("threshold", [-1, np.nan, np.inf, None, "invalid"])
88
  def test_invalid_threshold(threshold):
89
  with pytest.raises(ValueError, match="min_peak_flux"):
90
- make_series().plot(min_peak_flux=threshold)
 
12
  def make_series():
13
  predictions = []
14
  for minute, values in enumerate(([0, 2e-7], [1e-6, 2e-7], [0, 2e-7])):
15
+ metadata = foxes.api.ObservationMetadata(f"2023-08-01 00:0{minute}", (7, 2, 2))
16
  predictions.append(foxes.Prediction(
17
  metadata=metadata, flux=[0, 1e-6, 0][minute], flux_map=np.array([values]),
18
  patch_uncertainty_map=np.array([[2e-7, 3e-7]]),
 
23
  ],
24
  ))
25
  snapshot = foxes.Observation.from_array(np.ones((1, 2, 2)), timestamp="2023-08-01 00:01", wavelengths=(193,))
26
+ return foxes.PredictionTimeSeries(tuple(predictions), snapshot=snapshot)
27
 
28
 
29
  def test_log_lines_mask_nonpositive_values_and_preserve_data():
30
  series = make_series()
31
+ ax = series.plot_light_curves(show_full_disk=True, show_observed=True)
32
  assert ax.get_yscale() == "log"
33
  assert np.diff(ax.get_xlim())[0] == pytest.approx(2 / (24 * 60))
34
  lines = {line.get_label(): line for line in ax.lines}
 
46
 
47
  def test_peak_threshold_filters_curves_and_snapshot_without_changing_colors():
48
  series = make_series()
49
+ original = series.plot_light_curves(show_uncertainty=False)
50
  color = original.lines[0].get_color()
51
+ ax = series.plot_light_curves(show_snapshot=True, min_peak_flux=5e-7)
52
  assert [line.get_label() for line in ax.lines] == ["HARP 100", "AIA snapshot"]
53
  assert ax.lines[0].get_color() == color
54
  assert len(ax.figure.axes[1].patches) == 1
 
64
  series = make_series()
65
  # The last snapshot has zero HARP-100 flux, but its earlier peak qualifies.
66
  last_snapshot = foxes.Observation.from_array(np.ones((1, 2, 2)), timestamp="2023-08-01 00:02", wavelengths=(193,))
67
+ series = foxes.PredictionTimeSeries(series.predictions, snapshot=last_snapshot)
68
+ ax = series.plot_light_curves(show_snapshot=True, min_peak_flux=1e-6)
69
  assert any(line.get_label() == "HARP 100" for line in ax.lines)
70
  assert not ax.figure.axes[1].patches # Zero instantaneous flux is not labeled.
71
  plt.close(ax.figure)
72
+ ax = series.plot_light_curves(min_peak_flux=2e-6)
73
  assert not ax.lines and ax.get_legend() is None
74
  plt.close(ax.figure)
75
 
76
 
77
  def test_legend_overrides():
78
  series = make_series()
79
+ ax = series.plot_light_curves(show_snapshot=True, legend="full")
80
  assert "HARP 100" in [text.get_text() for text in ax.get_legend().texts]
81
  plt.close(ax.figure)
82
+ ax = series.plot_light_curves(legend="none")
83
  assert ax.get_legend() is None
84
  plt.close(ax.figure)
85
 
 
87
  @pytest.mark.parametrize("threshold", [-1, np.nan, np.inf, None, "invalid"])
88
  def test_invalid_threshold(threshold):
89
  with pytest.raises(ValueError, match="min_peak_flux"):
90
+ make_series().plot_light_curves(min_peak_flux=threshold)
tests/test_series_snapshot.py CHANGED
@@ -46,7 +46,7 @@ def observations(minutes=(0, 4, 10)):
46
 
47
 
48
  def make_series(**kwargs):
49
- return foxes.Predictor.predict_series(SnapshotModel(), observations(), **kwargs)
50
 
51
 
52
  def test_target_retains_one_channel_without_temporary_files(monkeypatch):
@@ -60,7 +60,7 @@ def test_target_retains_one_channel_without_temporary_files(monkeypatch):
60
 
61
 
62
  def test_target_ties_choose_earlier_and_channel_can_be_changed():
63
- series = foxes.Predictor.predict_series(
64
  SnapshotModel(), observations((10, 4, 0)),
65
  snapshot_time="2023-08-01 00:07", snapshot_wavelength=171,
66
  )
@@ -76,9 +76,10 @@ def test_no_target_retains_no_image(monkeypatch):
76
 
77
 
78
  def test_empty_series_has_no_snapshot():
79
- series = foxes.Predictor.predict_series(
80
- SnapshotModel(), iter(()), snapshot_time="2023-08-01",
81
- )
 
82
  assert series.predictions == ()
83
  assert series.snapshot is None
84
 
@@ -92,15 +93,15 @@ def test_target_selects_nearest_available_observation(target, expected_minute):
92
 
93
  def test_snapshot_reuses_overlay_and_matches_colors(monkeypatch):
94
  series = make_series(snapshot_time="2023-08-01 00:05")
95
- original = foxes.api.plot_flux_map
96
  calls = []
97
 
98
  def plot(*args, **kwargs):
99
  calls.append(kwargs)
100
  return original(*args, **kwargs)
101
 
102
- monkeypatch.setattr("helio_foxes.api.plot_flux_map", plot)
103
- ax = series.plot(show_snapshot=True)
104
  assert len(calls) == 1
105
  snapshot_ax = ax.figure.axes[1]
106
  assert len(ax.figure.axes) == 4 # Curves, standard flux map, AIA, flux colorbar.
@@ -128,27 +129,27 @@ def test_snapshot_reuses_overlay_and_matches_colors(monkeypatch):
128
 
129
  def test_toggle_and_selected_regions_keep_colors_stable():
130
  series = make_series(snapshot_time="2023-08-01 00:05")
131
- plain_ax = series.plot()
132
  assert len(plain_ax.figure.axes) == 1
133
  color = next(line.get_color() for line in plain_ax.lines if line.get_label() == "HARP 200")
134
- ax = series.plot(show_snapshot=True, harpnums=[200])
135
  assert len(ax.figure.axes[1].patches) == 1
136
  assert ax.lines[0].get_color() == color
137
  assert ax.figure.axes[1].texts[0].get_text().startswith("#200")
138
  plt.close(plain_ax.figure)
139
  plt.close(ax.figure)
140
  with pytest.raises(ValueError, match="No AIA snapshot"):
141
- make_series().plot(show_snapshot=True)
142
 
143
 
144
  def test_existing_axes_and_no_snapshot_harps_do_not_query(monkeypatch):
145
  series = make_series(snapshot_time="2023-08-01 00:05")
146
- monkeypatch.setattr(foxes.HARPProcessor, "fetch_date", lambda *args: pytest.fail("No query"))
147
  fig, (left, right, aia) = plt.subplots(1, 3)
148
- assert series.plot(ax=left, snapshot_ax=right, aia_ax=aia, show_snapshot=True, harpnums=[]) is left
149
  assert not right.patches
150
  with pytest.raises(ValueError, match="snapshot_ax"):
151
- series.plot(ax=left, show_snapshot=True)
152
  plt.close(fig)
153
 
154
 
@@ -160,14 +161,14 @@ def test_failed_prediction_raises():
160
  return super().predict(observation)
161
 
162
  with pytest.raises(RuntimeError, match="model failure"):
163
- foxes.Predictor.predict_series(
164
  FailingModel(), observations(), snapshot_time="2023-08-01 00:05",
165
  )
166
 
167
 
168
  def test_snapshot_is_independent_of_source_and_input_order():
169
  source = list(observations((10, 4, 0)))
170
- series = foxes.Predictor.predict_series(SnapshotModel(), iter(source), snapshot_time="2023-08-01 00:05")
171
  expected = source[1].data[3].copy()
172
  source[1].data[:] = -99
173
  assert series.snapshot.metadata.timestamp.minute == 4
@@ -176,8 +177,8 @@ def test_snapshot_is_independent_of_source_and_input_order():
176
 
177
 
178
  def test_uncertainties_on_bands_and_snapshot_labels_and_toggle():
179
- series = foxes.Predictor.predict_series(UncertainSnapshotModel(), observations(), snapshot_time="2023-08-01 00:05")
180
- ax = series.plot(show_snapshot=True)
181
  assert len(ax.collections) == 2
182
  assert r"\sigma" in ax.get_title()
183
  assert all("±" in label.get_text() for label in ax.figure.axes[1].texts)
@@ -189,7 +190,7 @@ def test_uncertainties_on_bands_and_snapshot_labels_and_toggle():
189
  assert min(ys) == pytest.approx(flux - sigma)
190
  assert max(ys) == pytest.approx(flux + sigma)
191
  plt.close(ax.figure)
192
- ax = series.plot(show_snapshot=True, show_uncertainty=False)
193
  assert not ax.collections
194
  assert all("±" not in label.get_text() for label in ax.figure.axes[1].texts)
195
  plt.close(ax.figure)
@@ -197,7 +198,7 @@ def test_uncertainties_on_bands_and_snapshot_labels_and_toggle():
197
 
198
  def test_deterministic_model_never_fabricates_uncertainty():
199
  series = make_series(snapshot_time="2023-08-01 00:05")
200
- ax = series.plot(show_snapshot=True, show_uncertainty=True)
201
  assert not ax.collections
202
  assert all("±" not in label.get_text() for label in ax.figure.axes[1].texts)
203
  assert r"\sigma" not in ax.get_title()
@@ -208,9 +209,9 @@ def test_mixed_models_do_not_bridge_unknown_uncertainties():
208
  images = list(observations())
209
  uncertain = UncertainSnapshotModel()
210
  deterministic = SnapshotModel()
211
- series = foxes.PredictionSeries((uncertain.predict(images[0]), deterministic.predict(images[1]),
212
  uncertain.predict(images[2])))
213
- ax = series.plot()
214
  for collection in ax.collections:
215
  for path in collection.get_paths():
216
  # Isolated known uncertainties must not shade across the middle sample.
 
46
 
47
 
48
  def make_series(**kwargs):
49
+ return foxes.FOXESModel.predict_time_series(SnapshotModel(), observations(), **kwargs)
50
 
51
 
52
  def test_target_retains_one_channel_without_temporary_files(monkeypatch):
 
60
 
61
 
62
  def test_target_ties_choose_earlier_and_channel_can_be_changed():
63
+ series = foxes.FOXESModel.predict_time_series(
64
  SnapshotModel(), observations((10, 4, 0)),
65
  snapshot_time="2023-08-01 00:07", snapshot_wavelength=171,
66
  )
 
76
 
77
 
78
  def test_empty_series_has_no_snapshot():
79
+ with pytest.warns(UserWarning, match="can only be used once"):
80
+ series = foxes.FOXESModel.predict_time_series(
81
+ SnapshotModel(), iter(()), snapshot_time="2023-08-01",
82
+ )
83
  assert series.predictions == ()
84
  assert series.snapshot is None
85
 
 
93
 
94
  def test_snapshot_reuses_overlay_and_matches_colors(monkeypatch):
95
  series = make_series(snapshot_time="2023-08-01 00:05")
96
+ original = foxes.Prediction.plot_flux_map
97
  calls = []
98
 
99
  def plot(*args, **kwargs):
100
  calls.append(kwargs)
101
  return original(*args, **kwargs)
102
 
103
+ monkeypatch.setattr(foxes.Prediction, "plot_flux_map", plot)
104
+ ax = series.plot_light_curves(show_snapshot=True)
105
  assert len(calls) == 1
106
  snapshot_ax = ax.figure.axes[1]
107
  assert len(ax.figure.axes) == 4 # Curves, standard flux map, AIA, flux colorbar.
 
129
 
130
  def test_toggle_and_selected_regions_keep_colors_stable():
131
  series = make_series(snapshot_time="2023-08-01 00:05")
132
+ plain_ax = series.plot_light_curves()
133
  assert len(plain_ax.figure.axes) == 1
134
  color = next(line.get_color() for line in plain_ax.lines if line.get_label() == "HARP 200")
135
+ ax = series.plot_light_curves(show_snapshot=True, harpnums=[200])
136
  assert len(ax.figure.axes[1].patches) == 1
137
  assert ax.lines[0].get_color() == color
138
  assert ax.figure.axes[1].texts[0].get_text().startswith("#200")
139
  plt.close(plain_ax.figure)
140
  plt.close(ax.figure)
141
  with pytest.raises(ValueError, match="No AIA snapshot"):
142
+ make_series().plot_light_curves(show_snapshot=True)
143
 
144
 
145
  def test_existing_axes_and_no_snapshot_harps_do_not_query(monkeypatch):
146
  series = make_series(snapshot_time="2023-08-01 00:05")
147
+ monkeypatch.setattr(foxes.HARPProcessor, "fetch", lambda *args: pytest.fail("No query"))
148
  fig, (left, right, aia) = plt.subplots(1, 3)
149
+ assert series.plot_light_curves(ax=left, snapshot_ax=right, aia_ax=aia, show_snapshot=True, harpnums=[]) is left
150
  assert not right.patches
151
  with pytest.raises(ValueError, match="snapshot_ax"):
152
+ series.plot_light_curves(ax=left, show_snapshot=True)
153
  plt.close(fig)
154
 
155
 
 
161
  return super().predict(observation)
162
 
163
  with pytest.raises(RuntimeError, match="model failure"):
164
+ foxes.FOXESModel.predict_time_series(
165
  FailingModel(), observations(), snapshot_time="2023-08-01 00:05",
166
  )
167
 
168
 
169
  def test_snapshot_is_independent_of_source_and_input_order():
170
  source = list(observations((10, 4, 0)))
171
+ series = foxes.FOXESModel.predict_time_series(SnapshotModel(), iter(source), snapshot_time="2023-08-01 00:05")
172
  expected = source[1].data[3].copy()
173
  source[1].data[:] = -99
174
  assert series.snapshot.metadata.timestamp.minute == 4
 
177
 
178
 
179
  def test_uncertainties_on_bands_and_snapshot_labels_and_toggle():
180
+ series = foxes.FOXESModel.predict_time_series(UncertainSnapshotModel(), observations(), snapshot_time="2023-08-01 00:05")
181
+ ax = series.plot_light_curves(show_snapshot=True)
182
  assert len(ax.collections) == 2
183
  assert r"\sigma" in ax.get_title()
184
  assert all("±" in label.get_text() for label in ax.figure.axes[1].texts)
 
190
  assert min(ys) == pytest.approx(flux - sigma)
191
  assert max(ys) == pytest.approx(flux + sigma)
192
  plt.close(ax.figure)
193
+ ax = series.plot_light_curves(show_snapshot=True, show_uncertainty=False)
194
  assert not ax.collections
195
  assert all("±" not in label.get_text() for label in ax.figure.axes[1].texts)
196
  plt.close(ax.figure)
 
198
 
199
  def test_deterministic_model_never_fabricates_uncertainty():
200
  series = make_series(snapshot_time="2023-08-01 00:05")
201
+ ax = series.plot_light_curves(show_snapshot=True, show_uncertainty=True)
202
  assert not ax.collections
203
  assert all("±" not in label.get_text() for label in ax.figure.axes[1].texts)
204
  assert r"\sigma" not in ax.get_title()
 
209
  images = list(observations())
210
  uncertain = UncertainSnapshotModel()
211
  deterministic = SnapshotModel()
212
+ series = foxes.PredictionTimeSeries((uncertain.predict(images[0]), deterministic.predict(images[1]),
213
  uncertain.predict(images[2])))
214
+ ax = series.plot_light_curves()
215
  for collection in ax.collections:
216
  for path in collection.get_paths():
217
  # Isolated known uncertainties must not shade across the middle sample.
tests/test_sxr_api.py CHANGED
@@ -82,7 +82,7 @@ def test_sxr_real_netcdf_reader_quality_and_temporary_cleanup(monkeypatch):
82
  (18, dict(offsets=[-60, 0, 30, 60], b_quality=[0, 1, 1, 0],
83
  xrsb=[2e-6, 9e-6, 8e-6, 3e-6])),
84
  ])
85
- result = helio_foxes.SXRProcessor().fetch_date("2023-07-31T20:00:00-04:00")
86
  assert result["timestamp"] == datetime(2023, 7, 31, 23, 59, tzinfo=timezone.utc)
87
  assert result["time_offset_seconds"] == -60
88
  assert result["satellites"] == ["GOES-18"]
@@ -102,7 +102,7 @@ def test_sxr_averages_same_time_satellites_once_and_skips_bad_files(monkeypatch)
102
  (18, dict(offsets=[0], xrsb=[4e-6])), (17, None),
103
  (16, dict(offsets=[0])),
104
  ], errors=["another file unavailable"])
105
- result = helio_foxes.SXRProcessor().fetch_date(TARGET)
106
  assert result["satellites"] == ["GOES-18", "GOES-16"]
107
  assert result["xrsb_flux"] == pytest.approx(2.5e-6)
108
  assert [row["xrsb_flux"] for row in result["measurements"]] == [4e-6, 1e-6]
@@ -118,7 +118,7 @@ def test_sxr_averages_same_time_satellites_once_and_skips_bad_files(monkeypatch)
118
 
119
  def test_sxr_explicit_satellite_and_no_extra_legacy_scaling(monkeypatch):
120
  _, searches = mock_download(monkeypatch, [(15, dict(offsets=[0])), (18, dict(offsets=[0]))])
121
- result = helio_foxes.SXRProcessor(satellite=15).fetch_date("2023-08-01")
122
  assert result["satellites"] == ["GOES-15"]
123
  assert result["xrsa_flux"] == pytest.approx(1e-8)
124
  assert result["xrsb_flux"] == pytest.approx(1e-6)
@@ -132,7 +132,7 @@ def test_sxr_explicit_satellite_and_no_extra_legacy_scaling(monkeypatch):
132
  ])
133
  def test_sxr_returns_none_for_gaps_bad_quality_or_invalid_flux(monkeypatch, values):
134
  staged, _ = mock_download(monkeypatch, [(18, values)])
135
- assert helio_foxes.SXRProcessor().fetch_date(TARGET) is None
136
  assert all(not path.exists() for path in staged)
137
 
138
 
@@ -156,7 +156,7 @@ def test_sxr_bad_short_band_does_not_remove_valid_training_target(monkeypatch, s
156
  (16, dict(offsets=[0], xrsb=[1e-6], **short_values)),
157
  (18, dict(offsets=[0], xrsb=[4e-6], xrsa=[2e-8])),
158
  ])
159
- result = helio_foxes.SXRProcessor().fetch_date(TARGET)
160
  assert result["xrsb_flux"] == pytest.approx(2.5e-6)
161
  assert result["xrsa_flux"] == pytest.approx(2e-8)
162
  assert result["measurements"][1]["xrsa_flux"] is None
@@ -164,7 +164,7 @@ def test_sxr_bad_short_band_does_not_remove_valid_training_target(monkeypatch, s
164
 
165
  def test_sxr_all_short_band_data_bad_still_returns_long_band(monkeypatch):
166
  mock_download(monkeypatch, [(18, dict(offsets=[0], a_quality=[1]))])
167
- result = helio_foxes.SXRProcessor().fetch_date(TARGET)
168
  assert result["xrsa_flux"] is None
169
  assert result["xrsb_flux"] == pytest.approx(1e-6)
170
 
@@ -174,7 +174,7 @@ def test_sxr_never_averages_different_timestamps(monkeypatch):
174
  (16, dict(offsets=[0], xrsb=[1e-6])),
175
  (18, dict(offsets=[-30, 30], xrsb=[4e-6, 6e-6])),
176
  ])
177
- result = helio_foxes.SXRProcessor().fetch_date(TARGET)
178
  assert result["satellites"] == ["GOES-16"]
179
  assert result["xrsb_flux"] == pytest.approx(1e-6)
180
  assert result["time_offset_seconds"] == 0
@@ -182,13 +182,13 @@ def test_sxr_never_averages_different_timestamps(monkeypatch):
182
 
183
  def test_sxr_no_search_results_does_not_download(monkeypatch):
184
  staged, _ = mock_download(monkeypatch, [])
185
- assert helio_foxes.SXRProcessor().fetch_date(TARGET) is None
186
  assert staged == []
187
 
188
 
189
  def test_sxr_cleans_up_interrupted_download(monkeypatch):
190
  staged, _ = mock_download(monkeypatch, [(18, {})], fail_fetch=True)
191
- assert helio_foxes.SXRProcessor().fetch_date(TARGET) is None
192
  assert len(staged) == 1 and not staged[0].exists()
193
 
194
 
@@ -214,7 +214,7 @@ def test_sxr_missing_dependency_explains_active_environment_and_cleans_up(monkey
214
  else:
215
  monkeypatch.setattr("sunpy.timeseries.TimeSeries", missing)
216
 
217
- assert helio_foxes.SXRProcessor().fetch_date(TARGET) is None
218
  assert sys.executable in caplog.text
219
  assert "%pip install h5netcdf h5py" in caplog.text
220
  assert all(not directory.exists() for directory in staged)
@@ -231,4 +231,4 @@ def test_sxr_rejects_invalid_settings(kwargs):
231
 
232
  def test_sxr_bad_timestamp_is_caller_error():
233
  with pytest.raises(ValueError):
234
- helio_foxes.SXRProcessor().fetch_date("invalid datetime")
 
82
  (18, dict(offsets=[-60, 0, 30, 60], b_quality=[0, 1, 1, 0],
83
  xrsb=[2e-6, 9e-6, 8e-6, 3e-6])),
84
  ])
85
+ result = helio_foxes.SXRProcessor().fetch("2023-07-31T20:00:00-04:00")
86
  assert result["timestamp"] == datetime(2023, 7, 31, 23, 59, tzinfo=timezone.utc)
87
  assert result["time_offset_seconds"] == -60
88
  assert result["satellites"] == ["GOES-18"]
 
102
  (18, dict(offsets=[0], xrsb=[4e-6])), (17, None),
103
  (16, dict(offsets=[0])),
104
  ], errors=["another file unavailable"])
105
+ result = helio_foxes.SXRProcessor().fetch(TARGET)
106
  assert result["satellites"] == ["GOES-18", "GOES-16"]
107
  assert result["xrsb_flux"] == pytest.approx(2.5e-6)
108
  assert [row["xrsb_flux"] for row in result["measurements"]] == [4e-6, 1e-6]
 
118
 
119
  def test_sxr_explicit_satellite_and_no_extra_legacy_scaling(monkeypatch):
120
  _, searches = mock_download(monkeypatch, [(15, dict(offsets=[0])), (18, dict(offsets=[0]))])
121
+ result = helio_foxes.SXRProcessor(satellite=15).fetch("2023-08-01")
122
  assert result["satellites"] == ["GOES-15"]
123
  assert result["xrsa_flux"] == pytest.approx(1e-8)
124
  assert result["xrsb_flux"] == pytest.approx(1e-6)
 
132
  ])
133
  def test_sxr_returns_none_for_gaps_bad_quality_or_invalid_flux(monkeypatch, values):
134
  staged, _ = mock_download(monkeypatch, [(18, values)])
135
+ assert helio_foxes.SXRProcessor().fetch(TARGET) is None
136
  assert all(not path.exists() for path in staged)
137
 
138
 
 
156
  (16, dict(offsets=[0], xrsb=[1e-6], **short_values)),
157
  (18, dict(offsets=[0], xrsb=[4e-6], xrsa=[2e-8])),
158
  ])
159
+ result = helio_foxes.SXRProcessor().fetch(TARGET)
160
  assert result["xrsb_flux"] == pytest.approx(2.5e-6)
161
  assert result["xrsa_flux"] == pytest.approx(2e-8)
162
  assert result["measurements"][1]["xrsa_flux"] is None
 
164
 
165
  def test_sxr_all_short_band_data_bad_still_returns_long_band(monkeypatch):
166
  mock_download(monkeypatch, [(18, dict(offsets=[0], a_quality=[1]))])
167
+ result = helio_foxes.SXRProcessor().fetch(TARGET)
168
  assert result["xrsa_flux"] is None
169
  assert result["xrsb_flux"] == pytest.approx(1e-6)
170
 
 
174
  (16, dict(offsets=[0], xrsb=[1e-6])),
175
  (18, dict(offsets=[-30, 30], xrsb=[4e-6, 6e-6])),
176
  ])
177
+ result = helio_foxes.SXRProcessor().fetch(TARGET)
178
  assert result["satellites"] == ["GOES-16"]
179
  assert result["xrsb_flux"] == pytest.approx(1e-6)
180
  assert result["time_offset_seconds"] == 0
 
182
 
183
  def test_sxr_no_search_results_does_not_download(monkeypatch):
184
  staged, _ = mock_download(monkeypatch, [])
185
+ assert helio_foxes.SXRProcessor().fetch(TARGET) is None
186
  assert staged == []
187
 
188
 
189
  def test_sxr_cleans_up_interrupted_download(monkeypatch):
190
  staged, _ = mock_download(monkeypatch, [(18, {})], fail_fetch=True)
191
+ assert helio_foxes.SXRProcessor().fetch(TARGET) is None
192
  assert len(staged) == 1 and not staged[0].exists()
193
 
194
 
 
214
  else:
215
  monkeypatch.setattr("sunpy.timeseries.TimeSeries", missing)
216
 
217
+ assert helio_foxes.SXRProcessor().fetch(TARGET) is None
218
  assert sys.executable in caplog.text
219
  assert "%pip install h5netcdf h5py" in caplog.text
220
  assert all(not directory.exists() for directory in staged)
 
231
 
232
  def test_sxr_bad_timestamp_is_caller_error():
233
  with pytest.raises(ValueError):
234
+ helio_foxes.SXRProcessor().fetch("invalid datetime")
tutorials/heliofoxes_demo/heliofoxes.ipynb CHANGED
The diff for this file is too large to render. See raw diff