Amarisoft

SoapySDR-Python

The purpose of this tutorial is to show you how to drive an Amarisoft SDR card from Python through the SoapySDR bindings.

NOTE : Just reading this tutorial would be OK any time, but If you want to try anaything in this tutorial, you need to get Soapy SDR dev environment installed first. Refer to SoapySDR Package Installation for SoapySDR package installation with many example scripts running on top of the package. Once this package is installed, you can jump directly into Example section without reading the details.

Table of Contents

Introduction

The SoapySDR tutorial ends with an Amarisoft SDR card that any SoapySDR application can drive, and it reaches that card from Python with a few lines. What it also reports is that the Python SSB detector could not keep up with the sample stream, and it leaves that as the practical boundary of a Python receiver: fine for control and for block at a time analysis, but not for sustained processing at the sample rate. This tutorial revisits that boundary and finds it in the wrong place. The detector was not slow because numpy is slow. On a machine with many cores, the one small matrix product in its decode was being split across every core, and the threads spent far longer synchronising than multiplying. Holding the thread pool to one removes the problem entirely, and the original program then holds real time using two thirds of a single core, with no change to its code. The rest of the tutorial is what surrounds that finding: what the packaged bindings actually are, where they sit in the stack, how samples cross from the driver into a numpy array without being copied, and how to check the result. The support module is never touched. It registers with the SoapySDR runtime, and anything that reaches that runtime reaches the card by the same code path.

Summary of the Tutorial

This tutorial takes the Python side of the Amarisoft SoapySDR support as far as it goes, and corrects a conclusion the earlier tutorial drew. The claim that a numpy SSB detector cannot keep up with a 7.68 Msps stream turns out to be a measurement of a thread pool rather than of Python. The emphasis throughout is on measuring before acting: the diagnosis is one command, the fix is one environment variable, and the result is checked against the original over identical recorded samples rather than asserted. It then puts the result to work on a harder signal than the cell. GPS arrives about 20 dB below the noise it shares a band with, so nothing about it can be seen; the last two examples acquire it, follow it, read the navigation message out of it and solve a position from four satellites at once, in the same language and over the same three calls as the minimal receiver.

The conclusion is not that Python is fast. It is that the measurement which said Python was too slow was reading the wrong thing, and that four seconds under time would have found it at any point. Correctness was never in question: the shipped detector, the faster one and the Octave port all produce byte identical output over the same recorded capture. The GPS examples make the same point from the other side. A receiver that pulls a signal out from 20 dB under the noise, follows it for ninety seconds and reads a 50 bit per second message out of it is not what the earlier conclusion would have predicted from this language, and nothing in it was written in C.

If you are a human

This tutorial is relatively lengthy and covers many technical details, so you may find it difficult or time-consuming to read the entire page from beginning to end on your own. If that is the case, you can use an AI chatbot to help you understand the contents more efficiently. Simply provide the URL of this tutorial to a chatbot of your choice, such as ChatGPT, Claude, or Grok, and ask it to summarize the tutorial, explain a particular section, or answer questions about topics that are not clear to you. You can also use the chatbot interactively and learn the material through a question-and-answer process instead of reading everything sequentially.

AI coding agents can also be useful for the practical parts of this tutorial. For example, if you want to install or uninstall the soapy_project package, you can ask a coding agent such as Claude Code or Codex to perform the procedure for you by referring to the section titled "Installing/Uninstalling soapy_project package". The coding agent can examine the instructions, execute the necessary commands in your development environment, and help diagnose any errors that occur during the installation process.

In this way, you do not necessarily have to follow every step of this lengthy tutorial manually. You can use the tutorial as a reference source and let an AI chatbot or coding agent help you navigate, understand, and apply the parts that are relevant to your task.

Installing the Bindings

Nothing is compiled here. Unlike the Octave case, where no binding exists and one has to be written, the Python bindings are packaged and the whole install is one command. The version has to match the SoapySDR already on the machine, which is 0.7.1 here.

Step 1 - Install python3-SoapySDR

numpy is needed as well. The detector is written in it, and readStream wants somewhere to put the samples.

sudo dnf install python3-SoapySDR python3-numpy

The plotting section later also uses matplotlib, which is a separate package and is not needed for anything else.

sudo dnf install python3-matplotlib

Step 2 - Check it sees the card

A three line check confirms the runtime, the module and the hardware are all visible from Python. It opens no radio, so it is safe to run at any time, including while another program holds a board.

python3 -c "

import SoapySDR

print('API', SoapySDR.getAPIVersion())

for d in SoapySDR.Device.enumerate(dict(driver='amarisoft')): print(dict(d))

"

The API version has to match the runtime the support module was built against. All four boards are listed because enumeration deliberately does not open them.

API 0.7.1
{'device': '/dev/sdr0', 'driver': 'amarisoft', 'label': 'Amarisoft SDR /dev/sdr0'}
{'device': '/dev/sdr1', 'driver': 'amarisoft', 'label': 'Amarisoft SDR /dev/sdr1'}
{'device': '/dev/sdr2', 'driver': 'amarisoft', 'label': 'Amarisoft SDR /dev/sdr2'}
{'device': '/dev/sdr3', 'driver': 'amarisoft', 'label': 'Amarisoft SDR /dev/sdr3'}

What python3-SoapySDR Is

The install was one command, which makes it easy to never ask what arrived. It is worth asking, because the answer decides how much of the C++ API is reachable, what the method names will be, and where the few rough edges are.

Not built in, and not unofficial

SoapySDR is not part of Python. It is not a built-in, it is not in the standard library, and Python will say so plainly.

>>> import sys, SoapySDR
>>> "SoapySDR" in sys.builtin_module_names
False
>>> "SoapySDR" in sys.stdlib_module_names
False
>>> SoapySDR.__file__
'/usr/lib64/python3.8/site-packages/SoapySDR.py'

Not built in is not the same as unofficial, and the two are easy to confuse. There are three places code can live, and only the first of them is what built in means.

  built in            sys, builtins          compiled into the interpreter binary
  standard library    json, argparse         ships with Python, as separate files
  an extension        SoapySDR, numpy       installed beside Python, in site-packages

SoapySDR is the third, and so is numpy. That category says where the code lives. It says nothing about who wrote it.

These bindings are part of SoapySDR itself. The library and the Python module come out of one upstream tree and arrive from one source package, so the two cannot be out of step with each other. python3 is a separate package and installing them changes nothing about it.

[root@UESB-2021102500 ~]# rpm -qi SoapySDR python3-SoapySDR python3 | grep -E 'Name|Source RPM|URL'
Name        : SoapySDR
Source RPM  : SoapySDR-0.7.1-5.fc32.src.rpm
URL         : https://github.com/pothosware/SoapySDR

Name        : python3-SoapySDR
Source RPM  : SoapySDR-0.7.1-5.fc32.src.rpm          the same source as the library
URL         : https://github.com/pothosware/SoapySDR

Name        : python3
Source RPM  : python3-3.8.10-1.fc32.src.rpm         unrelated, and untouched
URL         : https://www.python.org/

What is in the package

Two files do the work, and they are the two halves of any compiled Python extension. SoapySDR.py is the module the import statement finds. _SoapySDR.so is the compiled half it loads, and that is what links the SoapySDR runtime.

[root@UESB-2021102500 ~]# rpm -ql python3-SoapySDR | grep site-packages
/usr/lib64/python3.8/site-packages/SoapySDR.py          the wrapper you import
/usr/lib64/python3.8/site-packages/_SoapySDR.so        the compiled extension

[root@UESB-2021102500 ~]# head -2 /usr/lib64/python3.8/site-packages/SoapySDR.py
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.1

Neither file was written by hand. SWIG read the SoapySDR C++ headers and produced both, which is why every Python method here carries its C++ name. setSampleRate is setSampleRate, and a line of this Python sits directly beside the matching line of detectssb.cpp.

That also means the binding is architecture specific and version specific. It is built for one Python and one SoapySDR ABI, so a machine with a different pair needs its own package rather than a copy of this one. That is what the package manager is for.

What it exposes

Almost all of it. The module publishes 94 names, and the great majority of the C++ Device interface is reachable without dropping to C.

  46   SOAPY_SDR_* constants      directions, formats, error codes, stream flags
   5   classes you use            Device, StreamResult, Range, ArgInfo, ModuleVersion
  10   SWIG container types       SoapySDRKwargs, SoapySDRStringList and the rest
  30   module level functions     version queries, module loading, logging, time conversion

  Device itself carries 102 methods:
    stream    14   setupStream, activateStream, readStream, getStreamMTU, ...
    clocking  13   getHardwareTime, setMasterClockRate, listTimeSources, ...
    rate, bw   8   setSampleRate, listSampleRates, setBandwidth, ...
    frequency  7   setFrequency, getFrequencyRange, setFrequencyCorrection, ...
    gain       7   setGain, getGainRange, listGains, setGainMode, ...
    identity   6   getDriverKey, getHardwareKey, getHardwareInfo, enumerate, ...
    sensors    6   listSensors, readSensor, readSetting, writeSetting, ...
    channels   5   getNumChannels, getFullDuplex, getChannelInfo, ...
    antenna    3   listAntennas, setAntenna, getAntenna

The module level functions are the ones with no equivalent on a device, and several are useful before any board is opened. They answer which runtime is loaded and which modules it found.

>>> SoapySDR.getABIVersion()
'0.7'
>>> SoapySDR.getRootPath()
'/usr'
>>> SoapySDR.listSearchPaths()
['/usr/lib64/SoapySDR/modules0.7', '/usr/local/lib64/SoapySDR/modules0.7']
>>> SoapySDR.listModules()
['/usr/local/lib64/SoapySDR/modules0.7/libamarisoftSupport.so']

listModules is the quickest way to tell whether the support module is where the runtime will find it. An empty list means it was built but never installed onto the search path.

How the C++ API becomes Python

Four conversions cover nearly everything, and none of them need any code on your side.

A C++ Kwargs is a dict in both directions, so device arguments go in as a dict and hardware information comes back as one. A C++ vector is a list. A Range arrives as an object with minimum, maximum and step. And a C++ exception becomes a RuntimeError carrying the message the module wrote.

The session below opens a board and asks it what it is, which is the same set of calls SoapySDRUtil makes when it probes.

>>> d = SoapySDR.Device(dict(driver="amarisoft", device="/dev/sdr0"))
>>> d.getDriverKey(), d.getHardwareKey()
('amarisoft', 'AD9361')
>>> d.getNumChannels(SOAPY_SDR_RX)
2
>>> list(d.listAntennas(SOAPY_SDR_RX, 0))
['RX', 'TX_RX']
>>> r = d.getGainRange(SOAPY_SDR_RX, 0); r.minimum(), r.maximum()
(3.0, 71.0)
>>> list(d.getStreamFormats(SOAPY_SDR_RX, 0))
['CF32', 'CS16']
>>> list(d.listSensors())
['fpga_temp', 'rx_overflow_count', 'tx_underflow_count', 'abs_rx_power', ...]
>>> dict(d.getHardwareInfo())
{'device': '/dev/sdr0', 'fpga_revision': '2026-06-03  16:51:11', 'hardware_id': '0x4b01', ...}

Errors arrive the same way. Opening a device that is not there raises rather than returning a code, and the text is the one the support module produced.

>>> SoapySDR.Device(dict(driver="amarisoft", device="/dev/nope"))
RuntimeError: SoapyAmarisoft: msdr_open failed for "dev0=/dev/nope" - the device
may be in use by another process (lteue/lteenb)

The one place the mapping is not clean is a C++ method that returns a value through an argument. SWIG cannot guess what to do with those, so each one needs a rule written for it, and not every method got one.

readStream did. Its flags and timeNs are C++ output parameters, and rather than being passed in they come back gathered into a StreamResult with ret, flags, timeNs and chanMask. That is why three arguments are enough at the call site even though SoapySDR.py declares six.

getNativeStreamFormat did not. Its fullScale output parameter is still in the Python signature, so calling it the way the C++ documentation reads raises a TypeError about a missing argument. It is worth knowing that the rule is per method, so an unfamiliar call is worth checking against SoapySDR.py before assuming it takes the C++ argument list.

Using the Bindings

With the shape of the package established, the rest is using it. Where it sits in the stack, the order the calls have to come in, how samples reach numpy, and who is responsible for giving the card back.

Where SoapySDR sits

Six layers separate the RF at the antenna from a numpy array. Only the top two are Python. The lower four are the ones the SoapySDR tutorial builds and describes, and they are not rebuilt or reconfigured for Python.

_SoapySDR.so is linked against the SoapySDR runtime and against nothing else. It carries no reference to the support module or to libsdr. The string amarisoft passed as driver is data, handed to the runtime, and the runtime uses it to choose a factory.

The stack below reads from the board at the bottom to the Python prompt at the top. The left column says where each layer comes from. The arrows on the right say what crosses each boundary, and a dashed arrow marks the one join made at run time rather than at build time.

rx_minimal.py   detect_ssb.py   plot_spectrum.py the example programs and the interactive prompt /root/soapy_project/python/*.py your code import SoapySDR the SWIG binding: SoapySDR.py plus _SoapySDR.so /usr/lib64/python3.8/site-packages/_SoapySDR.so python3-SoapySDR package found by sys.path, installed by dnf libSoapySDR.so.0.7 the abstraction: factory registry, SoapySDR::Device /usr/lib64/libSoapySDR.so.0.7.1 SoapySDR package the normal linker path libamarisoftSupport.so SoapyAmarisoft: turns Device calls into msdr_* calls /usr/local/lib64/SoapySDR/modules0.7/libamarisoftSupport.so built in the SoapySDR tutorial must be on the module search path libsdr.so    +    sdr.ko the msdr_* C API and the kernel driver /root/trx_sdr/api/libsdr.so   /root/trx_sdr/kernel/sdr.ko Amarisoft trx_sdr release found by RPATH in the module /dev/sdr0 .. /dev/sdr3    -    SDR card RF in, IQ samples out character device, major 237, created by sdr.ko the board dev.readStream (rx, [buf], mtu) SoapySDR::Device calls linked at build time: -lSoapySDR dlopen at the first Device (), the factory chosen by driver = "amarisoft" msdr_* C API ioctl and DMA hyperframes linked at build time loaded at run time

Only one of those files has to be in a particular place. The SoapySDR runtime finds its modules by scanning two fixed directories, /usr/lib64/SoapySDR/modules0.7 and /usr/local/lib64/SoapySDR/modules0.7. So libamarisoftSupport.so is installed rather than merely built. A module left in the build tree is a module the runtime never sees.

Watching which shared objects the process has mapped shows each layer arriving only when it is first needed.

--- before import ---
  (nothing)

--- after import SoapySDR ---
  /usr/lib64/python3.8/site-packages/_SoapySDR.so
  /usr/lib64/libSoapySDR.so.0.7.1

--- after opening the card ---
  /usr/lib64/python3.8/site-packages/_SoapySDR.so
  /usr/lib64/libSoapySDR.so.0.7.1
  /usr/local/lib64/SoapySDR/modules0.7/libamarisoftSupport.so
  /root/trx_sdr-linux-2026-08-27/libsdr.so

The support module arrives at the first Device call, not at import, because that is when the runtime first consults its factory registry. Enumerating or importing pulls in neither it nor libsdr.

The call surface

The sequence below is the whole interface in one session. It is the same mandatory order as the C++ version: construct, configure, set up a stream, activate it, read, then release.

dev = SoapySDR.Device(dict(driver="amarisoft", device="/dev/sdr0"))

dev.setSampleRate(SOAPY_SDR_RX, 0, 7.68e6)

dev.setFrequency(SOAPY_SDR_RX, 0, 3488.16e6)

dev.setGain(SOAPY_SDR_RX, 0, 40)

 

rx = dev.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32, [0])

dev.activateStream(rx)

sr = dev.readStream(rx, [buf], mtu)

 

dev.deactivateStream(rx)

dev.closeStream(rx)

Direction is the integer constant SOAPY_SDR_RX rather than a string, and channels are zero based, exactly as SoapySDR numbers them. The constants come from the module, so they cannot drift from the library they describe.

Getting the samples out

readStream does not return an array. It is given one, as a list with one entry per channel, and it fills it in place. That is why the buffer is allocated once outside the loop and reused.

buf = np.empty(mtu, np.complex64)

sr = dev.readStream(rx, [buf], mtu)

 

sr.ret number of samples written, or a negative error code

sr.flags HAS_TIME, END_ABRUPT and the rest

sr.timeNs hardware timestamp of buf[0]

SoapySDR CF32 is a pair of 32 bit floats, which is exactly numpy complex64. The driver therefore writes straight into the array numpy already owns. Nothing is converted, copied or reinterpreted between the card and the workspace.

Two returns are easy to get wrong. A ret of SOAPY_SDR_TIMEOUT is an ordinary event rather than an error, so the loop continues instead of aborting. And ret is the count actually delivered, which is one DMA hyperframe and not necessarily the number asked for, so the buffer is sliced to it before use.

Releasing the card

The board is opened exclusively, so a program that exits without releasing it leaves the next one unable to start. Python makes this easier than Octave does. The Device object is released when it is garbage collected. Relying on that is still a mistake when an exception is in flight.

Both example programs put the teardown in a finally block for the same reason the C++ version uses destructors. It runs whether the body finished or threw.

Example 1 - a minimal receiver

This is the smallest correct SoapySDR receiver. The mandatory calls are highlighted. What it proves is narrow and worth proving: the streaming interface runs at the full sample rate from Python, before any signal processing is put on top of it.

#!/usr/bin/env python3
"""
The smallest *correct* SoapySDR receiver for the Amarisoft card, in Python.

Same mandatory sequence as the C++ version: open, set up a stream, activate it,
read while checking the return, then deactivate, close and release.  Nothing in
this file is Amarisoft specific except the driver name.

  ./rx_minimal.py --device /dev/sdr0 --freq 3479.52e6 --rate 30.72e6 --gain 6
"""

import argparse
import math
import sys
import time

import numpy as np
import SoapySDR
from SoapySDR import SOAPY_SDR_RX, SOAPY_SDR_CF32, SOAPY_SDR_TIMEOUT


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--device")                              # optional
    ap.add_argument("--freq", type=float, default=3479.52e6)
    # 30.72 MHz works on both front ends; 7.68 is AD9361 only.
    ap.add_argument("--rate", type=float, default=30.72e6)
    ap.add_argument("--gain", type=float, default=6.0)
    ap.add_argument("--seconds", type=float, default=2.0)
    a = ap.parse_args()
    # A capture length turns into a sample target.  A huge value simply
    # never completes, which reads as a hang; a non-positive one reads
    # zero samples and reports success.  Reject both.
    if not math.isfinite(a.seconds) or not 0.0 < a.seconds <= 300.0:
        sys.exit(f"ERROR: --seconds must be greater than 0 and at most 300, "
                 f"got {a.seconds}")


    args = dict(driver="amarisoft")                          # required
    if a.device:
        args["device"] = a.device

    dev = None
    rx = None
    try:
        dev = SoapySDR.Device(args)                          # required

        dev.setSampleRate(SOAPY_SDR_RX, 0, a.rate)
        dev.setFrequency(SOAPY_SDR_RX, 0, a.freq)
        dev.setGain(SOAPY_SDR_RX, 0, a.gain)

        rx = dev.setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32, [0])   # required
        dev.activateStream(rx)                                    # required

        mtu = dev.getStreamMTU(rx)
        buf = np.empty(mtu, np.complex64)

        print(f"tuned {dev.getFrequency(SOAPY_SDR_RX, 0)/1e6:.3f} MHz at "
              f"{dev.getSampleRate(SOAPY_SDR_RX, 0)/1e6:.3f} Msps, "
              f"gain {dev.getGain(SOAPY_SDR_RX, 0)} dB, MTU {mtu}")

        target = int(a.rate * a.seconds)
        got = 0
        timeouts = 0
        power = 0.0
        t0 = time.monotonic()

        while got < target:
            sr = dev.readStream(rx, [buf], mtu)               # required
            if sr.ret == SOAPY_SDR_TIMEOUT:                   # normal, not fatal
                timeouts += 1
                continue
            if sr.ret < 0:                                    # a real error
                print(f"readStream error {sr.ret}", file=sys.stderr)
                break
            n = sr.ret                                        # may be < mtu
            power += float(np.sum(np.abs(buf[:n]) ** 2))
            got += n

        wall = time.monotonic() - t0
        print(f"read {got} samples in {wall:.3f} s "
              f"= {got/wall/1e6:.3f} Msps (real time needs {a.rate/1e6:.3f})")
        print(f"mean power {10*np.log10(power/max(got,1) + 1e-30):.2f} dBFS, "
              f"timeouts {timeouts}, overflows {dev.readSensor('rx_overflow_count')}")

    except Exception as ex:                                   # Device() throws
        print(f"ERROR: {ex}", file=sys.stderr)
        return 1
    finally:
        # Required: the card is opened exclusively.
        if dev is not None and rx is not None:
            dev.deactivateStream(rx)
            dev.closeStream(rx)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run at 7.68 Msps it keeps up exactly, with no timeouts and no overflows. The mean power is the noise floor of a board that is not pointed at anything in particular.

[root@UESB-2021102500 python]# ./rx_minimal.py --device /dev/sdr0 --rate 7.68e6 --gain 6 --seconds 1
tuned 3479.520 MHz at 7.680 Msps, gain 6.0 dB, MTU 512
read 7680000 samples in 1.000 s = 7.681 Msps (real time needs 7.680)
mean power -63.90 dBFS, timeouts 0, overflows 0

The same program at 30.72 Msps reads 30.728 Msps, again with no overflows. So the binding is not the limit at any rate the card offers.

Usage examples

Every option has a default, so the shortest useful run names only the board. The card is opened exclusively, so a board already held by lteue or lteenb has to be left alone and another one named instead.

The plain case. Two seconds at 30.72 Msps, which is enough to show that the stream runs at the rate the card was asked for and that nothing is being dropped.

./rx_minimal.py --device /dev/sdr0

The narrow setup the GPS examples use. 3.84 Msps is a quarter of the usual rate and 1575.42 MHz is L1, so this is the quickest way to check that the card tunes there and that the gain is sane before anything is decoded.

./rx_minimal.py --device /dev/sdr0 --freq 1575.42e6 \

--rate 3.84e6 --gain 40

A longer run. Overflows rarely appear in the first second, because the driver buffers absorb the start; ten seconds is long enough for a rate the machine cannot sustain to show itself.

./rx_minimal.py --device /dev/sdr0 --seconds 10

A second board at a different rate. 7.68 Msps is the rate the SSB detector uses, and it is supported only on the AD9361 front end, so this also says which kind of board is in the slot.

./rx_minimal.py --device /dev/sdr1 --rate 7.68e6

Example 2 - SSB detection

The second example is a numpy port of the 5G NR SSB detector, performing the same overlap-save PSS correlation and the same SSS decode as the C++ version. The program is detect_ssb_fast.py. Pointed at a live cell it holds real time at 7.68 Msps inside two thirds of a single core, so the whole path from the card to a printed detection is Python with no compiled step anywhere in it.

Test Setup

This test is requires a special signal source that can feed SSB signal to the script. otherwise, the script would run but never pass. There are several options to feed SSB signal to the RX port where the script is running. A few examples of the setups are shown here.

< Case 1 >

Two machines are involved. The gNB runs on the callbox on the left and the detector runs on the UEsim on the right. Four coax cables run directly between the SDR ports of the two card cages.

No UE is connected to the gNB, so the cell sits idle. That is what you want here. An idle cell transmits SSB and SIB1 and nothing else. The detector then sees a clean repeating SSB with no traffic on top of it.

The detector runs on the UEsim, so the machine doing the numpy work is not the machine generating the signal. Neither one has to share cores with the other.

gNB on the callbox cabled to the UEsim running the detector

< Case 2>

One machine with two SDR boards in it. The gNB runs on sdr0 and the detector runs on sdr1. A single coax loops from TX0 on the first board down to RX0 on the second.

This is the setup the commands in this tutorial assume. rx_minimal.py is pointed at /dev/sdr1 for exactly this reason, because sdr0 is busy being the cell.

This needs the least hardware of the three. The cost is that the cell and the detector share the same cores. That matters for a program whose whole point is keeping up in real time.

Loopback from TX0 on sdr0 to RX0 on sdr1 inside one Amarisoft PC

< Case 3>

There is no gNB at all here. An RF signal generator is cabled straight into RX0 on the Amarisoft PC. Any other source that can play out an SSB waveform works the same way.

The generator in this example is set to the frequency and power level that would work for the script, out of its RF OUT / TX port. Two things have to match. The centre frequency you pass to the script has to be the generator frequency. The level has to be one the input can take without compressing.

Use this when you want the signal under your own control. You decide what is transmitted and at what level, so a detector problem is easier to tell apart from a radio one.

RF signal generator cabled into RX0 of the Amarisoft PC

One BLAS thread

The SSS decode tests all 336 hypotheses in a single matrix product, and numpy hands that to BLAS. OpenBLAS sizes its thread pool from the core count, so on the 36 core machine used here a 336 by 127 matrix multiplied by a 127 element vector would be split 36 ways, and the barrier between the threads costs far more than the multiply. The work is too small to divide, so the program holds the pool to one thread.

The limit has to be in place before numpy is imported, because the pool is sized when the BLAS library loads. That puts these lines above every other import in the file.

import os

# Must happen before numpy is imported, because the thread pool is sized when
# the BLAS library loads.  setdefault, so an explicit setting still wins.
for _v in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ.setdefault(_v, "1")

setdefault rather than plain assignment, so a reader who wants to experiment with a different pool size can still override it from the shell. Nothing has to be set in the environment for the program to run as intended.

Gathering the reads

The card hands over one MTU per readStream, which is 512 samples here, so a second of radio at 7.68 Msps is about fifteen thousand reads. Calling the detector on each of them costs more than the detection itself. Reads are gathered into a preallocated run instead, and the detector sees one HOP at a time.

Gathering is only sound while the samples are contiguous. The support module sets END_ABRUPT on the first read after anything was dropped, so the run is closed at that point and the next one is anchored on the read that follows the gap. Every reported timestamp then belongs to the sample it came from.

        # The card hands over one MTU per readStream, which is 512 samples
        # here, so a second of radio at 7.68 Msps is fifteen thousand reads.
        # Calling the detector on each of them costs more than the detection.
        # Reads are gathered into a preallocated run instead, and the detector
        # sees one HOP at a time.
        #
        # Gathering is only sound while the samples are contiguous.  The
        # support module sets END_ABRUPT on the first read after anything was
        # dropped, so the run is closed there and the next one is anchored on
        # the read that follows the gap.
        run = np.empty(HOP + mtu, np.complex64)
        nrun = 0
        run_ns = 0

        target = int(rate * a.seconds)
        got = 0
        ndet = 0
        t0 = time.monotonic()

        def flush():
            nonlocal nrun, ndet
            if nrun == 0:
                return
            det.push(run[:nrun].copy(), run_ns)
            nrun = 0
            for d in det.process(rate):
                ndet += 1
                t = time.monotonic() - t0
                print(f"  {t:10.4f}  {d['time_ns']:15d}   {d['nid2']:5d}  "
                      f"{d['nid1']:5d}  {d['pci']:4d}  {d['corr']:5.3f}  "
                      f"{d['margin']:5.1f} dB")

        while got < target:
            sr = dev.readStream(rx, [buf], mtu)
            if sr.ret == SOAPY_SDR_TIMEOUT:
                continue
            if sr.ret < 0:
                print(f"readStream error {sr.ret}", file=sys.stderr)
                break
            got += sr.ret

            if nrun and (sr.flags & SOAPY_SDR_END_ABRUPT):
                flush()
            if nrun == 0:
                run_ns = sr.timeNs
            run[nrun:nrun + sr.ret] = buf[:sr.ret]
            nrun += sr.ret
            if nrun >= HOP:
                flush()

        flush()

The detection block

The detector is overlap-save. Each block of M samples is transformed once and correlated against the three PSS sequences in the frequency domain, and the metric is the correlator output normalised by the energy of the window it sits on. detect_ssb_fast.py uses a 4096 sample block.

Two pieces of arithmetic are worth pointing at. The squared magnitude is written as the real part squared plus the imaginary part squared, which avoids a square root that the square immediately undoes, and over a 3 by M matrix that is the most expensive line in the block. The reference energy that normalises the metric is folded into the matched filter at construction, so the inner loop loses a division as well.

    def process(self, rate):
        out = []
        nvalid = HOP
        while len(self.buf) >= M + NEED_AHEAD:
            blk = self.buf[:M].astype(np.complex128)
            spec = np.fft.fft(blk)
            corr = np.fft.ifft(spec[None, :] * self.ref_f, axis=1)   # (3, M)

            # abs() takes a square root that the square then undoes, and
            # over a 3-by-M matrix that is the most expensive line in the
            # block.  ref_f already carries 1/sqrt(energy), so this is the
            # numerator of the metric and not just the correlator output.
            pw = corr.real ** 2 + corr.imag ** 2                     # (3, M)

            # sliding N_FFT energy of the block, via a cumulative sum
            cs = np.concatenate([[0.0], np.cumsum(blk.real ** 2 + blk.imag ** 2)])
            e_win = cs[N_FFT:N_FFT + nvalid] - cs[:nvalid]
            e_win[e_win <= 0] = np.inf

            best_n2 = np.argmax(pw[:, :nvalid], axis=0)
            best_m = pw[best_n2, np.arange(nvalid)] / e_win
            mx = float(best_m.max())
            if mx > self.best_seen:
                self.best_seen = mx

            # Below the threshold there is no peak to pick, which is the
            # usual case; one comparison saves scanning the whole block.
            if mx >= self.threshold:
                for off in np.flatnonzero(best_m >= self.threshold):
                    if off > 0 and best_m[off - 1] >= best_m[off]:
                        continue
                    if off + 1 < nvalid and best_m[off + 1] > best_m[off]:
                        continue
                    a = self.abs_start + int(off)
                    if a - self.last_det < SYM:
                        continue
                    d = self._decode(int(off), int(best_n2[off]),
                                     float(best_m[off]), a, rate)
                    if d:
                        self.last_det = a
                        out.append(d)

            self.buf = self.buf[HOP:]
            self.abs_start += HOP
        return out

Example run

The cell used for these runs is the idle mode gNB on the bench, band n78, 20 MHz, 30 kHz subcarrier spacing. Its SSB ARFCN is 632544, which is not the same as its cell centre ARFCN of 632628. The detector wants the SSB center ARFCN

[root@UESB-2021102500 python]# ./detect_ssb_fast.py --arfcn 632544 --scs 30 --device /dev/sdr0 --gain 40 --seconds 2
detect_ssb_fast.py - 5G NR SSB detection (Python / numpy)
  ARFCN         : 632544
  SSB centre    : 3488.160 MHz
  SCS           : 30.0 kHz
  sample rate   : 7.680 Msps

        time    timestamp(ns)   NID_2  NID_1   PCI   PSS    SSS
  ------------  ---------------   -----  -----  ----  -----  ------
      0.0118        322519401       1     33   100  0.923   16.7 dB
      0.0315        342519401       1     33   100  0.917   16.8 dB
      0.0515        362519401       1     33   100  0.909   16.6 dB
      ...            ...           ...    ...    ...    ...     ...
      1.9897       2293068880       1     33   100  0.836   16.7 dB

--- summary ---
  detections    : 100
  samples       : 15360000 in 2.000 s
  throughput    : 7.679 Msps (real time needs 7.680)
  rx overflows  : 1
  best PSS corr : 0.9811

The SSB period on this cell is 20 ms, so two seconds carries exactly one hundred of them and the detector reported one hundred. There is no warning line at the end, because it kept up. The single overflow is the one that happens while the stream is starting.

Under time the same run costs 1.74 seconds of user time and 0.09 of system time, which is 57% of one core for a 7.68 Msps stream. A detection count above 100 would not be a bonus. It would mean the run took longer than two seconds of radio, seeing more SSB periods while missing some of them.

Proving the port is faithful

A detector that keeps up is not worth much if it is finding different things. Comparing two live runs cannot settle that, because the two ran over different noise. The only clean test is to give both the same samples.

So four million samples were captured once to a file as raw complex float, and the Octave detector, the plain numpy port and detect_ssb_fast.py were each run over that file with the radio out of it. Each was fed in 512 sample chunks so the push pattern was identical.

All three agree completely: the same twenty six detections, the same identities, the same correlations to four decimals and the same best correlation seen to six.

octave detect_ssb.m      : 26 detections, best 0.966031
python detect_ssb.py     : 26 detections, best 0.966031
python detect_ssb_fast.py: 26 detections, best 0.966031
THREE-WAY PARITY: all byte identical

NOTE : If you knew PCI carried by the SSB, just compare the known PCI and the PCI decoded by the script and see if they match.

Usage examples

Both detectors take the same arguments, so a command can be moved between them by changing the name. --arfcn is the only one with no default, because there is no sensible guess: it names the channel, and the program converts it to a frequency.

The usual case. Band n78 at 30 kHz subcarrier spacing, which is what an idle Amarisoft gNB is normally configured for. This is the detector as first written, and on a many core machine it will report overflows and warn that SSBs may have been missed.

./detect_ssb.py --arfcn 631968 --scs 30 --device /dev/sdr0 --gain 6

The same run with the thread limit applied. The arguments are identical and so is the detection; what changes is that this one keeps up with the radio, so nothing is dropped and the count of SSBs is complete.

./detect_ssb_fast.py --arfcn 632544 --scs 30 \

--device /dev/sdr0 --gain 40

A long run, which is the reason for the speed. Thirty seconds of an idle cell is about fifteen hundred SSB periods, and a detector that drops samples will miss a different subset on every pass, which makes results hard to compare.

./detect_ssb_fast.py --arfcn 632544 --device /dev/sdr0 --seconds 30

A longer dwell on a sparse cell. An SSB burst lasts about a quarter of a millisecond in every twenty, so a short run on an idle cell can legitimately find nothing.

./detect_ssb.py --arfcn 631968 --device /dev/sdr0 --seconds 10

Moving the threshold. Lowering it finds weaker bursts at the cost of false hits; raising it does the opposite, which is what a noisy band calls for. The default of 0.08 is the correlation metric, normalised, so it does not change with gain.

./detect_ssb.py --arfcn 631968 --device /dev/sdr0 --threshold 0.04

./detect_ssb_fast.py --arfcn 632544 --device /dev/sdr0 --threshold 0.12

Example 3 - plotting the spectrum

Everything so far has been a program that prints. The other reason to drive a radio from Python is to look at what it hears, and a numpy array is already in the form matplotlib wants.

Test Setup

This test is requires a special signal source that can feed some signal into the script, otherwise you will get the plot but the entire spectrum will be stay around noise floor. You can use the same test setup used in previous example and feed signal to the script

How to Run

plot_spectrum.py opens the card, averages transforms and draws the result. It writes a file by default and selects the Agg backend to do so, because the machine this runs on usually has no display. With --show it opens a window instead.

./plot_spectrum.py --device /dev/sdr0 --freq 3489.42e6 --rate 30.72e6 --span 30 -o spectrum.png

One transform is not a spectrum when the cell is idle. An SSB burst lasts about a quarter of a millisecond in every twenty, and a single 32768 point transform covers about one, so most single shots catch nothing but noise. The default of 64 averages is a little over two milliseconds of radio per transform and sixty eight in total, which covers several SSB periods.

tuned 3489.420 MHz at 30.720 Msps, gain 40.0 dB, MTU 2048
averaged 64 transforms of 32768 points = 68.3 ms of radio
wrote spectrum.png

The span is 30 MHz around 3489.42 MHz. That is the cell centre rather than the SSB centre, so the whole carrier falls inside the display with clear air either side. The carrier shows as a flat block about 18 MHz wide, measured from 3480.4 to 3498.4 MHz. That is the 51 resource blocks a 20 MHz channel uses at 30 kHz subcarrier spacing, which is 18.36 MHz.

Averaged 30 MHz spectrum from Python showing the 18 MHz n78 carrier

How the code works

The program is one function. It opens the card the same way Example 1 does, then spends its time in a loop that fills a buffer, transforms it and adds the result to an accumulator. There is no class and no state carried between iterations beyond that accumulator.

One decision has to be made before matplotlib is imported rather than after. Selecting a backend only takes effect if it happens before pyplot loads, and the machine this runs on usually has no display, so the import is deferred until the arguments have been read and the choice can be made from them.

    import matplotlib
    if not a.show:
        # No display is needed to write a file, and the box this runs on
        # usually has none.  Must be chosen before pyplot is imported.
        matplotlib.use("Agg")
    import matplotlib.pyplot as plt

The measurement itself is the loop below. readStream hands over one MTU at a time and a transform needs N of them, so the inner while loop gathers reads until the segment is full; the outer for repeats that for as many averages as were asked for. What accumulates is the squared magnitude of each transform, not the transform itself. Adding complex spectra would let the phases cancel and the result would tend to nothing; adding power is what makes an average converge on the shape of the signal.

        N = a.nfft
        win = np.hanning(N)
        acc = np.zeros(N)
        seg = np.empty(N, np.complex64)
        n = 0

        for _ in range(a.averages):
            filled = 0
            while filled < N:
                sr = dev.readStream(rx, [buf], mtu)
                if sr.ret == SOAPY_SDR_TIMEOUT:
                    continue
                if sr.ret < 0:
                    print(f"readStream error {sr.ret}", file=sys.stderr)
                    return 1
                take = min(sr.ret, N - filled)
                seg[filled:filled + take] = buf[:take]
                filled += take
            acc += np.abs(np.fft.fft(seg.astype(np.complex128) * win)) ** 2
            n += 1

        psd = 10 * np.log10(np.fft.fftshift(acc / n) + 1e-12)
        f = (np.arange(N) - N // 2) / N * rate / 1e6 + freq / 1e6

Three small things in those last lines do more than they look. The Hanning window is applied because a transform assumes the segment repeats, and a segment that does not join up at its ends behaves like a step; the window tapers both ends to zero so a strong carrier does not smear across the whole display. The fftshift moves the zero frequency bin from the start of the array to the middle, which is where a spectrum is expected to have it. The small constant added before the logarithm keeps an empty bin from producing negative infinity and taking the plot with it.

The frequency axis is built rather than measured. Bin k of an N point transform of samples taken at the card's rate is at k times rate over N, and the rate and centre frequency are read back from the device rather than taken from the command line, so the axis describes what the card actually did rather than what was asked of it.

Usage examples

The program writes a file unless told otherwise, because the machine it runs on usually has no display. Everything else has a default that suits an n78 cell.

A cell, with 30 MHz of span around its centre. The span only affects the axes; the whole sample rate is still received and transformed, so narrowing it costs nothing and simply stops the interesting part being squeezed into the middle of the plot.

./plot_spectrum.py --device /dev/sdr0 --freq 3489.42e6  --span 30 -o cell.webp

A window instead of a file. This needs a display, and it is the one case where the Agg backend is not selected, so it will fail on a headless box rather than silently write nothing.

./plot_spectrum.py --device /dev/sdr0 --show

Heavier averaging for an idle cell. Sixty four transforms is about sixty eight milliseconds of radio; 256 is four times that, which lowers the noise on the trace by about 6 dB and makes a sparse carrier easier to see.

./plot_spectrum.py --device /dev/sdr0 --averages 256 -o idle.png

The GPS band, which is worth plotting once precisely because there is nothing to see. A flat trace at L1 is the correct result: the signal is below the noise, and Example 4 is what recovers it.

./plot_spectrum.py --device /dev/sdr0 --freq 1575.42e6 --rate 3.84e6 --gain 40 -o gps.png

Example 4 - finding GPS satellites

The three examples so far look at a signal that is there to be seen. A cell transmits at a level the spectrum plot shows without any help. GPS does not. The signal from a satellite arrives about 20 dB below the thermal noise in the same bandwidth, so nothing in a spectrum marks where it is, and averaging more transforms does not bring it out. The band looks empty because, measured that way, it is.

What makes it visible is that every satellite repeats a known 1023 chip code every millisecond, at 1.023 Mcps, and they all share the one frequency. Correlating the samples against the right code at the right delay collapses a whole millisecond of signal onto a single peak, and that peak stands clear of a noise floor the signal itself never rose above.

The purpose of this example to implement the algorithm to detect and decode GPS signals

Test Setup

This is an example in the tutorial that needs an antenna of its own, cabled to an RX port on the board. Which of the two cases below applies depends on whether the antenna needs DC power to run. If it does, it also depends on where that power comes from. Both cases end at the same place, the RX1 port of the SDR.

< Case 1 >

This is the simple one. The antenna cable runs straight to the RX1 port on the SDR card and nothing sits in between.

Use it when the antenna is passive, and also when the antenna is active but carries its own battery inside the antenna module. In both cases the board does not have to send anything up the coax, so a direct connection is all that is needed.

The connector marked RX1 is the one used here, on the board that the --device argument names.

GPS antenna cabled directly to the SDR RX1 port

< Case 2 >

An active antenna with no battery of its own needs DC sent up the same coax that brings the signal down. A bias tee does that, and it goes between the antenna and the board.

The antenna connects to the RF+DC port of the bias tee. The DC port on the side takes the battery. The RF port at the bottom goes to RX1 on the SDR card. It carries the signal with the DC blocked, so nothing is fed back into the RX input.

GPS active antenna fed through a battery powered bias tee into the SDR RX1 port

How to Run

gps_print.py does this for all 32 codes, stepping a carrier replica across a Doppler range because a satellite moving at four kilometres a second shifts the carrier by several kilohertz.

./gps_print.py --device /dev/sdr0 --gain 40 --ms 150 --doppler 6000 --step 250

Correlation in time is multiplication in frequency, so one transform of the samples and one inverse transform per code gives all 1023 delays together rather than one at a time. That is what makes the search tractable: six million cells, covering 32 codes against 49 Doppler bins against 3840 code phases, in eleven seconds on this machine.

gps_print.py - GPS L1 C/A acquisition
  centre        : 1575.420 MHz
  sample rate   : 3.840 Msps  (3840 samples per ms)
  gain          : 40 dB
  integration   : 150 x 1 ms, non-coherent
  doppler search: -6000 to +6000 Hz in 250 Hz steps (49 bins)
  searching     : 32 PRN, 6021120 cells in all
  threshold     : 1.60 peak/floor (for a 0.001 false alarm chance over the whole search)

  captured 576000 samples in 0.150 s, mean power -42.9 dBFS
  searched 32 PRN x 49 Doppler x 3840 code phases over 150 ms in 10.92 s

   PRN   Doppler Hz   code phase   C/N0 dB-Hz   peak/floor   peak/second
   ---   ----------   ----------   ----------   ----------   -----------
    28        -1500        884.5         41.2        14.29          9.14
    31         +250        230.4         36.9         5.85          3.93
    25        -3500        639.9         33.3         3.15          1.97
    32        -2500        542.1         33.1         3.03          1.87
    16        +4000        439.8         32.0         2.57          1.52

  --- summary ---
  satellites found : 5
  PRNs             : 28 31 25 32 16

  --- position ---
  satellites used  : 5  (28 31 25 32 16)
  latitude         :   44.850 N
  longitude        :   74.800 W
  residual         : 28 Hz, against a 250 Hz step
  Doppler only, so good to tens of km; a smaller --step tightens it

Two columns decide whether a row is a satellite. peak/floor is the best cell against the median of the rest, and the threshold beside it is computed from the size of the search rather than chosen: six million cells give noise six million chances to produce a tall peak, so the bar has to rise with the search. peak/second is the best cell against the next highest outside its own main lobe, and it is the one that separates a real detection from a loud patch of noise, because noise sits near 1 however low the floor happens to be. PRN 16 clears the second of those bars by 0.02 and is the kind of detection that appears in one run and not the next.

Two settings (--gain and --ms) matter more than they look. The gain should be configured so that it should not saturate the RX chain of the sdr card. --ms (integration period) should be set carefully as well. Just putting a large number does not always guarantee the better performance. In this example, the integration is 150 ms because more is worse, not better. A satellite code drifts as well as its carrier, by about 1.3 chips a second at 2 kHz of Doppler, and the correlation peak is only a chip wide, so past roughly 150 ms the peak smears across the accumulation faster than the noise averages down.

The position at the end is honest about what it is. No navigation message has been read, so the program has no idea where the satellites are; it downloads the current almanac and solves from Doppler alone. Each satellite's rate of change of range constrains where the listener can be, and five of them, with the receiver oscillator offset taken out as a term common to all, give an answer. The answer here is about 100 km from the true position, which is what Doppler at a 250 Hz step is worth. It is a region, not a point, and the next example is what turns it into one.

How the code works

gps_print.py is ten functions and no classes. Four of them do the work, and the shape of the program is the shape of the search.

ca_code(prn)          the 1023 chip code for one satellite, from two shift
                      registers; the only thing that differs between
                      satellites is which two G2 stages are combined

sampled_codes(prns)   every code stretched onto one millisecond of samples,
                      transformed once and conjugated: the matched filter,
                      built before the search rather than inside it

acquire(...)          the search.  For each millisecond, for each Doppler:
                      wipe the carrier, transform, multiply by all 32 codes
                      at once, transform back, add the squared magnitude

peaks(...)            reduce each satellite's surface to one candidate and
                      two ways of judging it, plus a C/N0 estimate

threshold_for(...)    the bar the candidate has to clear, computed from the
                      false alarm rate and the number of cells searched

locate(hits)          a position from Doppler alone, using gps_predict.py
                      and the downloaded almanac

self_test(), synth()  check the code generator against the published chips,
                      and run the whole search on a manufactured signal of
                      known C/N0.  Neither needs a radio

The search is the interesting part, and it is short because the transform is doing the work. Correlating against one code at one delay would test one of 1023 possibilities. Multiplying in the frequency domain and transforming back produces all 1023 delays in a single operation, so the inner loop never iterates over code phase at all; the code phase axis is the length of the array that comes out. The docstring is left out of the listing because the paragraph after it says the same thing.

def acquire(x, n, prns, codes_f, dopplers, rate):
    nblk = len(x) // n
    npr, nd = len(prns), len(dopplers)
    acc = np.zeros((nd, npr, n), np.float64)
    t = np.arange(n) / rate
    wipe = np.exp(-2j * np.pi * np.outer(dopplers, t))
    mix = np.empty(n, np.complex128)
    prod = np.empty((npr, n), np.complex128)
    for b in range(nblk):
        blk = x[b * n:(b + 1) * n].astype(np.complex128)
        blk -= blk.mean()                 # the card leaves a DC spike at centre
        for di in range(nd):
            np.multiply(blk, wipe[di], out=mix)
            xf = np.fft.fft(mix)
            np.multiply(xf, codes_f, out=prod)      # one matched filter per PRN
            corr = np.fft.ifft(prod, axis=1)
            acc[di] += corr.real ** 2 + corr.imag ** 2
    return acc, nblk

Three details in those lines are worth naming. The accumulator is indexed by Doppler, then satellite, then code phase, so each addition writes one contiguous block instead of striding across the satellite axis. The two scratch buffers are allocated once and reused with the out= argument, which keeps the inner loop from handing several megabytes back to the allocator thousands of times over. The mean is removed from every block because the card leaves a DC spike at the centre of the band, and a constant offset correlates with the non zero mean of a code just enough to matter.

What accumulates is the squared magnitude, one millisecond at a time. That is non coherent integration: it throws away the carrier phase, which is why it tolerates a Doppler estimate that is only good to half a bin, and why more of it helps only up to a point. The threshold is not a constant. Six million cells give noise six million chances to produce a tall peak, so threshold_for computes the bar from the requested false alarm probability and the size of the search, which is why narrowing the Doppler range makes the program more sensitive rather than merely faster.

Usage examples

The defaults are deliberately not the right settings for an active antenna. 60 dB of gain and a 10 kHz Doppler search will find nothing on this bench, so every command below names a gain and a search width.

A cold start, when nothing is known about the receiver clock. The wide Doppler range covers an oscillator that may be well off frequency, at the cost of a higher threshold because more cells are searched.

./gps_print.py --device /dev/sdr0 --gain 40 --ms 150 --doppler 25000

The everyday case, once the clock is known to be close. A narrower search is more sensitive rather than merely quicker, because the threshold is computed from the number of cells: fewer cells give noise fewer chances, so the bar comes down.

./gps_print.py --device /dev/sdr0 --gain 40 --ms 150 --doppler 6000 --step 250

One group of satellites at a time. Searching eight codes instead of thirty two cuts the cell count by four, which lowers the bar again, and is how a satellite that hovers at the threshold can be confirmed rather than argued about.

./gps_print.py --device /dev/sdr0 --gain 40 --ms 150 --prn 9,10,11,12,13,14,15,16

Acquisition on its own. The position step downloads the current almanac, so this is the form to use on a machine with no route to the internet, or when only the detection matters.

./gps_print.py --device /dev/sdr0 --gain 40 --ms 150 --no-locate

No radio at all. The code generator is checked against the published first ten chips of all 32 codes, and the search is run against a manufactured signal of known strength, so this says whether the program is intact without needing an antenna.

./gps_print.py --self-test

Example 5 - decoding the navigation message

Acquisition finds a satellite and stops. It says a code is present, at a Doppler and a code phase, and that is enough to place the receiver within a hundred kilometres. It never reads what the satellite is saying, because reading it needs something acquisition does not do: following the signal.

Test Setup

This is an example in the tutorial that needs an antenna of its own, cabled to an RX port on the board. You can use the same test setup as in previous example

How to Run

One correlation against a fixed code and carrier guess stays good for 150 ms. Over 90 seconds it does not, because the code slides and the carrier drifts, so the replicas have to be steered continuously. gps_decode.py closes two loops once per millisecond to do that, a delay lock loop on the code and a Costas loop on the carrier. Once the prompt correlator holds lock, its in phase output is the 50 bit per second data stream, one bit spread over 20 code periods, and the rest is framing rather than signal processing: find which of the 20 millisecond phases the bit edges fall on, find the 8 bit preamble that opens every subframe, check the parity on each 30 bit word, and read the fields.

./gps_decode.py --device /dev/sdr0 --gain 40 --seconds 90

A subframe is 300 bits, so six seconds, and the ephemeris that describes one satellite orbit is spread over subframes 1, 2 and 3. Thirty seconds of unbroken lock is therefore the minimum before a satellite can be used at all, and 90 seconds is chosen so that a satellite whose loops slip once still has another run at it.

gps_decode.py - GPS L1 C/A tracking and navigation message decode
  centre        : 1575.420 MHz
  sample rate   : 3.840 Msps
  gain          : 40 dB
  capture       : 90 s (2.76 GB in memory)
  captured 345600000 samples (90.0 s) in 90.0 s, timeouts 0, overflows 0
  window 0 at   0.0 s : 28 31 32 25
  window 1 at  29.9 s : 28 31 32 16 25 26
  window 2 at  59.9 s : 28 32 16 31
  found in some windows but not all: 25 16 26

  acquired 6 satellite(s) in 33.5 s (bar 1.60)
  PRNs          : 28 31 32 25 16 26

  ======== PRN 28 (acq C/N0 38.8 dB-Hz, Doppler -1750 Hz) ========
  fine Doppler  : -1769.8 Hz (acquisition said -1750)
  tracked 89997 ms in 14.8 s, lock indicator above 0.5 for 94% of it
  bit sync      : phase 1/20 ms, 100% of edges on that boundary
  bits          : 4499 at 50 bps
  subframes     : 14 passed preamble and parity
    bit     54  subframe 3  TOW 69613 (417672 s of week)  parity 10/10
    bit    354  subframe 4  TOW 69614 (417678 s of week)  parity 10/10
    bit    654  subframe 5  TOW 69615 (417684 s of week)  parity 10/10
    bit    954  subframe 1  TOW 69616 (417690 s of week)  parity 10/10
    bit   1254  subframe 2  TOW 69617 (417696 s of week)  parity 10/10
              [ nine more subframes, every one 10/10 ]

  --- decoded from PRN 28 ---
    GPS week        : 388 (mod 1024)
    SV health       : 0 (healthy)
    URA index       : 0
    IODC            : 134
    toc             : 424800 s
    af0 af1 af2     : -4.111580e-04 1.068656e-11 0.000000e+00
    Tgd             : -9.313226e-09 s
    sqrt(A)         : 5153.654444 -> a = 26560.154 km
    eccentricity    : 0.000497829
    M0              : 168.494263 deg
    delta n         : 2.734146e-07 deg/s
    toe             : 424800 s
    IODE (sf2)      : 134
    orbital period  : 11.966 h (GPS sits near 11.967)
    i0              : 55.141489 deg
    OMEGA0          : 152.956529 deg
    omega           : -4.788851 deg
    OMEGADOT        : -4.552135e-07 deg/s
    IODE (sf3)      : 134

              [ PRN 31, 32, 25, 16 and 26 follow in the same form ]

  ================ position ================
  satellites with a complete ephemeris : 5 of 6 tracked
    PRN 26 unusable: no subframe anchor
  common receive instant : sample 172794191 (45.00 s into the capture)
  week 388, and the ranges that instant gives:
    PRN 16  transmit 417715.910719039 s of week  (  +2.895 ms of spread)
    PRN 25  transmit 417715.907824324 s of week  (  +0.000 ms of spread)
    PRN 28  transmit 417715.916783913 s of week  (  +8.960 ms of spread)
    PRN 31  transmit 417715.920455254 s of week  ( +12.631 ms of spread)
    PRN 32  transmit 417715.912470479 s of week  (  +4.646 ms of spread)
  ionosphere       : NOT corrected, no page 18 in this capture
  troposphere      : standard atmosphere model

  --- fix ---
  latitude         :  45.323414 N
  longitude        :  75.932116 W
  height           :       58.4 m above the ellipsoid
  ECEF             : 1091911.7 -4357418.6 4512733.3 m
  receiver clock   : +8.161425 ms off GPS time
  residual rms     : 2.2 m over 5 satellites

  per satellite, at the solved position:
    PRN   elevation   ionosphere   troposphere
    16       24.5 deg      0.00 m        5.80 m
    25       15.5 deg      0.00 m        9.03 m
    28       56.7 deg      0.00 m        2.88 m
    31       79.3 deg      0.00 m        2.45 m
    32       32.8 deg      0.00 m        4.44 m
  HDOP 1.7  VDOP 1.8  PDOP 2.5  TDOP 1.4

  --- address ---
  looked up at openstreetmap.org, which is told the position above
  ****, ******, Kanata, Kanata North, Ottawa, Eastern Ontario, Ontario, K2T 0G6, Canada

The acquisition step searches three places in the capture rather than one. A satellite sitting near the threshold is not reliably there or absent: whether it clears the bar depends on which slice of noise it is measured against, and the line reporting 25, 16 and 26 as found in some windows but not all is that effect being named. The capture is ninety seconds long and only 150 ms of it was ever being looked at, so the rest is free evidence. Anything found late is then pinned down again at the start, where tracking begins, by a search over one code and a handful of Doppler bins; far fewer cells allow a far lower bar for the same false alarm rate.

Parity is what makes the decode trustworthy rather than plausible. Each 30 bit word carries six bits of a Hamming code computed over the previous word's last two bits as well as its own data, so a word that reads 10/10 is not merely well formed, it is consistent with the word before it. The TOW values climbing by exactly one every subframe, and agreeing across satellites that share nothing but the sky, is the same evidence from another direction.

The orbit fields can be checked against physics without trusting the program. A semi-major axis of 26560 km and a period of 11.966 hours are the GPS constellation as designed, an inclination near 55 degrees is the nominal value, and the IODE appearing identically in subframes 2 and 3 says both halves of the ephemeris came from the same upload.

The position is no longer a Doppler estimate. The ephemeris gives each satellite's position to metres, and the message gives the time it was sent: the TOW pins the subframe to a six second boundary, the bit index within it gives 20 ms, the code period count gives 1 ms, and the tracked code phase gives the sub-millisecond remainder. Every satellite is timed against the same sample clock, so the differences between those transmit times are range differences, and four unknowns come out of them, three of position and one of time. The receiver clock is 8.16 ms from GPS time, which is why it has to be solved for rather than assumed.

Judge the result by the geometry rather than the residual. HDOP 1.7 and PDOP 2.5 describe a good spread of satellites across the sky, and a height of 58 m is plausible for Ottawa. A fix from exactly four satellites is worth much less: with four unknowns and four measurements the residual is near zero whatever the answer, so it stops being evidence, and the program says so when that happens. The same run with a poorly placed antenna gave four usable satellites, PDOP 9.6 and a height of -242 m, which is the arithmetic working correctly on geometry that cannot support it.

The ionosphere column reads zero here because the coefficients that model it are broadcast in page 18 of subframe 4, and subframe 4 cycles through 25 pages at one page per 30 second frame, so that page comes round every 12.5 minutes and a 90 second capture usually misses it. When a capture does catch it the program prints the eight coefficients and a --iono line to reuse them, which is the practical route: they stay valid for hours. The troposphere needs nothing from the satellites, because the dry part follows from pressure and pressure follows from height, so it is always applied and runs from 2.45 m straight up to 9 m at 15 degrees of elevation.

How the code works

gps_decode.py is larger than the others, but it is a pipeline rather than a tangle: each stage turns one representation into the next, and nothing reaches back. It imports the code generator and the search from gps_print.py rather than repeating them.

samples        capture()            read the whole run, then release the card
               as_complex()         read it back, wide floats or byte pairs
                    |
                    v
seeds          acquire_all()        search several windows, keep the union
               reacquire()          pin a late find back to the start
               refine_doppler()     sharpen it to a few Hz before the loops
                    |
                    v
correlator     track()              two loops, closed once per millisecond,
                                    for the whole capture.  Returns the
                                    prompt output and when each code period
                                    arrived
                    |
                    v
bits           bit_sync()           which of 20 phases the bit edges fall on
               to_bits()            sum each 20 ms into one bit
                    |
                    v
words          find_subframes()     the 8 bit preamble, both polarities
               parity()             the Hamming check, IS-GPS-200 20.3.5
                    |
                    v
fields         parse_how()          time of week and subframe number
               parse_sf1/2/3()      clock correction and ephemeris
               parse_sf4_page18()   ionosphere coefficients, when caught
                    |
                    v
position       sat_state()          where a satellite was, and its clock error
               tx_time_at()         transmit time at one receiver instant
               klobuchar(), tropo()  atmosphere
               solve_fix()          least squares for x, y, z and time
               dops(), ecef_to_llh() geometry, and degrees
                    |
                    v
address        reverse_geocode()    the only call that leaves the machine

Everything before track() exists to give it a starting point, and everything after it is bookkeeping on what it produced. The loop below is the program. It runs once per code period, which is once per millisecond, for the length of the capture. Most of the comments and the test that ends it at the end of the capture are taken out here for space; everything else is as it stands in the file.

    for m in range(nms):
        cps = code_freq / rate                      # chips per sample
        nsamp = int(math.ceil((CA_CHIPS - rem) / cps))
        epoch[m] = pos - rem / cps
        blk = as_complex(x, pos, pos + nsamp)
        pos += nsamp

        k = np.arange(nsamp)
        idx = rem + k * cps
        ph = carr_phase + 2.0 * np.pi * carr_freq * k / rate
        mixed = blk * np.exp(-1j * ph)
        carr_phase = (ph[-1] + 2.0 * np.pi * carr_freq / rate) % (2.0 * np.pi)

        e = code[np.int32(np.floor(idx - spacing)) + 1]
        p = code[np.int32(np.floor(idx)) + 1]
        l = code[np.int32(np.floor(idx + spacing)) + 1]
        rem = idx[-1] + cps - CA_CHIPS

        mr, mi = mixed.real, mixed.imag
        IE, QE = float(np.dot(mr, e)), float(np.dot(mi, e))
        IP, QP = float(np.dot(mr, p)), float(np.dot(mi, p))
        IL, QL = float(np.dot(mr, l)), float(np.dot(mi, l))

        # Costas: the arctangent of Q over I is blind to a 180 degree flip,
        # so the data bits do not drag the loop off.
        carr_err = math.atan(QP / IP) / (2.0 * math.pi) if IP != 0.0 else 0.0
        carr_nco = (old_carr_nco + (tau2p / tau1p) * (carr_err - old_carr_err)
                    + carr_err * (T / tau1p))
        old_carr_err, old_carr_nco = carr_err, carr_nco
        carr_freq = doppler + carr_nco

        eA = math.hypot(IE, QE)
        lA = math.hypot(IL, QL)
        code_err = (eA - lA) / (eA + lA) if (eA + lA) > 0.0 else 0.0
        code_nco = (old_code_nco + (tau2c / tau1c) * (code_err - old_code_err)
                    + code_err * (T / tau1c))
        old_code_err, old_code_nco = code_err, code_nco
        code_freq = CA_RATE * (1.0 + carr_freq / L1) - code_nco

        ip[m], qp[m] = IP, QP
        lock[m] = (IP * IP - QP * QP) / (IP * IP + QP * QP + 1e-30)

Three replicas of the code are correlated rather than one. The prompt replica carries the data; the early and late ones sit half a chip either side and exist only to say which way the alignment is drifting, because the correlation peak is symmetric and the prompt output alone cannot tell early from late. Their difference over their sum is the delay error, and it is fed back into the chip rate.

The sign of that feedback is the one thing in the loop that cannot be reasoned about loosely. Early is the replica held back half a chip, which makes the difference negative when the local code lags, and that is what turns the subtraction on the last line into negative feedback. Building early the other way round produces a loop that runs the replica away from the signal at exactly the rate it should be closing on it, and the symptom is not an obvious failure: the correlation power simply decays over the first second and then sits at a fifth of its proper value.

The carrier loop uses the arctangent of Q over I rather than the angle of the full complex value. A data bit inverts the signal every 20 ms, and a discriminator that could see 360 degrees would read each inversion as a phase error of half a turn and chase it. The arctangent wraps at 180 degrees, so it is blind to exactly the thing the data does. The price is that the polarity of the recovered bit stream is unknown, and the parity check absorbs that for free: it is computed against the previous word's last two bits, which invert along with everything else.

The line recording epoch[m] is what later makes a range possible. It is the sample index at which that code period began, kept fractional on purpose, because one chip is 293 m and rounding to the nearest sample would put hundreds of metres into the answer. Every satellite in the capture is measured against the same sample clock, so the differences between their transmit times are range differences, and that is the whole of what solve_fix() is given.

Usage examples

The capture length is the setting that matters most. The ephemeris needs thirty seconds of unbroken lock from each satellite, so a run that is too short does not produce a worse fix, it produces no fix at all.

The default. Forty seconds is the least that is sure to carry subframes 1, 2 and 3, which is what a satellite needs before it can be used at all.

./gps_decode.py --device /dev/sdr0 --gain 40

The one to prefer. Ninety seconds gives a satellite whose loops slip once another run at the same three subframes, which is usually the difference between four satellites and six, and four is the number that leaves no redundancy at all.

./gps_decode.py --device /dev/sdr0 --gain 40 --seconds 90

Keep the samples. Tracking and decoding are pure arithmetic on the capture, so saving it means every later question can be asked again without the radio, and without waiting for the satellites to be in the same place.

./gps_decode.py --device /dev/sdr0 --gain 40 --seconds 90 --int8 --save /root/gps_now.i8

That capture again, offline. --int8 is needed on the way back in as well, because it says how the file is laid out. Byte pairs are a quarter the size of two floats and cost nothing that matters, since the signal is far below the noise either way.

./gps_decode.py --load /root/gps_now.i8 --int8

Reuse ionosphere coefficients decoded earlier. Page 18 of subframe 4 comes round only every 12.5 minutes, so most captures miss it, but the values stay good for hours and the program prints this line ready to paste whenever it does catch one. The eight numbers are one argument, so the list must not be broken across a continuation: the backslash collapses to a space and the shell would hand over two.

./gps_decode.py --load /root/gps_now.i8 --int8 --iono 1.21e-8,1.49e-8,-5.96e-8,-1.19e-7,9.63e4,8.19e4,-1.97e5,-3.93e5

A full cycle of subframe 4, which is certain to contain page 18. Thirteen minutes is a long time to hold the board, so this is a run to make once when the bench is otherwise idle; byte pairs keep it to about three gigabytes.

./gps_decode.py --device /dev/sdr0 --gain 40 --seconds 780 --int8 --prn 32,25 --no-locate

The quickest form, and the two ways to stop early. One acquisition window is what gps_print.py effectively does and is enough when signals are strong; --no-locate stops after the message, and --no-address keeps the solved position on the machine by skipping the only lookup that leaves it.

./gps_decode.py --device /dev/sdr0 --gain 40 --acq-windows 1

./gps_decode.py --device /dev/sdr0 --gain 40 --no-locate

./gps_decode.py --device /dev/sdr0 --gain 40 --no-address

Example 6 - Generating GPS Signal with Navigation message

Example 5 reads a signal from the sky, so its answer can only be judged as plausible. This example goes the other way. gps_generate.py builds a GPS L1 C/A signal from a scenario file, with a navigation message that gps_decode.py can read. The scenario says where the receiver is and at what time. The answer is known before the signal exists, so an error of ten metres shows up as ten metres.

Each step in the generator is the inverse of one step in gps_decode.py. The almanac picks the satellites and gives their orbits. The orbits are packed into subframes with parity. For each satellite, the light time to the receiver sets the code delay and the Doppler. The signal is code times data times carrier, summed over the satellites, plus noise. It goes into a file, or out of TX0 of a board.

Test Setup

Building a scenario into a file needs no board at all. Tests 1 to 3 below only write and read files. They need access to the internet, because the scenario fetches the almanac. Test 4 and the transmitting usage examples need the setup below.

One Amarisoft PC with two SDR boards in it. A single coax runs from TX0 on the first board, sdr0, to RX0 on the second board, sdr1. gps_generate.py transmits on sdr0, and gps_decode.py receives on sdr1 as a separate program. No gNB runs in this test.

Two boards are needed because a board is opened exclusively. On one board, transmitting and receiving would have to run in a single program. With two boards each program opens its own. With a cable from a board back to itself, use --mode loopback so that gps_generate.py does the recording.

(NOTE : Keep the cable. On a cable between TX0 and RX0 this is a conducted test and nothing leaves the bench. Into an antenna it is a real GPS transmitter. That is illegal without a licence in most of the world, and it pulls in every GPS receiver in range. The scenario files keep tx_gain at 20 for that reason.)

Coax from TX0 on sdr0 to RX0 on sdr1 inside one Amarisoft PC

How to Run

Everything about a run is in the scenario file. gps-gen-kanata.yaml places the receiver at 45.323414, -75.932116 and 58 m above the ellipsoid. That is the fix the sky gave on this bench. The file is shown below without its header comment.

# The cable runs sdr0 TX0 -> sdr1 RX0.  Two boards matter: a board is opened
# exclusively, so transmitting and receiving on the same one forces both into
# a single program.  On two boards gps_decode.py can listen live on its own.
#
# tx_device is used by  mode: tx  and  mode: loopback.
# rx_device and signal.rx_gain are used by  mode: loopback  ONLY, which is the
# case where this program records as well as transmits.  In  mode: tx  the
# receiving is gps_decode.py --device /dev/sdr1 and these two are ignored.
tx_device: /dev/sdr0    # the cable leaves here
rx_device: /dev/sdr1    # and arrives here (loopback only)
rate: 3.84e6            # gps_decode.py assumes this; both ends must agree
freq: 1575.42e6         # L1

position:
  lat: 45.323414        # the fix the sky gave, to within its own scatter
  lon: -75.932116
  alt: 58.0             # metres above the ellipsoid, not above sea level

time:
  mode: now             # now | fixed
  # week: 2436          # used only when mode is fixed
  # tow: 417715

satellites:
  mode: auto            # auto picks the highest ones the almanac puts up
  count: 6              # four is the minimum and leaves no redundancy
  mask: 10              # degrees of elevation, below which they are ignored
  almanac: fetch        # fetch, or a path to a local YUMA file
  # list: [28, 31, 32, 25, 16, 29]   # name them instead of choosing by height

atmosphere:
  # gps_decode.py always removes a tropospheric delay, and removes an
  # ionospheric one whenever the message carries the coefficients.  Leaving
  # these out of the signal does not make the test cleaner, it just moves the
  # answer by the size of the correction the receiver applies anyway.
  troposphere: true
  ionosphere: true

signal:
  seconds: 90           # 30 s of unbroken lock per satellite is the floor,
                        # and 90 gives a slipped one another run at it
  cn0: 45               # dB-Hz per satellite; the sky gives 33 to 42 here
  rms: 0.10             # full scale is 1.0, so this leaves room for peaks
  tx_gain: 20           # LOW ON PURPOSE.  This is a cable, not an antenna.
  rx_gain: 40           # loopback only; gps_decode.py sets its own gain

output:
  mode: tx              # file | tx | loopback
                        #   file     build a capture, no radio at all
                        #   tx       transmit; run gps_decode.py on rx_device
                        #   loopback transmit and record here, one program
  path: /root/gps_sim.c64
  int8: false           # byte pairs instead of two floats, a quarter the size

time mode now builds the signal for the current GPS time. Set mode fixed with week and tow to repeat an exact moment. satellites mode auto takes the count highest satellites that the almanac puts above mask degrees of elevation. Use list to name the PRNs instead.

atmosphere puts the tropospheric and ionospheric delays into the signal. gps_decode.py always removes a tropospheric delay. It removes an ionospheric one whenever the message carries the coefficients. A signal built without them decodes several metres out, through no fault of the receiver.

cn0 is the level of each satellite in dB-Hz. 45 is stronger than the 33 to 42 the sky gives here. rate has to stay at 3.84e6, because gps_decode.py assumes it. output.mode picks file, tx or loopback. The command line options --mode, --seconds, --out, --cn0 and --tx-gain override the file without editing it.

< Test 1 > Building a scenario into a file

The command below builds 45 seconds of signal and writes it to /root/gps_sim.c64. No board is opened. --mode file and --seconds 45 override the values in the scenario file.

cd /root/soapy_project/python

./gps_generate.py --config gps-gen-kanata.yaml --mode file --seconds 45 --out /root/gps_sim.c64

gps_generate.py - a GPS L1 C/A scenario, built to be decoded
  scenario      : gps-gen-kanata.yaml
  receiver      : 45.323414, -75.932116, 58.0 m
  time          : GPS week 2436, 424476 s of week (10 subframes)
  satellites    : 6
    PRN 16  elevation  81.4 deg
    PRN 4   elevation  62.8 deg
    PRN 26  elevation  60.0 deg
    PRN 31  elevation  41.9 deg
    PRN 9   elevation  30.2 deg
    PRN 27  elevation  27.3 deg
  atmosphere    : troposphere on, ionosphere on
  signal        : 45 s at 3.840 Msps, C/N0 45 dB-Hz
    PRN 16 done (1 of 6)
    PRN 4  done (2 of 6)
    PRN 26 done (3 of 6)
    PRN 31 done (4 of 6)
    PRN 9  done (5 of 6)
    PRN 27 done (6 of 6)
  built 172800000 samples in 86.0 s, rms 0.100, peak 0.433
  wrote /root/gps_sim.c64 (1.38 GB)

  decode it with:
    ./gps_decode.py --load /root/gps_sim.c64 --seconds 45
  and the fix should come back at 45.323414, -75.932116

The generator picked six satellites, from PRN 16 at 81.4 degrees down to PRN 27 at 27.3 degrees. The time is GPS week 2436, 424476 s of week. It is rounded down to a subframe boundary, so the code epoch and the bit edge both start at zero.

45 seconds at 3.84 Msps is 172800000 samples. At two 32 bit floats per sample, that is 1.38 GB. The build took 86.0 s, about twice real time. The signal is scaled to an rms of 0.100. The peak is 0.433, well below the full scale of 1.0, so nothing clips on transmit. The last lines give the command to decode the file and the position it should return.

< Test 2 > Decoding the file

gps_decode.py reads the file with --load in place of a board. --acq-windows 1 runs a single acquisition window, which is enough for a signal this strong. The decode of PRN 4 is shown in full below. The other five satellites decode the same way and are left out here, up to the position.

./gps_decode.py --load /root/gps_sim.c64 --acq-windows 1

gps_decode.py - GPS L1 C/A tracking and navigation message decode
  loaded        : /root/gps_sim.c64, 172800000 samples (45.0 s at 3.84 Msps)

  acquired 6 satellite(s) in 11.1 s (bar 1.60)
  PRNs          : 4 16 31 26 9 27

  ======== PRN 4 (acq C/N0 44.2 dB-Hz, Doppler +1250 Hz) ========
  fine Doppler  : +1149.5 Hz (acquisition said +1250)
  tracked 44997 ms in 7.6 s, lock indicator above 0.5 for 100% of it
  bit sync      : phase 9/20 ms, 100% of edges on that boundary
  bits          : 2249 at 50 bps
  subframes     : 7 passed preamble and parity
    bit      3  subframe 1  TOW 70747 (424476 s of week)  parity 9/10
    bit    303  subframe 2  TOW 70748 (424482 s of week)  parity 10/10
    bit    603  subframe 3  TOW 70749 (424488 s of week)  parity 10/10
    bit    903  subframe 4  TOW 70750 (424494 s of week)  parity 10/10
    *** subframe 4 page 18: ionosphere and UTC ***
      alpha : 1.210719e-08,1.490116e-08,-5.960464e-08,-1.192093e-07
      beta  : 9.625600e+04,8.192000e+04,-1.966080e+05,-3.932160e+05
      leap seconds (GPS ahead of UTC) : 18
      reuse on another capture with:
        --iono 1.210719e-08,1.490116e-08,-5.960464e-08,-1.192093e-07,9.625600e+04,8.192000e+04,-1.966080e+05,-3.932160e+05
    bit   1203  subframe 5  TOW 70751 (424500 s of week)  parity 10/10
    bit   1503  subframe 1  TOW 70752 (424506 s of week)  parity 10/10
    bit   1803  subframe 2  TOW 70753 (424512 s of week)  parity 10/10

  --- decoded from PRN 4 ---
    GPS week        : 388 (mod 1024)
    SV health       : 0 (healthy)
    URA index       : 0
    IODC            : 0
    toc             : 424464 s
    af0 af1 af2     : 0.000000e+00 0.000000e+00 0.000000e+00
    Tgd             : 0.000000e+00 s
    sqrt(A)         : 5153.615234 -> a = 26559.750 km
    eccentricity    : 0.003969193
    M0              : -76.989042 deg
    delta n         : 0.000000e+00 deg/s
    toe             : 424464 s
    IODE (sf2)      : 0
    orbital period  : 11.966 h (GPS sits near 11.967)
    i0              : 55.725197 deg
    OMEGA0          : 96.526330 deg
    omega           : -166.901786 deg
    OMEGADOT        : -4.433241e-07 deg/s
    IODE (sf3)      : 0

       ... PRN 16, 31, 26, 9 and 27 decode the same way ...

  ================ position ================
  satellites with a complete ephemeris : 6 of 6 tracked
  common receive instant : sample 86393741 (22.50 s into the capture)
  week 388, and the ranges that instant gives:
    PRN 4   transmit 424498.429283550 s of week  (  +6.884 ms of spread)
    PRN 9   transmit 424498.422681630 s of week  (  +0.282 ms of spread)
    PRN 16  transmit 424498.432197555 s of week  (  +9.798 ms of spread)
    PRN 26  transmit 424498.429521141 s of week  (  +7.122 ms of spread)
    PRN 27  transmit 424498.422399430 s of week  (  +0.000 ms of spread)
    PRN 31  transmit 424498.425587554 s of week  (  +3.188 ms of spread)
  ionosphere       : broadcast coefficients, subframe 4 page 18
  troposphere      : standard atmosphere model

  --- fix ---
  latitude         :  45.323519 N
  longitude        :  75.931995 W
  height           :       65.3 m above the ellipsoid
  ECEF             : 1091920.0 -4357412.9 4512746.5 m
  receiver clock   : +8.827416 ms off GPS time
  residual rms     : 1.2 m over 6 satellites

  per satellite, at the solved position:
    PRN   elevation   ionosphere   troposphere
    4        62.9 deg      3.42 m        2.70 m
    9        30.3 deg      5.20 m        4.77 m
    16       81.6 deg      3.18 m        2.43 m
    26       59.9 deg      3.36 m        2.78 m
    27       27.5 deg      6.43 m        5.22 m
    31       41.8 deg      4.25 m        3.61 m
  HDOP 1.4  VDOP 2.1  PDOP 2.5  TDOP 1.6

  --- address ---
  looked up at openstreetmap.org, which is told the position above
  1109, Tischart Crescent, Kanata, Kanata North, Ottawa, Eastern Ontario, Ontario, K2T 0G6, Canada

    street         : 1109 Tischart Crescent
    neighbourhood  : Kanata
    district       : Kanata North
    city           : Ottawa
    province       : Ontario
    postcode       : K2T 0G6
    country        : Canada

                     latitude      longitude      height
  scenario said       45.323414     -75.932116       58.0 m
  decoder returned    45.323519     -75.931995       65.3 m
  difference            11.7 m N        9.5 m E       7.3 m

  horizontal error  15.0 m

All six satellites are acquired, at 43.4 to 44.2 dB-Hz against the 45 that was built. Each one tracks for the full 44997 ms with the lock indicator above 0.5 all the time. Every subframe passes parity 10/10 except the first one, at 9/10. Its first word has no previous word to take D29 and D30 from.

Subframe 4 carries page 18 in every frame here. A real satellite sends it once in 25 frames. Sending it every frame lets a 45 second file exercise the ionosphere correction at all. No real satellite does this.

The orbit fields are the ones the almanac gave. sqrt(A) of 5153.615234 gives a = 26559.750 km and a period of 11.966 h. Several fields read zero: af0, af1, af2, Tgd, delta n and IODE. That is the generator, not the receiver. The almanac carries no clock polynomial and no orbit corrections, so those fields are zero in the message that was sent.

The fix lands 15.0 m from the scenario horizontally and 7.3 m out in height. The residual is 1.2 m over six satellites, with HDOP 1.4 and PDOP 2.5. Repeat runs land between about 6 and 15 m. That spread comes from the receiver. The fix interpolates a single code epoch, and a few hundredths of a chip of delay lock jitter is already metres of range.

< Test 3 > Moving the receiver to the Eiffel Tower

Only the scenario file changes. gps-gen-eiffel-tower.yaml sets the receiver at 48.858370, 2.294481 and 77.0 m. The almanac is asked what is above Paris at that moment, so the satellite set changes as well. PRN 18 appears here and not in the Kanata run.

This test is stronger than Test 1. A decode that lands near the bench could in principle be the real sky leaking in. A decode in Paris cannot be, because the satellites above Paris are not the ones above Ottawa. Whatever the decoder reads, it reads from the file. The output below shows the build, then the position part of the decode.

./gps_generate.py --config gps-gen-eiffel-tower.yaml --mode file --seconds 45

./gps_decode.py --load /root/gps_sim_eiffel.c64 --acq-windows 1

gps_generate.py - a GPS L1 C/A scenario, built to be decoded
  scenario      : gps-gen-eiffel-tower.yaml
  receiver      : 48.858370, 2.294481, 77.0 m
  time          : GPS week 2436, 425340 s of week (10 subframes)
  satellites    : 6
    PRN 26  elevation  60.3 deg
    PRN 18  elevation  54.7 deg
    PRN 29  elevation  53.8 deg
    PRN 31  elevation  53.5 deg
    PRN 28  elevation  38.4 deg
    PRN 16  elevation  26.2 deg
  atmosphere    : troposphere on, ionosphere on
  signal        : 45 s at 3.840 Msps, C/N0 45 dB-Hz
    PRN 26 done (1 of 6)
    PRN 18 done (2 of 6)
    PRN 29 done (3 of 6)
    PRN 31 done (4 of 6)
    PRN 28 done (5 of 6)
    PRN 16 done (6 of 6)
  built 172800000 samples in 86.9 s, rms 0.100, peak 0.432
  wrote /root/gps_sim_eiffel.c64 (1.38 GB)

  decode it with:
    ./gps_decode.py --load /root/gps_sim_eiffel.c64 --seconds 45
  and the fix should come back at 48.858370, 2.294481

       ... gps_decode.py: six satellites acquired and decoded, as in Test 2 ...

  ================ position ================
  satellites with a complete ephemeris : 6 of 6 tracked
  common receive instant : sample 86395123 (22.50 s into the capture)
  week 388, and the ranges that instant gives:
    PRN 16  transmit 425362.422976114 s of week  (  +0.000 ms of spread)
    PRN 18  transmit 425362.427808228 s of week  (  +4.832 ms of spread)
    PRN 26  transmit 425362.429867920 s of week  (  +6.892 ms of spread)
    PRN 28  transmit 425362.424870307 s of week  (  +1.894 ms of spread)
    PRN 29  transmit 425362.428247679 s of week  (  +5.272 ms of spread)
    PRN 31  transmit 425362.428204811 s of week  (  +5.229 ms of spread)
  ionosphere       : broadcast coefficients, subframe 4 page 18
  troposphere      : standard atmosphere model

  --- fix ---
  latitude         :  48.858339 N
  longitude        :   2.294299 E
  height           :       99.0 m above the ellipsoid
  ECEF             : 4201006.6 168311.1 4780283.2 m
  receiver clock   : +6.138096 ms off GPS time
  residual rms     : 0.6 m over 6 satellites

  per satellite, at the solved position:
    PRN   elevation   ionosphere   troposphere
    16       26.3 deg      2.85 m        5.40 m
    18       54.9 deg      1.77 m        2.93 m
    26       60.4 deg      1.67 m        2.75 m
    28       38.3 deg      2.27 m        3.87 m
    29       53.6 deg      1.80 m        2.97 m
    31       53.4 deg      1.80 m        2.99 m
  HDOP 1.4  VDOP 3.3  PDOP 3.6  TDOP 2.5

  --- address ---
  looked up at openstreetmap.org, which is told the position above
  Buffets, 5, Avenue Anatole France, Quartier du Gros-Caillou,
  Paris 7e Arrondissement, Paris, Īle-de-France, 75007, France

    street         : 5 Avenue Anatole France
    neighbourhood  : Paris 7e Arrondissement
    district       : Paris
    city           : Paris
    province       : Īle-de-France
    postcode       : 75007
    country        : France

                     latitude      longitude      height
  scenario said       48.858370       2.294481       77.0 m
  decoder returned    48.858339       2.294299       99.0 m
  difference            -3.4 m N      -13.4 m E      22.0 m

  horizontal error  13.8 m

The fix lands 13.8 m from the scenario. The address lookup returns 5 Avenue Anatole France in Paris, the street address of the Eiffel Tower. OpenStreetMap knows nothing about this bench or this signal, so the address is an independent check.

The height is 22.0 m out. VDOP is 3.3 against an HDOP of 1.4, because every satellite is above the receiver and none is below it. The residual is only 0.6 m, so the six ranges agree with each other closely. A low residual with a larger height error is geometry, not a measurement fault.

< Test 4 > Transmitting on sdr0 and receiving on sdr1

This is the whole path through hardware. The Eiffel Tower scenario is played out of TX0 on sdr0. gps_decode.py listens on sdr1 at the same time, in a second terminal. --mode tx builds the signal and then transmits it. --repeat 0 sends it again and again until control C, and each pass prints when it starts.

In the run recorded here, the two boards were linked by two antennas over a short distance, not by a cable. That is why --tx-gain is 90, which the board clamps to 89.75 dB, and why the receiver gain is 60. Do not repeat it that way. On the cable, use the tx_gain of 20 from the scenario file and --gain 40 on the receiver.

./gps_generate.py --config gps-gen-eiffel-tower.yaml --mode tx --repeat 0 --seconds 90 --tx-gain 90

./gps_decode.py --device /dev/sdr1 --gain 60 --seconds 60

terminal 1, transmitting until control C:

gps_generate.py - a GPS L1 C/A scenario, built to be decoded
  scenario      : gps-gen-eiffel-tower.yaml
  transmitting  : /dev/sdr0
  receiver      : 48.858370, 2.294481, 77.0 m
  time          : GPS week 2436, 429348 s of week (17 subframes)
  satellites    : 6
    PRN 26  elevation  76.8 deg
    PRN 18  elevation  67.0 deg
    PRN 16  elevation  55.7 deg
    PRN 27  elevation  29.4 deg
    PRN 31  elevation  28.4 deg
    PRN 29  elevation  26.3 deg
  atmosphere    : troposphere on, ionosphere on
  signal        : 90 s at 3.840 Msps, C/N0 45 dB-Hz
    PRN 26 done (1 of 6)
       ... the other five build the same way ...
    PRN 29 done (6 of 6)
  built 345600000 samples in 173.8 s, rms 0.100, peak 0.435

  Sending the scenario over and over until control C.
  [WARNING] SoapyAmarisoft: TX gain 90.00 dB clamped to 89.75 dB
  pass 1 starts at +0.0 s, runs 90 s
  pass 2 starts at +90.0 s, runs 90 s
  pass 3 starts at +180.0 s, runs 90 s
       ... continues until control C ...

terminal 2, receiving on the other board while it transmits:

gps_decode.py - GPS L1 C/A tracking and navigation message decode
  centre        : 1575.420 MHz
  sample rate   : 3.840 Msps
  gain          : 60 dB
  capture       : 60 s (1.84 GB in memory)
  captured 230400000 samples (60.0 s) in 60.0 s, timeouts 0, overflows 0
  window 0 at   0.0 s : 31 26 29 18 16 27
  window 1 at  19.9 s : 31 29 18 16 26 27
  window 2 at  39.9 s : 18 31 29 26 16 27

  acquired 6 satellite(s) in 32.8 s (bar 1.60)
  PRNs          : 31 26 29 18 16 27

  ======== PRN 31 (acq C/N0 43.0 dB-Hz, Doppler -750 Hz) ========
  fine Doppler  : -758.1 Hz (acquisition said -750)
  tracked 59997 ms in 9.5 s, lock indicator above 0.5 for 97% of it
  bit sync      : phase 11/20 ms, 100% of edges on that boundary
  bits          : 2999 at 50 bps
  subframes     : 9 passed preamble and parity
    bit     53  subframe 4  TOW 71562 (429366 s of week)  parity 10/10
    *** subframe 4 page 18: ionosphere and UTC ***
      alpha : 1.210719e-08,1.490116e-08,-5.960464e-08,-1.192093e-07
      beta  : 9.625600e+04,8.192000e+04,-1.966080e+05,-3.932160e+05
      leap seconds (GPS ahead of UTC) : 18
    bit    353  subframe 5  TOW 71563 (429372 s of week)  parity 10/10
    bit    653  subframe 1  TOW 71564 (429378 s of week)  parity 10/10
    bit    953  subframe 2  TOW 71565 (429384 s of week)  parity 10/10
    bit   1253  subframe 3  TOW 71566 (429390 s of week)  parity 10/10
    bit   1553  subframe 4  TOW 71567 (429396 s of week)  parity 10/10
    bit   1853  subframe 5  TOW 71568 (429402 s of week)  parity 10/10
    bit   2153  subframe 1  TOW 71569 (429408 s of week)  parity 10/10
    bit   2453  subframe 2  TOW 71570 (429414 s of week)  parity 10/10

  --- decoded from PRN 31 ---
    GPS week        : 388 (mod 1024)
    SV health       : 0 (healthy)
    sqrt(A)         : 5153.606445 -> a = 26559.659 km
    eccentricity    : 0.011100292
    M0              : 116.765332 deg
    toe             : 429344 s
    orbital period  : 11.966 h (GPS sits near 11.967)
    i0              : 54.732307 deg
    OMEGA0          : 155.664103 deg
    omega           : 57.994123 deg
    OMEGADOT        : -4.446338e-07 deg/s

       ... PRN 26, 29, 18, 16 and 27 follow, each 9 subframes at 10/10,
           each carrying the same page 18, at 42.1 to 42.7 dB-Hz ...

  ================ position ================
  satellites with a complete ephemeris : 6 of 6 tracked
  common receive instant : sample 115193357 (30.00 s into the capture)
  week 388, and the ranges that instant gives:
    PRN 16  transmit 429394.934804152 s of week  (  +7.892 ms of spread)
    PRN 18  transmit 429394.934847434 s of week  (  +7.935 ms of spread)
    PRN 26  transmit 429394.936244551 s of week  (  +9.332 ms of spread)
    PRN 27  transmit 429394.929079105 s of week  (  +2.167 ms of spread)
    PRN 29  transmit 429394.926992710 s of week  (  +0.080 ms of spread)
    PRN 31  transmit 429394.926912446 s of week  (  +0.000 ms of spread)
  ionosphere       : broadcast coefficients, subframe 4 page 18
  troposphere      : standard atmosphere model

  --- fix ---
  latitude         :  48.858313 N
  longitude        :   2.294421 E
  height           :       86.8 m above the ellipsoid
  ECEF             : 4201000.4 168319.9 4780272.1 m
  receiver clock   : +7.309018 ms off GPS time
  residual rms     : 3.4 m over 6 satellites

  per satellite, at the solved position:
    PRN   elevation   ionosphere   troposphere
    16       56.0 deg      1.75 m        2.89 m
    18       66.9 deg      1.59 m        2.61 m
    26       76.6 deg      1.53 m        2.47 m
    27       29.7 deg      2.66 m        4.84 m
    29       26.0 deg      2.87 m        5.47 m
    31       28.1 deg      2.76 m        5.10 m
  HDOP 1.5  VDOP 1.9  PDOP 2.4  TDOP 1.4

  --- address ---
  5, Avenue Anatole France, Quartier du Gros-Caillou,
  Paris 7e Arrondissement, Paris, Ile-de-France, 75007, France

    street         : 5 Avenue Anatole France
    neighbourhood  : Paris 7e Arrondissement
    city           : Paris
    province       : Ile-de-France
    postcode       : 75007
    country        : France

                     latitude      longitude      height
  scenario said       48.858370       2.294481       77.0 m
  decoder returned    48.858313       2.294421       86.8 m
  difference            -6.3 m N       -4.4 m E       9.8 m

  horizontal error  7.7 m

  address           5 Avenue Anatole France, 75007 Paris, France

The 90 s scenario takes 173.8 s to build before the first pass starts. Start the receiver after that, just after a pass begins. Each pass restarts the scenario, and the satellites and the time of week jump back with it. A capture that crosses a restart decodes to a wrong answer, and nothing in the output says so. Keep the receiver's --seconds below the 90 s of a pass. Here the 60 s capture fits inside one pass.

All six satellites decode nine subframes each at parity 10/10, at 42.1 to 43.0 dB-Hz. The fix lands 7.7 m from the scenario and resolves to the same street address. Two boards also mean two oscillators. The receiving board is free to be slightly off the transmitting one. That lands as a Doppler shared by every satellite. The position solve has a term for it, the same as for a real receiver clock.

How the code works

gps_generate.py reuses gps_decode.py for everything the two have in common. The orbit model, the troposphere and Klobuchar models and the subframe parsers are imported from it. The C/A code comes from gps_print.py, and the almanac from gps_predict.py. The generator adds only the encoding and the signal.

almanac        fetch_almanac()          which satellites are up (gps_predict.py)
               ephemeris_from_almanac() the same orbits, as message fields
                    |
                    v
message        sf1_bits() .. sf3_bits() the ephemeris, scaled and packed
               sf4_page18_bits()        ionosphere and UTC, in every frame
               decode_back()            read it back, build from what was sent
               encode_word()            24 data bits in, 30 out, with parity
               nav_bits()               the whole message as +1 and -1
                    |
                    v
propagation    light_time()             when the signal left the satellite
                    |
                    v
baseband       generate()               code x data x carrier, summed, plus noise
                    |
                    v
output         tofile()                 mode file: a .c64 capture
               transmit()               mode tx and loopback: out of TX0

decode_back() is the step that is easy to leave out. Every field is rounded on the way into the message. sqrt(A) lands on a multiple of 2^-19, and the mean anomaly on a multiple of 2^-31 semicircles. A receiver can only recover those rounded values. The signal is therefore built from the fields read back out of the subframes, not from the almanac values. The orbit in the signal is then exactly the orbit in the message.

encode_word() is the inverse of the parity check in gps_decode.py. The pairing of D29* and D30* across the six equations has to match the decoder exactly. A mistake there is nearly invisible in testing. Words 2 and 10 end in two zeros, and every word after one of them checks out either way.

The loop below is the inner part of generate(). It runs once per satellite, one second of samples at a time. Some comments are shortened here for space. Everything else is as it stands in the file.

    for si, (prn, eph) in enumerate(sats):
        code = ca_code(prn)
        taus = np.empty(ngrid)
        for i in range(ngrid):
            taus[i], _ = light_time(eph, rx, float(tg[i]), iono,
                                    tropo_on, iono_on)
        data = eph["_nav"]

        for a in range(0, n, chunk):
            b = min(a + chunk, n)
            k = np.arange(a, b)
            t_rel = k / rate
            tau = np.interp(t_rel, (tg - t0), taus)

            # Transmit time, relative to a start that is a whole number of
            # subframes, so the code epoch and the bit boundary both fall at
            # zero and nothing large has to be reduced modulo anything small.
            ttx = t_rel - tau

            chips = ttx * CA_RATE
            ci = np.mod(chips, CA_CHIPS).astype(np.int32)
            bi = np.floor(ttx / (MS_PER_BIT * 1e-3)).astype(np.int64)
            np.clip(bi, 0, len(data) - 1, out=bi)

            # Carrier phase is minus the delay in cycles of L1.  Only the
            # fraction of a cycle carries anything, so it is reduced before
            # the exponential; the whole number of cycles is thrown away.
            cyc = -L1 * tau
            frac = cyc - np.floor(cyc)
            out[a:b] += (amp * code[ci] * data[bi]) * np.exp(2j * np.pi * frac)
        if not quiet:
            print("    PRN %-2d done (%d of %d)" % (prn, si + 1, len(sats)))

The delay is not solved per sample. light_time() runs on a 20 ms grid, and np.interp fills in the samples between. The delay is a smooth function of time, so a straight line over 20 ms is wrong by nanometres. Solving it per sample would cost a Kepler iteration per sample for nothing.

Code, data and carrier all come from that one delay. ttx is the transmit time of each sample. It sets the chip index ci and the bit index bi, so the code phase and the bit edge cannot disagree. The carrier phase is minus the delay in cycles of L1. Only the fraction of a cycle matters, so the whole cycles are dropped before np.exp. The Doppler comes out of the changing delay, with no separate frequency term.

amp sets the level. It is the square root of 10^(cn0/10) divided by the rate, against noise of unit variance. That is how cn0 in the scenario becomes a C/N0 in dB-Hz. The noise is added after all the satellites, in place and a second at a time. A long run then never holds two copies of the signal.

Usage examples

The mode is the setting that matters most. file builds a capture and needs no board. tx transmits and leaves the receiving to gps_decode.py. loopback transmits and records in the same program. The examples that transmit assume the cable from TX0 on sdr0 to RX0 on sdr1.

Build a capture and decode it. No radio is involved at either end.

./gps_generate.py --config gps-gen-kanata.yaml --mode file

./gps_decode.py --load /root/gps_sim.c64

Transmit once on sdr0 and receive live on sdr1, in two terminals. The scenario is sent once, for its 90 s. Once the signal is built, the generator prints the receiver command to use.

./gps_generate.py --config gps-gen-kanata.yaml --mode tx

./gps_decode.py --device /dev/sdr1 --gain 40 --seconds 90

Keep transmitting until control C. The receiver can then be started at any time. Start it just after a pass begins, so its capture does not cross a restart.

./gps_generate.py --config gps-gen-kanata.yaml --mode tx --repeat 0

./gps_decode.py --device /dev/sdr1 --gain 40 --seconds 60

The same cable, driven from one program. loopback transmits on sdr0 and records sdr1 itself, so there is no timing between two terminals. The capture is written to output.path, ready for --load.

./gps_generate.py --config gps-gen-kanata.yaml --mode loopback --tx-device /dev/sdr0 --rx-device /dev/sdr1

./gps_decode.py --load /root/gps_sim.c64

A cable from a board back to itself. Only one program can hold that board, so the generator has to do the recording. loopback is the only mode that works here.

./gps_generate.py --config gps-gen-kanata.yaml --mode loopback --tx-device /dev/sdr0 --rx-device /dev/sdr0

Override the scenario without editing it. --seconds and --cn0 each replace one value from the file. The run below is shorter and stronger than the scenario says.

./gps_generate.py --config gps-gen-kanata.yaml --seconds 40 --cn0 50

Installing/Uninstalling soapy_project package

You can install all the package and examples for this tutorial refering to this tutorial.

Directory Structure

Everything in this tutorial lives in one directory inside the soapy_project tree described in the SoapySDR tutorial. Nothing here is compiled, so there is no build directory and nothing that has to be rebuilt when the tree is moved.

/root/soapy_project/python/
  +-- rx_minimal.py             the minimal receiver
  +-- detect_ssb.py             the SSB detector as first written
  +-- detect_ssb_fast.py        the same detector, holding real time
  +-- plot_spectrum.py          averaged spectrum, drawn with matplotlib
  +-- gps_print.py              GPS L1 C/A acquisition, and a Doppler position
  +-- gps_predict.py            what the almanac says should be overhead
  +-- gps_decode.py             tracking, navigation message, and a real fix
  +-- run_tests.sh              checks the programs

Needed on the system, beyond the soapy_project prerequisites:

  python3-SoapySDR              [MANDATORY] the SWIG bindings, 0.7.1 here
  python3-numpy                 [MANDATORY] the detectors are written in it
  python3-matplotlib            plot_spectrum.py only
  /usr/local/lib64/SoapySDR/modules0.7/libamarisoftSupport.so
                                [MANDATORY] the module, unchanged from
                                the SoapySDR tutorial

The bindings are architecture specific and version specific, so a machine with a different Python or a different SoapySDR needs its own python3-SoapySDR rather than a copy of this one. That is what the package manager is for, and it is the one respect in which the Python side is easier than the Octave side.