Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/PRBEM/IRBEM/llms.txt

Use this file to discover all available pages before exploring further.

The IRBEM Python wrapper exposes the full Fortran library through two high-level classes, MagFields and Coords, both found in python/IRBEM/IRBEM.py. Under the hood, Python’s built-in ctypes module loads the compiled shared object (libirbem.so on Linux/macOS, libirbem.dll on Windows) and marshals all arguments and return values between Python types and the Fortran ABI. You never call the Fortran subroutines directly — the classes handle all array sizing, type conversion, and output packaging for you.

Installation

1

Compile the Fortran source

Follow the instructions in README.install at the top of the IRBEM repository to build the shared library. After a successful build you should find a file named libirbem.so (Linux/macOS) or libirbem.dll (Windows) in the top-level IRBEM directory.
# From the IRBEM root
make
Verify the shared object was created before continuing:
ls libirbem.so    # Linux / macOS
2

Install the Python package

Change into the python/ subdirectory and install with pip. A system-wide install requires sudo; use --user to install for the current user only.
cd python/

# System-wide
sudo python3 -m pip install -e .

# Current user only
python3 -m pip install --user -e .
The package requires Python ≥ 3.6 and the following dependencies (installed automatically): numpy >= 1.12, scipy >= 0.14, python-dateutil, and wheel. The optional pandas package is supported but not required.
3

Verify the installation

Run one of the provided test and visualisation scripts to confirm everything is working end-to-end:
python3 python/*test_and_visualizations.py
If the wrapper raises "Either none or multiple .so files found in the sources folder!" check that exactly one libirbem.so file exists in the IRBEM root before the Python package directory is searched.
The Python wrapper is developed and tested on Linux and Python versions greater than 3.6. Windows users can run the wrapper through the Windows Subsystem for Linux (WSL).

The two classes

ClassPurpose
MagFieldsMagnetic coordinates, field tracing, drift shells, mirror points, and foot points
CoordsCoordinate system transformations (GDZ, GEO, GSM, GSE, SM, GEI, MAG, SPH, RLL)

MagFields

MagFields wraps IRBEM’s magnetic field subroutines. All configuration (field model, coordinate system, options) is supplied once at construction time and shared across every subsequent method call.

Constructor

import IRBEM

model = IRBEM.MagFields(
    kext='OPQ77',
    sysaxes=0,
    options=[0, 0, 0, 0, 0],
    verbose=False,
)
path
str | pathlib.Path
Explicit path to the compiled shared object (libirbem.so or libirbem.dll). When omitted, the wrapper searches for the shared object in the top-level IRBEM directory automatically.
kext
int | str
default:"5 ('OPQ77')"
The external magnetic field model. Accepts either the integer index or the corresponding string name from the lookup table below.
IndexStringModel
0'None'No external field
1'MF75'Mead–Fairfield 1975
2'TS87'Tsyganenko 1987 (Stern & Tsyganenko)
3'TL87'Tsyganenko–Longo 1987
4'T89'Tsyganenko 1989
5'OPQ77'Olson–Pfitzer Quiet 1977
6'OPD88'Olson–Pfitzer Dynamic 1988
7'T96'Tsyganenko 1996
8'OM97'Ostapenko–Maltsev 1997
9'T01'Tsyganenko 2001
10'T01S'Tsyganenko 2001 (storm)
11'T04'Tsyganenko–Sitnov 2004
12'A00'Alexeev 2000
13'T07'Tsyganenko–Sitnov 2007
14'MT'Mead–Tsyganenko
sysaxes
int
default:"0"
Input coordinate system. 0 = GDZ (altitude km, latitude °, East longitude °). See the coordinate system table in the Coords section for all available values.
options
list[int]
default:"[0, 0, 0, 0, 0]"
A list of five integers controlling optional computations. Refer to the IRBEM HTML documentation for the full option descriptions. A common choice is [1, 0, 0, 0, 0] to enable L* computation.
verbose
bool
default:"False"
When True, prints a status message before each Fortran call. Useful for debugging silent crashes caused by type mismatches at the Fortran boundary.

Input dictionaries

Every MagFields method accepts two dictionaries: X for the spacecraft position and time, and maginput for the magnetic field model driving parameters.

X — position and time

X = {
    'x1': 651.0,                     # first coordinate in sysaxes
    'x2': 63.0,                      # second coordinate in sysaxes
    'x3': 20.0,                      # third coordinate in sysaxes
    'dateTime': '2015-02-02T06:12:43',  # ISO-8601 string or datetime object
}
For sysaxes=0 (GDZ), x1 is altitude in km, x2 is geodetic latitude in degrees, and x3 is East longitude in degrees. The dateTime value may be an ISO-8601 string, a datetime.datetime object, or a pandas.Timestamp.

maginput — model driving parameters

maginput = {
    'Kp':    40.0,   # Kp × 10 (so Kp=4 → 40)
    'Dst':   -20.0,  # Dst index (nT)
    'dens':  5.0,    # solar wind density (cm⁻³)
    'velo':  400.0,  # solar wind velocity (km/s)
    'Pdyn':  2.0,    # solar wind dynamic pressure (nPa)
    'ByIMF': 0.0,    # IMF By GSM (nT)
    'BzIMF': -5.0,   # IMF Bz GSM (nT)
    'G1':    0.0,    # Tsyganenko G1 parameter
    'G2':    0.0,    # Tsyganenko G2 parameter
    'G3':    0.0,    # Tsyganenko G3 parameter
    'W1':    0.0,    # Tsyganenko W1 parameter
    'W2':    0.0,    # Tsyganenko W2 parameter
    'W3':    0.0,    # Tsyganenko W3 parameter
    'W4':    0.0,    # Tsyganenko W4 parameter
    'W5':    0.0,    # Tsyganenko W5 parameter
    'W6':    0.0,    # Tsyganenko W6 parameter
    'AL':    0.0,    # AL index (nT)
}
You only need to supply the keys required by your chosen external field model. Keys that are omitted default to the Fortran error sentinel value (-9999). Values may be scalars (int, float) or arrays/lists of equal length for multi-point calls.
The Python wrapper uses -9999 as its error sentinel. The underlying Fortran library uses -1×10³¹; the wrapper converts between the two automatically. Any output field returning -9999 indicates that IRBEM could not compute a valid result for that point.

Methods

make_lstar(X, maginput)

Computes magnetic coordinates at the spacecraft position: McIlwain L shell, L*, local field magnitude, minimum field magnitude, the second adiabatic invariant integral J, and magnetic local time.
output = model.make_lstar(X, maginput)
# output keys: 'Lm', 'MLT', 'blocal', 'bmin', 'Lstar', 'xj'
Returns dict with keys:
KeyDescription
LmMcIlwain L shell
MLTMagnetic local time (hours)
blocalLocal magnetic field magnitude (nT)
bminMinimum field on the field line (nT)
LstarRoederer L* (drift shell)
xjIntegral invariant J (related to second adiabatic invariant)

drift_shell(X, maginput)

Traces a complete drift shell for a particle whose mirror point is at the input location. Returns the positions of all 48 field lines that make up the shell.
output = model.drift_shell(X, maginput)
# output keys: 'Lm', 'lstar', 'blocal', 'bmin', 'xj', 'POSIT', 'Nposit'
Returns dict with keys:
KeyDescription
LmMcIlwain L shell (scalar)
lstarL* / drift shell parameter (scalar)
blocalLocal B array, shape (48, 1000)
bminMinimum B on shell (scalar, nT)
xjIntegral invariant J (scalar)
POSITGEO Cartesian positions, shape (48, 1000, 3)
NpositNumber of valid points per field line, shape (48,)

drift_bounce_orbit(X, maginput, alpha=90, R0=1)

Traces a complete drift-bounce orbit for a particle with a specified local pitch angle. Returns 25 azimuths (vs. 48 for drift_shell) and only positions between the mirror points.
output = model.drift_bounce_orbit(X, maginput, alpha=45, R0=1)
# output keys: 'Lm', 'lstar', 'blocal', 'bmin', 'bmirr', 'xj',
#              'POSIT', 'Nposit', 'hmin', 'hmin_lon'
alpha
float
default:"90"
Local pitch angle in degrees.
R0
float
default:"1"
Minimum radial distance allowed along the drift path, in units of Earth radii. Use R0 < 1 to work inside the drift loss cone.
Returns dict — same keys as drift_shell plus:
KeyDescription
bmirrMirror field magnitude (nT)
hminAltitude of the minimum-altitude point along the orbit (km)
hmin_lonEast longitude (GDZ °) of the minimum-altitude point

find_mirror_point(X, maginput, alpha)

Finds the magnitude and GEO location of the mirror point along the field line passing through X for a given local pitch angle.
output = model.find_mirror_point(X, maginput, alpha=30.0)
# output keys: 'blocal', 'bmin', 'POSIT'
alpha
float
required
Local pitch angle in degrees.
Returns dict:
KeyDescription
blocalLocal field magnitude at input point (nT)
bminField magnitude at the mirror point (nT)
POSITGEO Cartesian coordinates of the mirror point, shape (3,)

find_foot_point(X, maginput, stopAlt, hemiFlag)

Traces the field line from X to find where it crosses the altitude stopAlt in the chosen hemisphere.
output = model.find_foot_point(X, maginput, stopAlt=100.0, hemiFlag=1)
# output keys: 'XFOOT', 'BFOOT', 'BFOOTMAG'
stopAlt
float
required
Target footprint altitude above Earth’s surface in kilometres.
hemiFlag
int
required
Hemisphere selection:
  • 0 — same magnetic hemisphere as the starting point
  • +1 — northern magnetic hemisphere
  • -1 — southern magnetic hemisphere
  • +2 — opposite magnetic hemisphere to the starting point
Returns dict:
KeyDescription
XFOOTFootprint location in GDZ coordinates [alt_km, lat_deg, lon_deg]
BFOOTMagnetic field vector at footprint in GEO coordinates (nT)
BFOOTMAGMagnetic field magnitude at footprint (nT)

trace_field_line(X, maginput, R0=1)

Traces the complete field line that passes through X down to a reference sphere of radius R0.
output = model.trace_field_line(X, maginput, R0=1)
# output keys: 'POSIT', 'Nposit', 'lm', 'blocal', 'bmin', 'xj'
R0
float
default:"1"
Radius of the reference surface in Earth radii. The field line is traced until it reaches this radius in both hemispheres.
Returns dict:
KeyDescription
POSITGEO Cartesian positions along the line, shape (Nposit, 3)
NpositTotal number of traced points
lmMcIlwain L shell
blocalLocal B magnitude at each point, shape (Nposit,)
bminMinimum B on the field line (nT)
xjIntegral invariant J

find_magequator(X, maginput)

Traces the field line from X and returns the coordinates and field magnitude at the magnetic equator (where |B| is minimum).
output = model.find_magequator(X, maginput)
# output keys: 'bmin', 'XGEO'
Returns dict:
KeyDescription
bminField magnitude at the magnetic equator (nT)
XGEOGEO Cartesian coordinates of the magnetic equator, shape (3,)

get_field_multi(X, maginput)

Computes the full GEO magnetic field vector and magnitude at one or more input locations.
output = model.get_field_multi(X, maginput)
# output keys: 'BxGEO', 'ByGEO', 'BzGEO', 'Bl'
Returns dict:
KeyDescription
BxGEOX component of the field in GEO coordinates (nT)
ByGEOY component of the field in GEO coordinates (nT)
BzGEOZ component of the field in GEO coordinates (nT)
BlTotal field magnitude (nT)

get_mlt(X)

Returns the Magnetic Local Time (MLT) from a Cartesian GEO position and date. Unlike most other methods, X must supply GEO Cartesian coordinates regardless of the sysaxes set at construction.
mlt = model.get_mlt(X)  # returns float (hours)
Returns float — MLT in hours (0–24).

bounce_period(X, maginput, E, Erest=511, R0=1, alpha=90, interpNum=100000)

Calculates the bounce period for a particle with kinetic energy E in an arbitrary magnetic field model. This method is not a direct IRBEM Fortran call; it uses trace_field_line and numerical integration.
Tb = model.bounce_period(X, maginput, E=500.0)        # electron, 500 keV → seconds
Tb = model.bounce_period(X, maginput, E=[100, 500, 1000])  # array of energies
E
float | list | np.ndarray
required
Particle kinetic energy in keV. A single value or an array.
Erest
float
default:"511"
Particle rest energy in keV. Default is the electron rest mass (511 keV). Change this to compute bounce periods for other species.
R0
float
default:"1"
Reference surface radius in Earth radii.
alpha
float
default:"90"
Local pitch angle in degrees.
interpNum
int
default:"100000"
Number of interpolation samples along the field line. Larger values improve accuracy at the cost of speed.
Returns float or np.ndarray — bounce period(s) in seconds.

mirror_point_altitude(X, maginput, R0=1)

Calculates the mirror point altitude for locally mirroring particles in the opposite hemisphere. Complements find_mirror_point, which works in the same hemisphere.
alt_km = model.mirror_point_altitude(X, maginput, R0=1)  # returns float
R0
float
default:"1"
Reference surface radius in Earth radii.
Returns float — mirror point altitude in km.

Coords

Coords wraps IRBEM’s coordinate transformation subroutines. It shares the same path and verbose constructor keyword arguments as MagFields but has no kext, sysaxes, or options — coordinate transforms do not depend on a magnetic field model.

Constructor

coords = IRBEM.Coords()                          # auto-detect shared object
coords = IRBEM.Coords(path='/path/to/libirbem.so')  # explicit path
coords = IRBEM.Coords(verbose=True)

transform(time, pos, sysaxesIn, sysaxesOut)

Transforms one or more position vectors from one coordinate system to another.
import datetime
import IRBEM

coords = IRBEM.Coords()

t = datetime.datetime(2015, 2, 2, 6, 12, 43)
pos_gdz = [651.0, 63.0, 20.0]   # altitude km, lat °, lon °

# Single point: GDZ → GEO
pos_geo = coords.transform(t, pos_gdz, 'GDZ', 'GEO')
print(pos_geo)   # GEO Cartesian in Re

# Multiple points
import numpy as np
times = [datetime.datetime(2015, 2, 2, 6, i, 0) for i in range(5)]
positions = [[651 + i*10, 63.0, 20.0] for i in range(5)]
pos_gsm = coords.transform(times, positions, 'GDZ', 'GSM')
print(pos_gsm.shape)   # (5, 3)
time
datetime.datetime | list[datetime.datetime] | list[str]
required
One datetime or a list/array of datetimes (or ISO-8601 strings) at which the positions are defined.
pos
array-like
required
Position vector(s). For a single point pass a list of 3 values; for multiple points pass an (N, 3) array-like.
sysaxesIn
int | str
required
Source coordinate system (integer index or 3-letter string).
sysaxesOut
int | str
required
Target coordinate system (integer index or 3-letter string).
Available coordinate systems:
IndexCodeDescription
0GDZGeodetic: altitude (km), latitude (°), East longitude (°)
1GEOGeographic Cartesian (Re)
2GSMGeocentric Solar Magnetospheric Cartesian (Re)
3GSEGeocentric Solar Ecliptic Cartesian (Re)
4SMSolar Magnetic Cartesian (Re)
5GEIGeocentric Equatorial Inertial Cartesian (Re)
6MAGGeomagnetic Cartesian (Re)
7SPHGeographic Spherical: radial distance (Re), latitude (°), East longitude (°)
8RLLRadial distance (Re), latitude (°), East longitude (°) — preferred over SPH
Returns np.ndarray — transformed positions. Shape (3,) for a single point, (N, 3) for multiple points.
Coords.coords_transform() is a deprecated alias for Coords.transform(). Use transform() in all new code.

Full working example

import datetime
import IRBEM

# --- MagFields: compute L* for a single spacecraft position ---
model = IRBEM.MagFields(kext='OPQ77', sysaxes=0, options=[1, 0, 0, 0, 0])

X = {
    'x1': 651.0,                      # altitude, km
    'x2': 63.0,                       # geodetic latitude, deg
    'x3': 20.0,                       # East longitude, deg
    'dateTime': '2015-02-02T06:12:43',
}
maginput = {'Kp': 40.0}   # Kp = 4.0

result = model.make_lstar(X, maginput)
print(f"L*    = {result['Lstar'][0]:.4f}")
print(f"Lm    = {result['Lm'][0]:.4f}")
print(f"MLT   = {result['MLT'][0]:.2f} h")
print(f"Bmin  = {result['bmin'][0]:.2f} nT")
print(f"Blocal= {result['blocal'][0]:.2f} nT")
print(f"xj    = {result['xj'][0]:.4f}")

# --- Coords: transform GDZ → GSM ---
coords = IRBEM.Coords()
t = datetime.datetime(2015, 2, 2, 6, 12, 43)
pos_gsm = coords.transform(t, [651.0, 63.0, 20.0], 'GDZ', 'GSM')
print(f"GSM position (Re): {pos_gsm[0]}")

Build docs developers (and LLMs) love