Usage of torchMWRT#

torchMWRT is a PyTorch translation of the radiative-transfer calculation core of PyRTlib. Its results agree with PyRTlib within numerical tolerances for the tested configurations. Calculations are vectorized over frequencies, angles, height levels and leading dimensions such as time or location. This can provide substantial speedups for batches of profiles. It also supports GPU acceleration and automatic differentiation, although differentiation through radiative transfer is not required for the standard retrieval workflow.

The following example calculates brightness temperatures for one profile and then a batch. The displayed figures, tables and timings illustrate a Munich example with R24. Rerun the cells for other profiles.

%config InlineBackend.figure_format = 'svg'

import numpy as np
import xarray as xr
import time
import matplotlib.pyplot as plt

from torchMWRT import AtmProfile, RTModel

FREQS = np.array([22.24,23.04,23.84,25.44,26.24,27.84,31.40,51.26,52.28,53.86,54.94,56.66,57.30,58.00])
ANGLES = np.array([90.0], dtype=float)

PROJECT_DIR = '.'

Load the prepared profiles from Create a Retrieval. Run this notebook from the working project. The standalone RT calculation below selects R24 explicitly. It does not read simulation.toml.

ds = xr.load_dataset(f"{PROJECT_DIR}/data/sites/my_site/profiles/03715.nc")[['T', 'p', 'rh', 'lwc']]
ds
<xarray.Dataset> Size: 150MB
Dimensions:  (synop: 22540, height: 208)
Coordinates:
  * synop    (synop) datetime64[ns] 180kB 1990-01-01 ... 2026-10-24
  * height   (height) int64 2kB 0 10 25 50 75 ... 28000 28500 29000 29500 30000
Data variables:
    T        (synop, height) float64 38MB 267.1 267.1 267.1 ... 221.0 221.3
    p        (synop, height) float64 38MB 963.2 962.0 960.2 ... 11.23 10.39
    rh       (synop, height) float64 38MB 96.6 95.27 93.27 93.82 ... 1.0 1.0 1.0
    lwc      (synop, height) float64 38MB 0.0 0.007414 0.01853 ... 0.0 0.0 0.0
Attributes:
    station_id:      03715
    station_name:    Oberschleißheim (Lustheim)
    station_height:  484
    station_lat:     48.2446
    station_lon:     11.5525

Run torchMWRT for a Single Profile#

ds_date = ds.isel(synop= -1)

fig, axs = plt.subplots(ncols=3, sharey=True, figsize=(8, 4), constrained_layout=True)

ds_date['T'].sel(height=slice(0,10000)).plot(y='height', ax=axs[0])
ds_date['rh'].sel(height=slice(0,10000)).plot(y='height', ax=axs[1])
ds_date['lwc'].sel(height=slice(0,10000)).plot(y='height', ax=axs[2])

for i, ax in enumerate(axs):
    ax.set_ylabel("" if i > 0 else "Height [m]")
    ax.set_title('')
fig.suptitle('Single Radiosonde Profile')

plt.show()

ds_date
../_images/bcfd121a10fb234840a4b8de66aab57583e50f19f133e191ca84725e2263b407.svg
<xarray.Dataset> Size: 8kB
Dimensions:  (height: 208)
Coordinates:
  * height   (height) int64 2kB 0 10 25 50 75 ... 28000 28500 29000 29500 30000
    synop    datetime64[ns] 8B 2026-10-24
Data variables:
    T        (height) float64 2kB 282.3 282.4 282.6 282.6 ... 219.9 221.0 221.3
    p        (height) float64 2kB 959.0 957.8 956.1 953.2 ... 12.13 11.23 10.39
    rh       (height) float64 2kB 64.0 64.0 63.6 62.0 62.91 ... 1.0 1.0 1.0 1.0
    lwc      (height) float64 2kB 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0
Attributes:
    station_id:      03715
    station_name:    Oberschleißheim (Lustheim)
    station_height:  484
    station_lat:     48.2446
    station_lon:     11.5525

The first step is to create an instance of the RTModel class, which owns the radiative transfer code. In the initialization, all the settings are defined, such as the frequencies and angles for which the calculations should be performed, the absorption model to use, whether to simulate measurements from the surface or from a satellite.

rtmodel = RTModel(freqs=FREQS, angles=ANGLES, absmdl="R24", ray_tracing=True)

The next step is to create an AtmProfile object, which holds the atmospheric profile data. The AtmProfile class is designed to be flexible and can handle different input types, like numpy arrays, xarray DataArrays, or PyTorch tensors. The only requirement is that they all share the same height dimension / coordinate. To run a clear sky simulation just omit the lwc and the iwc variables.

atm_profile = AtmProfile(
    temperature=ds_date["T"],
    height=ds_date["height"] + ds_date.surface_altitude,
    pressure=ds_date["p"],
    rh=ds_date["rh"] / 100.0,
    lwc=ds_date["lwc"],
)

Finally, the execute method of the RTModel instance is called to perform the radiative transfer calculations. The results can be returned as an xarray Dataset.

For gradients, use PyTorch tensor inputs with requires_grad=True and keep return_ds=False. The tensor output retains the computation graph. Converting to xarray detaches it. Finite-difference checks cover selected R24 and R17 configurations.

result_ds = rtmodel.execute(atm_profile, return_ds=True)
result_ds["tbtotal"]
<xarray.DataArray 'tbtotal' (frq: 14, ang: 1)> Size: 112B
array([[ 28.09264574],
       [ 26.70509246],
       [ 23.04900631],
       [ 17.54623888],
       [ 16.07600739],
       [ 14.6301906 ],
       [ 14.67710277],
       [ 98.9475077 ],
       [136.88129245],
       [237.64524868],
       [272.3412259 ],
       [279.10856471],
       [279.74409964],
       [280.13977587]])
Coordinates:
  * frq      (frq) float64 112B 22.24 23.04 23.84 25.44 ... 56.66 57.3 58.0
  * ang      (ang) float64 8B 90.0

Run torchMWRT for Multiple Profiles#

The RTModel and AtmProfile classes are designed to be run on multiple profiles in parallel / vectorized. To do this, simply add leading dimensions to the profile variables, for example by stacking multiple profiles along a new “time” dimension. The execute method processes all profiles in parallel and preserves the leading dimensions.

In this example, the code is executed on up to 1000 profiles. Note that the RTModel instance can be reused for different profiles, so the initialization overhead is incurred only once.

ds_1000 = ds.isel(synop=slice(-1001, -1))
ds_1000
<xarray.Dataset> Size: 7MB
Dimensions:  (synop: 1000, height: 208)
Coordinates:
  * synop    (synop) datetime64[ns] 8kB 2025-06-25 ... 2026-10-23T12:00:00
  * height   (height) int64 2kB 0 10 25 50 75 ... 28000 28500 29000 29500 30000
Data variables:
    T        (synop, height) float64 2MB 288.9 290.9 293.6 ... 219.3 220.5 221.6
    p        (synop, height) float64 2MB 960.7 959.6 957.8 ... 12.21 11.3 10.46
    rh       (synop, height) float64 2MB 80.18 68.36 52.2 46.25 ... 1.0 1.0 1.0
    lwc      (synop, height) float64 2MB 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
Attributes:
    station_id:      03715
    station_name:    Oberschleißheim (Lustheim)
    station_height:  484
    station_lat:     48.2446
    station_lon:     11.5525
start = time.perf_counter()

atm_profile = AtmProfile(
    temperature=ds_1000["T"],
    height=ds_1000["height"] + ds_1000.surface_altitude,
    pressure=ds_1000["p"],
    rh=ds_1000["rh"] / 100.0,
    lwc=ds_1000["lwc"],
)
result_ds = rtmodel.execute(atm_profile, return_ds=True)

end = time.perf_counter()

print(f"Elapsed time: {end - start:.3f} seconds")

result_ds["tbtotal"]
Elapsed time: 3.309 seconds
<xarray.DataArray 'tbtotal' (synop: 1000, frq: 14, ang: 1)> Size: 112kB
array([[[ 54.94801011],
        [ 50.97829505],
        [ 42.11573968],
        ...,
        [293.11084372],
        [293.65404345],
        [293.97374401]],

       [[ 52.50222212],
        [ 48.81061739],
        [ 40.49792838],
        ...,
        [295.38956456],
        [296.14161258],
        [296.62403281]],

       [[ 53.87793733],
        [ 50.16300184],
        [ 41.59395688],
        ...,
...
        ...,
        [279.20493365],
        [279.94064697],
        [280.4066352 ]],

       [[ 24.78827351],
        [ 23.4655345 ],
        [ 20.31700943],
        ...,
        [279.85431875],
        [280.25246905],
        [280.46498356]],

       [[ 32.95435198],
        [ 30.6249545 ],
        [ 25.50106758],
        ...,
        [281.22310572],
        [281.4711448 ],
        [281.54658454]]], shape=(1000, 14, 1))
Coordinates:
  * synop    (synop) datetime64[ns] 8kB 2025-06-25 ... 2026-10-23T12:00:00
  * frq      (frq) float64 112B 22.24 23.04 23.84 25.44 ... 56.66 57.3 58.0
  * ang      (ang) float64 8B 90.0