Metadata-Version: 2.5
Name: speasy
Version: 1.10.0
Summary: A simple Python package to deal with main Space Physics WebServices (CDA, CSA, AMDA and SSC).
Project-URL: homepage, https://github.com/SciQLop/speasy
Author-email: Alexis Jeandet <alexis.jeandet@member.fsf.org>
Maintainer-email: Alexis Jeandet <alexis.jeandet@member.fsf.org>
License: MIT License
        
        Copyright (c) 2024 Laboratory of Plasma Physics, Ecole Polytechnique, CNRS, Sorbonne Université, Université Paris-Saclay
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
License-File: AUTHORS.rst
License-File: LICENSE
Keywords: CDF,amda,cdpp,nasa-data,plasma-physics,satellite
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.10
Requires-Dist: appdirs
Requires-Dist: astropy
Requires-Dist: cefast>=0.2.2
Requires-Dist: certifi
Requires-Dist: cyclopts>=4.25
Requires-Dist: diskcache
Requires-Dist: humanize
Requires-Dist: matplotlib
Requires-Dist: msgspec; sys_platform != 'emscripten'
Requires-Dist: numcodecs; sys_platform != 'emscripten'
Requires-Dist: numpy
Requires-Dist: packaging
Requires-Dist: pandas
Requires-Dist: pycdfpp>=0.17.0
Requires-Dist: pyistp>=0.9.3
Requires-Dist: pysciqlop-cache<0.5,>=0.4.2; sys_platform != 'emscripten'
Requires-Dist: pysocks
Requires-Dist: python-dateutil
Requires-Dist: pyyaml
Requires-Dist: requests
Requires-Dist: scipy
Requires-Dist: tqdm
Requires-Dist: urllib3>=1.26.0
Provides-Extra: blosc
Provides-Extra: xarray
Requires-Dist: xarray; extra == 'xarray'
Provides-Extra: zstd
Requires-Dist: pyzstd; extra == 'zstd'
Description-Content-Type: text/markdown

<h1 align="center">
<img src="https://raw.githubusercontent.com/SciQLop/speasy/main/logo/logo_speasy.svg" width="300">
</h1>

<p align="center"><b>Space Physics made EASY: one function for in-situ space physics data.</b></p>

<p align="center">
<a href="https://pypi.org/project/speasy"><img src="https://img.shields.io/pypi/v/speasy.svg" alt="PyPI"></a>
<a href="https://github.com/SciQLop/speasy/actions?query=workflow%3A%22Tests%22"><img src="https://github.com/SciQLop/speasy/workflows/Tests/badge.svg" alt="Tests"></a>
<a href="https://speasy.readthedocs.io/en/latest/?badge=latest"><img src="https://readthedocs.org/projects/speasy/badge/?version=latest" alt="Documentation"></a>
<a href="https://doi.org/10.5281/zenodo.4118780"><img src="https://zenodo.org/badge/DOI/10.5281/zenodo.4118780.svg" alt="DOI"></a>
<a href="https://matrix.to/#/#speasy:matrix.org"><img src="https://img.shields.io/matrix/speasy:matrix.org" alt="Chat on Matrix"></a>
<a href="https://mybinder.org/v2/gh/SciQLop/speasy/main?labpath=docs/examples"><img src="https://mybinder.org/badge_logo.svg" alt="Try on MyBinder"></a>
</p>

<!--[[[cog
# This file is the source: everything below between a cog marker comment and its matching end
# marker is generated by running `make readme` (cogapp, https://cog.readthedocs.io), which
# executes the Python shown in the visible fenced code blocks for real (live network calls to
# AMDA/CDA/SSC/HAPI) and writes its actual output back in place. Never hand-edit a generated region;
# edit the run("""...""") source strings below instead and regenerate. `make readme-check`
# verifies in CI that this file matches what regenerating it would produce.
import os
import tempfile
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

README_IMG_DIR = os.path.abspath("README_files")
README_RAW_BASE_URL = "https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main"

def run(code):
    print(f"```python\n{code.strip()}\n```")
    exec(compile(code, "<readme>", "exec"), globals())

def run_in_tmp_dir(code):
    # Examples that create folders run in a throwaway directory, so `make readme` leaves no files behind.
    cwd = os.getcwd()
    with tempfile.TemporaryDirectory() as tmp:
        os.chdir(tmp)
        try:
            run(code)
        finally:
            os.chdir(cwd)

def save_and_show(name, alt):
    plt.savefig(os.path.join(README_IMG_DIR, name), bbox_inches="tight")
    plt.close("all")
    print(f"![{alt}]({README_RAW_BASE_URL}/README_files/{name})")
]]]-->
<!--[[[end]]]-->

<!--[[[cog
run("""
import speasy as spz
ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")
ace_mag.plot();
""")
save_and_show("ace_mag.png", "ACE interplanetary magnetic field")
]]]-->
```python
import speasy as spz
ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")
ace_mag.plot();
```
![ACE interplanetary magnetic field](https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main/README_files/ace_mag.png)
<!--[[[end]]]-->

That's it. Three lines, and you have three days of ACE magnetic field data, with time, units and labels.
The same call works for tens of thousands of products from many data centers.

![Many data sources, one get_data(product, start, stop) call, one SpeasyVariable that converts to numpy, pandas, xarray and astropy](https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main/docs/_static/overview.svg)

## Why Speasy

- **One call for many archives.** [AMDA](https://amda.cdpp.eu/), [CDAWeb](https://cdaweb.gsfc.nasa.gov/),
  ESA's [Cluster Science Archive](https://csa.esac.esa.int/csa-web/), [SSCWeb](https://sscweb.gsfc.nasa.gov/),
  [CDPP 3DView](http://3dview.cdpp.eu/), the U. Iowa ephemeris tool, every server of the
  [HAPI](https://hapi-server.org/) server list, and your own archives described in a YAML file.
  See the [data providers page](https://speasy.readthedocs.io/en/latest/user/data_providers.html).
- **Find data by tab-completion.** Browse `spz.inventories.tree.<provider>` in IPython or Jupyter, down to each product.
- **Fast on the second request.** Data is cached on your disk, and a community cache server speeds up the first one.
- **Reproducible studies.** A [`DataIndex`](https://speasy.readthedocs.io/en/latest/user/data_index.html) keeps exactly
  the data a study used. It never expires, works offline, and exports as a single file to share with a colleague.
- **Fits the tools you already use.** Numpy functions work directly on Speasy variables, and they convert to
  pandas, xarray and astropy.
- **Your own products.** Register a Python function as a
  [virtual product](https://speasy.readthedocs.io/en/latest/user/virtual_products.html), and use it like any other product.
- **Also from the shell, and from Julia.** A [`speasy` command](https://speasy.readthedocs.io/en/latest/user/cli.html)
  downloads, converts and pre-fetches data. [Speasy.jl](https://github.com/SciQLop/Speasy.jl) brings the same API to Julia.

Prefer clicking to coding? [SciQLop](https://github.com/SciQLop/SciQLop) is a graphical interface built on Speasy.

## Installation

Speasy needs **Python 3.10 or newer**:

```console
$ python -m pip install speasy
```

Or try the command line without installing anything, with [uv](https://docs.astral.sh/uv/):

```console
$ uvx speasy get amda/imf 2018-06-01 2018-06-02
```

The first request for some data needs internet access; after that, it comes from the local cache.
Behind a proxy or a firewall? See the [configuration page](https://speasy.readthedocs.io/en/latest/user/configuration.html).

## Examples

### Browse instead of typing ids

Every provider is a tree you can explore with tab-completion. This is the same product as above:

<!--[[[cog
run("""
import speasy as spz
amda_tree = spz.inventories.data_tree.amda
ace_mag = spz.get_data(amda_tree.Parameters.ACE.MFI.ace_imf_all.imf, "2016-6-2", "2016-6-5")
""")
]]]-->
```python
import speasy as spz
amda_tree = spz.inventories.data_tree.amda
ace_mag = spz.get_data(amda_tree.Parameters.ACE.MFI.ace_imf_all.imf, "2016-6-2", "2016-6-5")
```
<!--[[[end]]]-->

### Any HAPI server

The Dst index during the May 2024 geomagnetic storm, from the World Data Center in Kyoto:

<!--[[[cog
run("""
import speasy as spz
dst = spz.get_data("hapi/wdc_kyoto_hapi/hour_dst/dstValue", "2024-05-09", "2024-05-14")
dst.plot();
""")
save_and_show("dst_may_2024.png", "Dst index, May 2024 storm")
]]]-->
```python
import speasy as spz
dst = spz.get_data("hapi/wdc_kyoto_hapi/hour_dst/dstValue", "2024-05-09", "2024-05-14")
dst.plot();
```
![Dst index, May 2024 storm](https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main/README_files/dst_may_2024.png)
<!--[[[end]]]-->

### Several instruments on one figure

Magnetic field, electron and ion data from MMS1, on a shared time axis:

<!--[[[cog
run("""
import speasy as spz
import matplotlib.pyplot as plt

mms1 = spz.inventories.tree.cda.MMS.MMS1
fig = plt.figure(figsize=(8, 16), layout="constrained")
axes = fig.add_gridspec(6, hspace=0).subplots(sharex=True)

plots = [
    (mms1.FGM.MMS1_FGM_SRVY_L2.mms1_fgm_b_gse_srvy_l2_clean, axes[0]),
    (mms1.SCM.MMS1_SCM_SRVY_L2_SCSRVY.mms1_scm_acb_gse_scsrvy_srvy_l2, axes[1]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_bulkv_gse_fast, axes[2]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_temppara_fast, axes[3]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_tempperp_fast, axes[3]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_energyspectr_omni_fast, axes[4]),
    (mms1.DIS.MMS1_FPI_FAST_L2_DIS_MOMS.mms1_dis_energyspectr_omni_fast, axes[5]),
]

for product, ax in plots:
    spz.get_data(product, "2019-01-02T15", "2019-01-02T22").replace_fillval_by_nan().plot(ax=ax)
""")
save_and_show("mms1_multi_timeseries.png", "MMS1 multiple time series")
]]]-->
```python
import speasy as spz
import matplotlib.pyplot as plt

mms1 = spz.inventories.tree.cda.MMS.MMS1
fig = plt.figure(figsize=(8, 16), layout="constrained")
axes = fig.add_gridspec(6, hspace=0).subplots(sharex=True)

plots = [
    (mms1.FGM.MMS1_FGM_SRVY_L2.mms1_fgm_b_gse_srvy_l2_clean, axes[0]),
    (mms1.SCM.MMS1_SCM_SRVY_L2_SCSRVY.mms1_scm_acb_gse_scsrvy_srvy_l2, axes[1]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_bulkv_gse_fast, axes[2]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_temppara_fast, axes[3]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_tempperp_fast, axes[3]),
    (mms1.DES.MMS1_FPI_FAST_L2_DES_MOMS.mms1_des_energyspectr_omni_fast, axes[4]),
    (mms1.DIS.MMS1_FPI_FAST_L2_DIS_MOMS.mms1_dis_energyspectr_omni_fast, axes[5]),
]

for product, ax in plots:
    spz.get_data(product, "2019-01-02T15", "2019-01-02T22").replace_fillval_by_nan().plot(ax=ax)
```
![MMS1 multiple time series](https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main/README_files/mms1_multi_timeseries.png)
<!--[[[end]]]-->

### Many products, many intervals, one call

The result holds one list per product, with one variable per interval:

<!--[[[cog
run("""
import speasy as spz
products = [
    spz.inventories.tree.amda.Parameters.Wind.SWE.wnd_swe_kp.wnd_swe_vth,
    spz.inventories.tree.amda.Parameters.Wind.SWE.wnd_swe_kp.wnd_swe_pdyn,
    spz.inventories.tree.amda.Parameters.Wind.SWE.wnd_swe_kp.wnd_swe_n,
    spz.inventories.tree.cda.Wind.WIND.MFI.WI_H2_MFI.BGSE,
    spz.inventories.tree.ssc.Trajectories.wind,
]
intervals = [["2010-01-02", "2010-01-02T10"], ["2009-08-02", "2009-08-02T10"]]
data = spz.get_data(products, intervals)
""")
]]]-->
```python
import speasy as spz
products = [
    spz.inventories.tree.amda.Parameters.Wind.SWE.wnd_swe_kp.wnd_swe_vth,
    spz.inventories.tree.amda.Parameters.Wind.SWE.wnd_swe_kp.wnd_swe_pdyn,
    spz.inventories.tree.amda.Parameters.Wind.SWE.wnd_swe_kp.wnd_swe_n,
    spz.inventories.tree.cda.Wind.WIND.MFI.WI_H2_MFI.BGSE,
    spz.inventories.tree.ssc.Trajectories.wind,
]
intervals = [["2010-01-02", "2010-01-02T10"], ["2009-08-02", "2009-08-02T10"]]
data = spz.get_data(products, intervals)
```
<!--[[[end]]]-->

### Numpy works directly

Compute the field magnitude yourself, and check it against the one MMS provides:

<!--[[[cog
run("""
import speasy as spz
import numpy as np
mms1 = spz.inventories.tree.cda.MMS.MMS1
b = spz.get_data(mms1.FGM.MMS1_FGM_SRVY_L2.mms1_fgm_b_gsm_srvy_l2, "2017-01-01T02:00:00", "2017-01-01T02:00:15")
b.replace_fillval_by_nan(inplace=True)
bt = b["Bt"]
b = b["Bx GSM", "By GSM", "Bz GSM"]
computed_norm = np.sqrt(np.sum(b ** 2, axis=1))
print(f"Type of computed_norm: {type(computed_norm)}")
print("Same as the provided magnitude?", bool(np.allclose(computed_norm, bt)))
""")
]]]-->
```python
import speasy as spz
import numpy as np
mms1 = spz.inventories.tree.cda.MMS.MMS1
b = spz.get_data(mms1.FGM.MMS1_FGM_SRVY_L2.mms1_fgm_b_gsm_srvy_l2, "2017-01-01T02:00:00", "2017-01-01T02:00:15")
b.replace_fillval_by_nan(inplace=True)
bt = b["Bt"]
b = b["Bx GSM", "By GSM", "Bz GSM"]
computed_norm = np.sqrt(np.sum(b ** 2, axis=1))
print(f"Type of computed_norm: {type(computed_norm)}")
print("Same as the provided magnitude?", bool(np.allclose(computed_norm, bt)))
```
Type of computed_norm: <class 'speasy.products.variable.SpeasyVariable'>
Same as the provided magnitude? True
<!--[[[end]]]-->

### Convert to pandas, xarray or astropy

<!--[[[cog
run("""
import speasy as spz
ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")
print(type(ace_mag.to_dataframe()).__name__)
print(type(ace_mag.to_dataarray()).__name__)
print(type(ace_mag.to_astropy_table()).__name__)
""")
]]]-->
```python
import speasy as spz
ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")
print(type(ace_mag.to_dataframe()).__name__)
print(type(ace_mag.to_dataarray()).__name__)
print(type(ace_mag.to_astropy_table()).__name__)
```
DataFrame
DataArray
Table
<!--[[[end]]]-->

### Resample one product onto another

Interpolate ion temperatures onto the magnetic field timestamps:

<!--[[[cog
run("""
import speasy as spz
from speasy.signal.resampling import interpolate
import matplotlib.pyplot as plt
mms1 = spz.inventories.tree.cda.MMS.MMS1

b, Tperp, Tpara = spz.get_data(
    [
        mms1.FGM.MMS1_FGM_SRVY_L2.mms1_fgm_b_gsm_srvy_l2,
        mms1.DIS.MMS1_FPI_FAST_L2_DIS_MOMS.mms1_dis_tempperp_fast,
        mms1.DIS.MMS1_FPI_FAST_L2_DIS_MOMS.mms1_dis_temppara_fast,
    ],
    "2017-01-01T02:00:00",
    "2017-01-01T02:00:15",
)

Tperp_interp, Tpara_interp = interpolate(b, [Tperp, Tpara])

plt.figure()
ax = b.plot()
plt.plot(Tperp_interp.time, Tperp_interp.values, marker="+")
plt.plot(Tpara_interp.time, Tpara_interp.values, marker="+")
plt.tight_layout()
""")
save_and_show("resampling.png", "Resampling")
]]]-->
```python
import speasy as spz
from speasy.signal.resampling import interpolate
import matplotlib.pyplot as plt
mms1 = spz.inventories.tree.cda.MMS.MMS1

b, Tperp, Tpara = spz.get_data(
    [
        mms1.FGM.MMS1_FGM_SRVY_L2.mms1_fgm_b_gsm_srvy_l2,
        mms1.DIS.MMS1_FPI_FAST_L2_DIS_MOMS.mms1_dis_tempperp_fast,
        mms1.DIS.MMS1_FPI_FAST_L2_DIS_MOMS.mms1_dis_temppara_fast,
    ],
    "2017-01-01T02:00:00",
    "2017-01-01T02:00:15",
)

Tperp_interp, Tpara_interp = interpolate(b, [Tperp, Tpara])

plt.figure()
ax = b.plot()
plt.plot(Tperp_interp.time, Tperp_interp.values, marker="+")
plt.plot(Tpara_interp.time, Tpara_interp.values, marker="+")
plt.tight_layout()
```
![Resampling](https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main/README_files/resampling.png)
<!--[[[end]]]-->

### Your own products

A virtual product is a Python function that Speasy serves like any other product:

<!--[[[cog
run("""
import numpy as np
import speasy as spz
from speasy.virtual_products import register_virtual_product

@register_virtual_product("virtual/ace/b_magnitude", meta={"units": "nT"}, labels=["|B|"])
def ace_b_magnitude(start, stop):
    b = spz.get_data("amda/imf", start, stop)
    return np.sqrt(np.sum(b ** 2, axis=1))

spz.get_data("virtual/ace/b_magnitude", "2016-6-2", "2016-6-5").plot();
""")
save_and_show("virtual_product.png", "ACE field magnitude, from a virtual product")
]]]-->
```python
import numpy as np
import speasy as spz
from speasy.virtual_products import register_virtual_product

@register_virtual_product("virtual/ace/b_magnitude", meta={"units": "nT"}, labels=["|B|"])
def ace_b_magnitude(start, stop):
    b = spz.get_data("amda/imf", start, stop)
    return np.sqrt(np.sum(b ** 2, axis=1))

spz.get_data("virtual/ace/b_magnitude", "2016-6-2", "2016-6-5").plot();
```
![ACE field magnitude, from a virtual product](https://raw.githubusercontent.com/SciQLop/speasy/refs/heads/main/README_files/virtual_product.png)
<!--[[[end]]]-->

### Keep a study's data

Inside a `DataIndex` block, `get_data` stores what it downloads in a folder.
Next time, the same calls are served from that folder, even offline.
Export it as one file, and a colleague gets exactly the same data:

<!--[[[cog
run_in_tmp_dir("""
import speasy as spz

with spz.DataIndex("my_study") as study:
    ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")  # downloaded, kept in my_study/
study.export_data("my_study.tar")                                # one file to send

# On your colleague's machine:
with spz.DataIndex("their_copy") as copy:
    copy.import_data("my_study.tar")
    ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")  # read from their_copy/, no download
""")
]]]-->
```python
import speasy as spz

with spz.DataIndex("my_study") as study:
    ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")  # downloaded, kept in my_study/
study.export_data("my_study.tar")                                # one file to send

# On your colleague's machine:
with spz.DataIndex("their_copy") as copy:
    copy.import_data("my_study.tar")
    ace_mag = spz.get_data("amda/imf", "2016-6-2", "2016-6-5")  # read from their_copy/, no download
```
<!--[[[end]]]-->

## Documentation

The [documentation](https://speasy.readthedocs.io/en/latest/) covers each data provider, configuration,
the command line, and has a gallery of [examples](https://speasy.readthedocs.io/en/latest/examples/index.html).
Speasy's plots are meant for quick looks; for publication figures, use Matplotlib directly,
or [SciQLop](https://github.com/SciQLop/SciQLop) for interactive exploration.

## Help us improve Speasy

- Tell us how you use Speasy in our [user survey](https://docs.google.com/forms/d/e/1FAIpQLScV12kvETk8jc4Zc4sIsHiteMHRVo5I8DiSAE8RyVdVkUaxJA/viewform?usp=sf_link).
- Report bugs or request features in the [issues](https://github.com/SciQLop/speasy/issues/new).
- Ask questions in the [discussions](https://github.com/SciQLop/speasy/discussions) or on [Matrix](https://matrix.to/#/#speasy:matrix.org).
- Want to add a data provider? See the [contributing guide](https://github.com/SciQLop/speasy/blob/main/CONTRIBUTING.rst).

## Citing Speasy

If Speasy helped your research, please cite it. GitHub's "Cite this repository" button, on the right of this page,
gives a ready-made reference from [CITATION.cff](CITATION.cff). Every release also has a
[Zenodo DOI](https://doi.org/10.5281/zenodo.4118780).

## Thanks

Speasy only exists thanks to the data centers and teams who produce, archive and serve the data,
and to the HAPI community for a shared standard.
The development of Speasy is supported by the [CDPP](http://www.cdpp.eu/).
