Metadata-Version: 2.5
Name: nrlx
Version: 0.3.0b1
Summary: NRL eXtended: tools for building and validating seismic instrument responses.
Project-URL: Homepage, https://github.com/vishnurajsreerajnair/nrlx
Project-URL: Repository, https://github.com/vishnurajsreerajnair/nrlx
Project-URL: Issues, https://github.com/vishnurajsreerajnair/nrlx/issues
Author-email: Vishnuraj Sreeraj Nair <vishnurajsreeraj@yahoo.com>
License-Expression: MIT
License-File: LICENSE
Keywords: NRL,ObsPy,RESP,StationXML,instrument response,nominal response library,seismology
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: msgspec>=0.18
Requires-Dist: obspy>=1.4
Requires-Dist: platformdirs>=4.0
Requires-Dist: rich>=13.0
Requires-Dist: typer>=0.19
Provides-Extra: dev
Requires-Dist: black>=24.0; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: plot
Requires-Dist: matplotlib>=3.8; extra == 'plot'
Description-Content-Type: text/markdown

# nrlx

[![PyPI](https://img.shields.io/pypi/v/nrlx)](https://pypi.org/project/nrlx/)
[![Python versions](https://img.shields.io/pypi/pyversions/nrlx)](https://pypi.org/project/nrlx/)
[![CI](https://github.com/vishnurajsreerajnair/nrlx/actions/workflows/ci.yml/badge.svg)](https://github.com/vishnurajsreerajnair/nrlx/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

**NRL eXtended** — a Python CLI and library for browsing EarthScope/IRIS's Nominal
Response Library (NRL v2) and building seismic instrument responses.

## Quickstart

How it works, in short: `nrlx` keeps one local copy of IRIS's NRL catalog on your
disk, you describe your instrument with a few keys, and `nrlx` asks IRIS to build
the actual response. One command finds and writes:

```bash
pip install nrlx

nrlx sync                                   # download the catalog and its code table (first run and refreshes)

nrlx response --sensor luni,tellus          # what matches, and what still varies
nrlx response --sensor luni,tellus,LP=1 \
  --datalogger centaur,FR=100,FV=40Vpp,DF=Off,FP=Linear \
  --network XY --station TST --location 00 --channels HHZ,HHN,HHE \
  -o station.xml                            # a real StationXML file

nrlx doctor station.xml                     # check it, and compare it with the NRL
```

Without `-o`, `nrlx response` only shows: the matches of each part and the
parameters that still vary between them. Add keys until each part matches one
configuration, then add `-o FILE`. Not sure where to start? `nrlx response -i`
asks the parts step by step, writes the file and prints the same command line.

That `station.xml` is a real FDSN StationXML file built by IRIS's own service:
load it anywhere that reads StationXML, including
`obspy.read_inventory("station.xml")`.

## Install

```bash
pip install nrlx          # the stable release, 0.2.1
pip install --pre nrlx    # the 0.3.0b1 beta, with the commands below
```

This README describes 0.3.0b1. nrlx needs Python 3.11 or later, and installs
`obspy` with it: the responses it builds are obspy objects in memory (see
[Python library](#python-library)).

## Concepts

- **Catalog**: IRIS's tree of every nominal response, organized as `element`
  (sensor, datalogger, integrated, soh) → `manufacturer` → `model` →
  `configuration`.
- **instconfig**: the exact identifier of one configuration, e.g.
  `sensor_Streckeisen_STS-2_EG3_SG1500_LP120_STgroundVel`. Its parts after the
  model are two-letter codes and values (`SG1500` is a sensitivity of 1500 V/m/s);
  `nrlx prefixes` decodes them. It is what nrlx sends to IRIS; the keys exist to
  find it.
- **Local cache**: nrlx keeps one copy of the catalog and of its code table on
  disk (under your platform cache dir), so finding is instant and offline. `nrlx
  sync` refreshes both.

## Commands

| Command | What it does |
| --- | --- |
| `nrlx status [--live]` | Show version and local cache info; `--live` also checks the service. |
| `nrlx sync` | Download the current NRL catalog and code table into the local cache. |
| `nrlx prefixes [query]` | Decode the two-letter parameter codes of the instconfigs (LP, FR, FV, ...). |
| `nrlx response` | Find configurations by keys, and write their response (StationXML, RESP or SACPZ). |
| `nrlx convert <file> -o <out>` | Convert a response file to StationXML, RESP or SACPZ, read back and checked. |
| `nrlx assets add\|list\|get\|deprecate\|delete\|export\|import` | Keep the responses you build, by UID and versioned, in a database you can share. |
| `nrlx local sync\|status\|remove` | Keep a local copy of the whole NRL, for `nrlx response --source local`. |
| `nrlx doctor <file>` | Check each channel of a response file (amplitude, units and rates, poles, codes) and compare it with its NRL nominal. |

Run `nrlx <command> --help` for the full option list.

### Finding: keys

`nrlx response` without arguments shows the catalog: each manufacturer of each
element with its counts. Bare keys (`nrlx response sts-2`, `--element sensor` to
narrow) explore every element; the parts `--sensor`, `--datalogger`,
`--integrated` and `--soh` are what `-o` writes. A sensor, a datalogger or both;
an integrated instrument or a state of health channel alone.

The keys of a part are comma-separated or repeated, in any order. Each is:

- a **word**: a manufacturer (`luni`), a model, a part of the instconfig (`LP1`,
  `Q330HR_PG1`), a parameter value (`'400 V/m/s'`), or the exact instconfig. A
  whole name or part wins over the start of one, which wins over a text found
  inside: `LP1` keeps the LP1 configuration, not LP10 and LP120. A note says when
  a word matched only the start of a name or inside a text;
- a **condition** `name<op>value` with `=`, `<`, `>`, `<=`, `>=`, or a range
  `FR=100..500`, `FR=100..`, `FR=..200` (shell-safe, no quotes). The name is a
  code (`FR`, `LP`) or the start of a word of a parameter name (`corner>=60`);
  numbers are compared as numbers, so `FR=40` is 40 Hz, not 400 Hz.

What you see depends on how many configurations match: more than 20 are grouped
by model, with the parameters that still vary in each; up to 20 are listed one
per row; one is shown in full, with every parameter. When nothing matches, nrlx
says which key leaves no configuration, and suggests the nearest names or the
values there.

### Writing: channels, format, labels

```bash
nrlx response --sensor streckeisen,STS-2,EG3,SG=1500 \
  --datalogger Q330HR_PG1,FR=40,ADHR,LRbelow100 \
  --network XY --station MYSTN --location 00 --channels BHZ,BHN,BHE \
  --starttime 2021-01-01 \
  --latitude 49.096 --longitude 8.432 --elevation 112 \
  -o station.xml
```

- The format comes from the extension: `.xml` for StationXML, `.resp` for RESP,
  `.pz` for SACPZ; `--format stationxml|resp|sacpz` overrides it. The RESP writer
  keeps 16 significant digits.
- `--channels` are written as given, all in one file; `--split` writes one file
  per channel, named by its SEED id (`station_XY.MYSTN.00.BHZ.xml`). A channel
  code whose band letter does not fit the sample rate (SEED norm) gets a one-line
  note, never an error.
- The service builds the response once; nrlx copies it for each channel and sets
  the network, station, location, times (`--starttime`, `--endtime`, UTC) and the
  place (`--latitude`, `--longitude` in degrees; `--elevation` and `--depth` in
  metres, 0 unless given). The labels not given keep the service placeholders.
- A response nrlx does not combine itself (the service's, or a part alone from
  the local copy) is written as received, with a note when it contradicts itself:
  a normalization factor that does not give its stage's gain (12 % of the NRL
  sensors), or a stated sensitivity its stages do not give (more than 0.1 %).

### Your own sensor or datalogger

```bash
nrlx response --sensor-file my_sensor.xml#XX.SENS..HHZ \
  --datalogger centaur,FR=100,FV=40Vpp,DF=Off,FP=Linear \
  --network XY --station TST --channels HHZ -o station.xml
```

- `--sensor-file` and `--datalogger-file` take the part from any file obspy
  reads (StationXML, RESP, dataless SEED), in place of `--sensor` or
  `--datalogger`; `FILE#NET.STA.LOC.CHA` picks a channel of a file with several.
  The file can hold the part alone or a whole channel: the sensor is taken up to
  its voltage output, the datalogger from its voltage input.
- The other part comes from the NRL by keys as usual (or from a file too), and
  nrlx combines the two itself: it chains the units at the voltage, corrects the
  normalization factors that contradict their gains, and computes the overall
  sensitivity as obspy does. Notes say what was filled or corrected.
- `-i` asks the NRL parts only, so it does not take a file.

### Offline: the local NRL

```bash
nrlx local sync          # the whole NRL: about 300 MB to download, 2.8 GB on disk
nrlx response --sensor luni,tellus,LP=1 \
  --datalogger centaur,FR=100,FV=40Vpp,DF=Off,FP=Linear --source local -o st.xml
nrlx local status        # folder, files, size, date
nrlx local remove        # asks first (--yes to skip); the catalog stays
```

- `nrlx local sync` downloads the catalog, the code table and the zip of the
  whole NRL from the service, unzips it in the cache (`<cache>/nrl/NRL`, the
  layout of the zip, which obspy's NRL client also opens) and checks that every
  configuration of the catalog has its file. The three replace the previous ones
  together; a failure keeps the previous copy.
- `--source local` builds without any request: a part alone is its file, a
  sensor and a datalogger are combined by nrlx (as with `--sensor-file`). With
  `--source service` (the default) the service combines the NRL parts.

### Converting a file

```bash
nrlx convert station.dataless -o station.xml       # every channel, one file
nrlx convert station.xml -o station.resp --split   # one file per channel
nrlx convert "station.xml#XY.MYSTN.00.BHZ" -o bhz.pz
```

- The input is any file obspy reads: StationXML, RESP, dataless SEED, XSEED,
  SC3ML. The output is StationXML, RESP or SACPZ, from the extension (`.xml`,
  `.resp`, `.pz`) or `--format`.
- The file written is read back and compared with the input. StationXML and RESP
  must give the same curve (within 1e-9) or the command fails, keeping the file
  to look at. When evalresp cannot compute the curve of the input (no stages, a
  polynomial of more than 3 coefficients), a note says it is not checked.
- The channels a format cannot hold are skipped, with a note that lists them by
  reason; when none is left, it is an error. Every format needs a response; RESP
  also needs a stage, a sensitivity or a polynomial, and no stage numbered 0
  (RESP keeps 0 for the sensitivity of the channel). A file without channels is
  an error.
- SACPZ keeps only the first poles and zeros stage and the overall sensitivity;
  a note says how far that is from the whole response (an STS-2 on a Q330 at
  40 sps: within 4.9 % up to 3.6 Hz, 28.9 % at 16 Hz). Channels SACPZ cannot hold
  (no analog poles and zeros, or an input other than m, m/s or m/s**2) are
  skipped with the note, where obspy would skip them silently.
- The SACPZ constant is A0 × the overall sensitivity, as rdseed, IRIS and obspy
  write it. That holds only when A0 normalizes the poles and zeros at the
  frequency of the sensitivity, so nrlx normalizes them there first: a geophone
  normalized at 100 Hz on a 1 sps channel, whose sensitivity is at 0.1 Hz, gets
  a SACPZ within 0.02 % of its response instead of 100 % off.
- A RESP file has no sample rate: obspy takes it from the decimation and rounds
  it to an integer, so a channel below 0.5 sps reads 0. nrlx takes the exact
  rate of the last decimation, for `convert`, `assets add` and the file parts.
- nrlx reads dataless SEED but never writes it. Beware of dataless files written
  by obspy (`Parser.write_seed`, obspy 1.5): a SEED blockette holds at most 9999
  bytes, and obspy writes a longer one, such as a FIR of more than about 415
  coefficients, without splitting it, so the file is corrupt from that stage on.
  15 of 46 random NRL builds have such a FIR; obspy then reads the channel with
  no response, and `nrlx convert` skips it with a note ("no response"), or fails
  when no channel is left. Use StationXML or RESP to move those responses.

### Assets: the responses you keep

```bash
nrlx response --sensor streckeisen,STS-2,EG3,SG=1500 \
  --datalogger Q330HR_PG1,FR=40,ADHR,LRbelow100 \
  --network XY --station T13 --channels HHZ,HHN,HHE -o t13.xml --add-asset
nrlx assets list                          # every version, with its variant
nrlx assets get T13 FR=40 -o t13.resp     # the latest in use that the keys pick
nrlx assets add calibrated.xml --uid EB696
nrlx assets deprecate T13 --version 1     # --undo puts it back
nrlx assets export share/                 # share/T13/v1.xml ... + manifest.json
nrlx assets import share/                 # or another .sqlite
```

- An asset is a StationXML file as built, stored whole under a UID: the station
  code by default, `--uid` for another (a serial number follows the unit from
  station to station). `--add-asset` works with or without `-o`.
- The versions of a UID are numbered in one sequence. A response the UID already
  has is not added again (a note on `nrlx response`, an error on `assets add`).
- `get` picks the latest version in use whose NRL parts match the keys of
  `nrlx response` (`STS-2`, `FR=40`), and `rate=` and `units=` on the file; when
  the keys leave several variants it lists them. `--version N` gets any version,
  deprecated or not. The file written is read back and checked, as by `convert`.
- `nrlx response` writes a comment on each StationXML channel with the
  instconfigs it was built from (`built by nrlx 0.3.0b1 (service): sensor=... datalogger=...`, or `(local)`),
  so the NRL keys also pick the files added later with `assets add`.
- The database is `assets.sqlite` in the cache folder (`--db` for another).
  `nrlx local remove` never touches it, but deleting the cache folder by hand
  does: export it to keep a copy. To share, export and import rather than
  writing to one database on a network drive, where SQLite's locking is not
  reliable.

### Checking a file

```bash
nrlx doctor station.xml                       # a file nrlx built: compared with its NRL parts
nrlx doctor vendor.resp --sensor STS-2,SG=1500 --datalogger Q330,FR=100
nrlx doctor "station.xml#XY.MYSTN.00.BHZ" --all
nrlx doctor station.pz                        # SACPZ: poles, constant, codes
```

- Any file obspy reads (StationXML, RESP, dataless SEED, XSEED, SC3ML), or SACPZ.
  A table gives each channel ok, or its warnings and errors, in five groups;
  below it a line per warning or error (`--all`: every check). An error exits 1.
- **amplitude**: the stated sensitivity against what its stages give by the
  rules of evalresp (an error beyond 1 %: `remove_response` and
  `remove_sensitivity` would disagree), and warnings for a normalization factor
  that does not give its stage gain, a sensitivity at or above Nyquist or out of
  the sensor's flat band, a FIR whose coefficients do not sum to 1.
- A channel that is not a sensor (instrument code such as LOG, OCF, a
  temperature or a mass position) without a sensitivity or a response is an
  info, not an error; a sensor without one is an error.
- **chains**: stages numbered 1 to N, units that follow from stage to stage and
  end in counts (a stage with only a gain, which has no units in StationXML,
  passes them through; COUNT and COUNTS are the same), decimations that chain
  and end at the channel's rate (a break in the rate chain is a warning, as
  evalresp takes each stage at its own rate).
- **poles**: an analog pole with a positive real part, or a digital one outside
  the unit circle, is an error: the amplitude is the same, but the phase is
  wrong. On the whole NRL v2 this finds 18 sensor files with poles of the wrong
  sign and 448 datalogger files with an analog filter typed as a Z transform.
- **codes**: the band code for the sample rate and the instrument code for the
  input units (SEED norm), warnings.
- **nominal**: the channel against the NRL nominal of its parts, from the
  provenance comment of a StationXML built by nrlx, or from `--sensor`,
  `--datalogger`, `--integrated` for any other file. A different input unit,
  rate or sensor poles and zeros is an error; amplitude beyond 1 % or phase
  beyond 1 degree a warning (a calibration can explain it), with the stages that
  differ. The nominal comes from the source of the comment (`--source` to
  change; service by default), one request per distinct nominal;
  `--no-nominal` skips it. Without a synced catalog the other checks still run.
- A file obspy cannot read is an error, with obspy's reason.

## Python library

Everything the CLI does is a thin layer over the `nrlx` package:

```python
from pathlib import Path

from nrlx import Nrlx, write_resp
from nrlx.io.inventory import read_part

nrl = Nrlx.from_cache()                      # the catalog and code table on disk
# nrl = Nrlx.sync()                          # or download fresh ones first

# Find: the rows carry their parents, with what still varies
found = nrl.find(["luni", "tellus"], "sensor")
for element, manufacturer, model, configuration in found.rows:
    print(model.name, configuration.instconfig, configuration.parameters)
print(found.varying)                         # {"Long-Period_Corner": ["1 s", ...], ...}

# Build: each part resolves to one configuration, then one request
inventory, notes = nrl.response(
    sensor=["luni", "tellus", "LP=1"],
    datalogger=["centaur", "FR=100", "FV=40Vpp", "DF=Off", "FP=Linear"],
    network="XY", station="TST", location="00", channels=["HHZ", "HHN", "HHE"],
    latitude=45.6, longitude=8.9,
)

# Your own sensor (any file obspy reads) with an NRL datalogger, combined by nrlx;
# the notes say what it filled or corrected
sensor = read_part(Path("my_sensor.xml"), "XX.SENS..HHZ")
inventory, notes = nrl.response(
    sensor_response=sensor,
    datalogger=["centaur", "FR=100", "FV=40Vpp", "DF=Off", "FP=Linear"],
    channels=["HHZ"],
)

inventory.write("station.xml", format="STATIONXML")   # an obspy Inventory
text = write_resp(inventory)                          # RESP, which obspy cannot write

# Assets: the same database as the CLI (Nrlx.from_cache(assets_db=...) for another)
row = nrl.assets.add(inventory, uid="EB696")          # UID: the station by default
inventory = nrl.assets.get("EB696", ["FR=100"])       # or version=2
for row in nrl.assets.list():
    print(row.uid, row.version, row.sample_rate, row.deprecated)
```

nrlx raises built-in exceptions: `LookupError` when a part matches no
configuration or several (the message lists the hints or what still varies),
`ValueError` for an invalid request or catalog, `FileNotFoundError` when the
cache has not been synced, and `httpx.HTTPError` when the service cannot be
reached. Each part resolves before any request, so a wrong selection fails
offline.

## Status

Working end to end against the live NRL v2 service (0.3.0b1 beta on PyPI, 0.2.1
the stable release; 0.1.0 was an early skeleton, yanked): finding by keys and
conditions, sensor and datalogger combination (also with your own sensor or
datalogger files),
StationXML, RESP and SACPZ writing with any channel codes, a local copy of the
NRL to build offline, conversion between formats, assets, and `doctor` with
physical checks and the comparison with the NRL nominal. Planned next: finding
the NRL parts of a file that does not say them (reverse lookup). See
[CHANGELOG.md](CHANGELOG.md) for details.

## Note for developers

This is pre-1.0 and the public API (both CLI flags and the Python classes) can
still change between releases. The package is organized in layers, each
importing only the ones below it:

| Layer | Holds |
| --- | --- |
| `nrlx/schema/` | msgspec structs of every input: the NRL service JSON (`catalog`, `prefixes`), the cache files, and the request `response`, with its validation |
| `nrlx/models/` | the structs with their methods (`Catalog`, `Found`, `Assets`), plus `Nrlx` |
| `nrlx/core/` | pure functions on plain values: matching, SEED band codes, `/combine` parameters, the combination of responses, the amplitudes of the stages, the conversion checks, doctor checks |
| `nrlx/io/` | the NRL service (httpx), the local cache and the local NRL, the assets database (SQLite) and its exports, obspy reading, labelling and writing, the RESP writer, the SACPZ reader |
| `nrlx/tools/cmd/` | the `nrlx` commands, the only code that prints and exits |

Library code raises built-in exceptions, and each command catches the ones it
can get. [CLAUDE.md](CLAUDE.md) lists the code conventions.

Not yet: nrlx does not read SACPZ as an input to convert or build (obspy
cannot; `nrlx doctor` reads it with its own reader). Issues and PRs welcome.

## Disclaimer

This project is not affiliated with EarthScope, IRIS, or the official Nominal Response Library.
NRL data remains owned/maintained by its respective providers.
