Metadata-Version: 2.4
Name: maser-tools
Version: 0.5.0
Summary: Tools to handle some file formats supported in maser-data package
Keywords: maser,data science,radioastronomy
Author: MASER team
Author-email: MASER team <contact.maser@obspm.fr>
License-Expression: CECILL-B
License-File: LICENSE
Requires-Dist: numpy>=2.0
Requires-Dist: spacepy>=0.7,<1.0
Requires-Dist: openpyxl>=3.1,<4
Requires-Dist: pytz>=2022.4
Requires-Dist: pandas>=2.2.2
Requires-Dist: requests>=2.27
Requires-Dist: netcdf4>=1.6 ; extra == 'netcdf'
Requires-Python: >=3.10
Project-URL: Homepage, https://pypi.org/project/maser-tools
Project-URL: Repository, https://gitlab.obspm.fr/maser/maser-tools
Project-URL: Documentation, https://maser.pages.obspm.fr/maser4py/
Provides-Extra: netcdf
Description-Content-Type: text/markdown

# About maser-tools

maser-tools is part of the [MASER](https://maser.obspm.fr) Python libraries, with
[maser4py](https://pypi.org/project/maser4py/), maser-data and maser-plot.
It offers programs to support radio data format (e.g., CDF) and time
(e.g. leap seconds and time conversion handling):

- `maser.tools.cdf.serializer`: conversions between master binary CDF (.cdf),
  skeleton table (.skt) and Excel (.xlsx) files, as follows:

  ```
  Excel (.xlsx) <--> binary CDF (.cdf) <--> skeleton table (.skt)
  ```

- `maser.tools.cdf.cdfcompare`: comparison of two CDF files
- `maser.tools.cdf.cdfinfo`: display of the metadata of a CDF file
- `maser.tools.cdf.validator`: validation of a CDF file against a model (e.g. ISTP)
- `maser.tools.cdf.bin`: Python port of the programs of the
  [NASA CDF distribution](https://cdf.gsfc.nasa.gov/html/sw_and_docs.html)
  (`cdfdump`, `cdfvalidate`, `skeletontable`, `cdfconvert`...), see
  [Python port of the NASA CDF programs](#python-port-of-the-nasa-cdf-programs)
- `maser.tools.time`: leap seconds and time conversions (UTC, TT2000, Julian days)

Read [main documentation](https://maser.pages.obspm.fr/maser4py/) for details.

# Installation

To install the package, run the following command:

```bash
pip install maser-tools
```

or, with [uv](https://docs.astral.sh/uv/):

```bash
uv add maser-tools        # in a uv project
uv tool install maser-tools  # to only use the maser-tools and cdfinfo commands
```

## Requirements

- Python 3.10 or later
- The CDF files are read and written with [spacepy.pycdf](https://spacepy.github.io/pycdf.html),
  which relies on the [NASA CDF library](https://cdf.gsfc.nasa.gov/html/sw_and_docs.html)
  (see [spacepy installation](https://spacepy.github.io/install.html) if it is not found).
- The conversions between binary CDF and skeleton table call the `skeletoncdf` and
  `skeletontable` programs of the [NASA CDF software](https://cdf.gsfc.nasa.gov/html/sw_and_docs.html).
  They are searched in the `$CDF_BIN` directory, then in the `$PATH`.

# Usage

## Command line interface

The programs can be run from a terminal with the `maser-tools` command
(or `python -m maser.tools`):

```bash
maser-tools --help
maser-tools skeletoncdf --help
```

Available sub-commands are:

| Sub-command     | Description                                                          |
|-----------------|----------------------------------------------------------------------|
| `skeletoncdf`   | Convert skeleton table (.skt) or Excel (.xlsx) files into binary CDF |
| `skeletontable` | Convert binary CDF files into skeleton tables (and Excel files)      |
| `leapsec`       | Leap seconds handling tool                                           |
| `cdf_compare`   | Compare two CDF files                                                |
| `cdf_validator` | Validate a CDF file                                                  |

The metadata of a CDF file (options, global and variable attributes) can be
displayed with the `cdfinfo` command:

```bash
cdfinfo my_file.cdf
cdfinfo --no-option --no-variable --gattrs Project Mission_group -- my_file.cdf
cdfinfo --csv my_file.cdf > my_file.csv  # or --asciidoc for an AsciiDoc table
```

For instance, to make a master CDF from an Excel file, then save it back as
a skeleton table and an Excel file in the `build` folder:

```bash
maser-tools skeletoncdf -o build my_master.xlsx
maser-tools skeletontable --to-xlsx -o build/skt build/my_master.cdf
```

An example of Excel file is provided in
`src/maser/tools/support/cdf/converter_example.xlsx`.

## Python

```python
from maser.tools.cdf.serializer import xlsx2cdf, cdf2xlsx

cdf_file = xlsx2cdf("my_master.xlsx", output_dir="build", overwrite=True)
xlsx_file = cdf2xlsx("build/my_master.cdf", output_dir="build", overwrite=True)
```

## Python port of the NASA CDF programs

The `maser.tools.cdf.bin` package is a Python port of the programs of the `bin`
directory of the [NASA CDF distribution](https://cdf.gsfc.nasa.gov/html/sw_and_docs.html)
(version 3.9.2), written from their C source code
([cdf_dist-all.tar.gz](https://spdf.gsfc.nasa.gov/pub/software/cdf/dist/cdf39_2/)).
The CDF files are read and written with the NASA CDF C library (through
`spacepy.pycdf`), with the same library calls as the original programs, so their
behaviour is the same: same qualifiers, same messages, same output text and same
produced files. Unlike the original programs, their functions can also be imported
and called from a Python program.

| Module (`maser.tools.cdf.bin.`) | NASA CDF program     | Description                                                    |
|---------------------------------|----------------------|----------------------------------------------------------------|
| `cdfcompare`                    | `cdfcompare`         | Compare two CDF files                                          |
| `cdfconvert`                    | `cdfconvert`         | Convert a CDF (format, majority, encoding, compression...)     |
| `cdfdir`                        | `cdfdir`             | List the files of a (single or multi-file) CDF                 |
| `cdfdump`                       | `cdfdump`            | Dump the metadata and data of a CDF                            |
| `cdfedit`                       | `cdfedit`            | Interactive (full-screen) CDF editor/browser                   |
| `cdfexport`                     | `cdfexport`          | Export CDF data to a text file or another CDF                  |
| `cdfinquire`                    | `cdfinquire`         | Display the version and the defaults of the CDF distribution   |
| `cdfirsdump`                    | `cdfirsdump`         | Dump the internal records of a CDF file                        |
| `cdfleapsecondsinfo`            | `cdfleapsecondsinfo` | Display the leap seconds table used by the CDF library         |
| `cdfmerge`                      | `cdfmerge`           | Merge several CDF files                                        |
| `cdfstats`                      | `cdfstats`           | Statistics on the variables of a CDF (min/max, fill values...) |
| `cdfvalidate`                   | `cdfvalidate`        | Check the integrity of CDF files                               |
| `skeletoncdf`                   | `skeletoncdf`        | Make a CDF from a skeleton table (.skt)                        |
| `skeletontable`                 | `skeletontable`      | Make a skeleton table (.skt) from a CDF                        |
| `cdf_to_netcdf`                 | `cdf-to-netCDF`      | Convert a CDF into a netCDF file                               |
| `netcdf_to_cdf`                 | `netCDF-to-cdf`      | Convert a netCDF file into a CDF                               |

The netCDF converters need the `netCDF4` package: install maser-tools with its
`netcdf` extra (`pip install "maser-tools[netcdf]"`).

### Command line

Each module is run with `python -m`, with exactly the same qualifiers as the original
program. Without argument, the online help of the program is displayed:

```bash
python -m maser.tools.cdf.bin.cdfvalidate -debug my_file.cdf
python -m maser.tools.cdf.bin.cdfdump -dump data -vars "Epoch,B" -recordrange 1,10 my_file.cdf
python -m maser.tools.cdf.bin.skeletontable -values all -skeleton my_file my_file.cdf
python -m maser.tools.cdf.bin.skeletoncdf -delete -cdf my_master my_file.skt
python -m maser.tools.cdf.bin.cdfconvert -compression "cdf:gzip.6" -column in.cdf out.cdf
python -m maser.tools.cdf.bin.cdf_to_netcdf -o my_file.nc my_file.cdf
python -m maser.tools.cdf.bin.cdfdump
```

The exit status is the one of the original program.

### Python

Each module provides a function with the name of the program, whose keyword
arguments correspond to the qualifiers, and a `main(argv=None)` function running the
command line interface (it returns the exit status):

```python
from maser.tools.cdf.bin.cdfvalidate import cdfvalidate, validate_cdf
from maser.tools.cdf.bin.cdfdump import cdfdump_text
from maser.tools.cdf.bin.skeletontable import skeletontable
from maser.tools.cdf.bin.skeletoncdf import skeletoncdf
from maser.tools.cdf.bin.cdfcompare import cdfcompare
from maser.tools.cdf.bin.cdfedit import CDFEditor

# True if the file is valid (the messages are displayed as by cdfvalidate)
ok = cdfvalidate("my_file.cdf", quiet=True)
# or, without any message: CDF status and list of the errors
status, errors = validate_cdf("my_file.cdf")

# cdfdump output as a string
text = cdfdump_text("my_file.cdf", dump="metadata")

# CDF <-> skeleton table
skeletontable("my_file.cdf", skeleton="my_file.skt", values="all")
skeletoncdf("my_file.skt", cdf="my_master.cdf", delete=True)

# True if differences have been found
diff = cdfcompare("file1.cdf", "file2.cdf", value=True)

# cdfedit operations, without the full-screen interface
with CDFEditor("my_file.cdf") as editor:
    editor.rename_variable("B", "B_GSE")
    editor.set_compression("GZIP.6")

# The command line interface
from maser.tools.cdf.bin import cdfstats

status = cdfstats.main(["-output", "stats.txt", "my_file.cdf"])
```

See the docstring of each module for its functions and the list of their arguments
(e.g. `python -c "import maser.tools.cdf.bin.cdfdump as m; help(m)"`).

### Differences with the original programs

The Python versions aim at reproducing the original programs byte for byte. The
reference is the macOS (arm64) binary distribution of the NASA CDF software 3.9.2: they
were checked against its executables on real CDF files
(Solar Orbiter RPW data) and on synthetic files covering the CDF features (data types,
compressions, sparse records, majorities, encodings, multi-file CDFs...). The known
differences are documented in the docstring of each module. The main ones are:

- the online help is never paged (no "Enter RETURN for more..." pause);
- the cases where the C program crashes or uses uninitialized memory are handled
  without crash, with a defined result;
- `cdfedit` and `cdfexport` (interactive mode) end with an error when the standard
  input/output is not a terminal, instead of waiting forever;
- on other platforms, the programs built from the source code of the CDF distribution
  can differ in some details (the sources differ a bit from the macOS binaries, and
  the C code has platform dependent undefined behaviours);
- the netCDF files written by `cdf_to_netcdf` have the same content as the ones of
  `cdf-to-netCDF`, but they are not byte-identical when the version of the netCDF/HDF5
  libraries differs.

Note: when they find no mapping file in the current directory (and no `-map` option
is given), the netCDF converters use the same hard-coded mapping as the original
programs. The mapping files of the CDF distribution are provided in the package
(`maser.tools.cdf.bin.cdf_to_netcdf.MAPPING_FILE` and
`maser.tools.cdf.bin.netcdf_to_cdf.MAPPING_FILE`) and can be given with `-map`.

# Development

To contribute to the development of the package, clone the repository:

```bash
git clone https://gitlab.obspm.fr/maser/maser-tools.git
cd maser-tools
```

The project is managed with [uv](https://docs.astral.sh/uv/getting-started/installation/).
Its requirements are detailed in the `pyproject.toml` file, and pinned in the `uv.lock` file.

## Installing a local copy of maser-tools

Run the following command to create the virtual environment (`.venv`) and install
the package (in editable mode) with its development dependencies:

```bash
uv sync
```

Then run the programs from this environment with `uv run`, e.g.:

```bash
uv run maser-tools --help
```

The binary files (e.g. Excel files) are stored with [Git LFS](https://git-lfs.com):
run `git lfs install` once before cloning the repository.

## Code quality

The code is linted and formatted with [ruff](https://docs.astral.sh/ruff/), through
[pre-commit](https://pre-commit.com) hooks. Install them once with:

```bash
uv run pre-commit install
```

They can also be run on all the files with:

```bash
uv run pre-commit run --all-files
```

## Tests

Run the tests with:

```bash
uv run pytest
```

The tests calling the programs of the NASA CDF software (`skeletoncdf`, `skeletontable`,
and the comparisons of the `maser.tools.cdf.bin` modules with the original programs)
are skipped when the programs are not found. They are searched in the `$CDF_BIN`
directory, then in the `$PATH`. The comparisons of the `maser.tools.cdf.bin` modules
with the original programs are only done on macOS, the reference platform (set the
`CDF_BIN_COMPARE` environment variable to 1 or 0 to force or disable them), e.g.:

```bash
CDF_BIN=/Applications/cdf/cdf39_2-dist/bin uv run pytest
```

## Continuous integration

The GitLab CI pipeline runs the tests with the minimum and latest supported Python
versions. It is not run on push: start it from the GitLab web interface
(Build > Pipelines > Run pipeline), or with the [glab](https://gitlab.com/gitlab-org/cli) CLI:

```bash
glab ci run -b develop
```

## Publish `maser-tools` on PyPI

maser-tools is published on PyPI by the GitLab CI pipeline, once the tests have
passed, for a tag on the `main` branch. The tag must be the version of
`pyproject.toml`, with or without a `v` prefix:

```bash
uv version 0.4.0  # update the version in pyproject.toml and uv.lock
git commit -am "Release 0.4.0"
git checkout main && git merge develop
git tag v0.4.0
git push origin main v0.4.0
```

The PyPI API token must be defined in the masked and protected `UV_PUBLISH_TOKEN`
CI/CD variable of the GitLab project (the tags must then be protected).

# License

maser-tools is distributed under the [CeCILL-B](https://cecill.info/licences/Licence_CeCILL-B_V1-en.html)
free software license (see the `LICENSE` file).
