Skip to content

Python specific

Thomas Nipen edited this page May 11, 2022 · 2 revisions

This page contains python-specific information for using titanlib.

After installing the package, titanlib can be loaded with import titanlib. There are no submodules in titanlib, so all functions are accessed with titanlib.<function>. Read the header file documentation to see available functions. All functions available in the C++ library are also made available in python, with the same function signature. For example, the C++ function:

vec2 range_check(const vec &values, const vec &min, const vec& max)

can be used in python as follows:

>>> import titanlib
>>> titanlib.range_check([-20, 11, 2], [-15], [10])
array([1, 0, 1], dtype=int32)

Input data types

The SWIG interface does type checking and casting when required, and the following types can be used:

C++ type Python types
float Any scalar
int Any scalar
vec 1D np.array, list, tuple
vec2 2D np.array, list of lists, tuple of tuples
ivec 1D np.array, list, tuple

For best performance, use numpy arrays since these already store their data sequentially in C. Using tuples or lists incurr a significant conversion penalty for large datasets.

All python vectors are automatically converted to C++ floats when passed to C++ functions that expect floats. Python vectors are automatically converted to C++ ints when passed to C++ functions that expect ints. This means you can pass numpy arrays of any numeric dtype, such as float32, float64, int32. However, arrays with dtypes of float32 and int32 are ideal, since then no conversion from (for example) float64 is made.

Output data types

When arrays are returned from the C++ function back to python, they are converted to numpy arrays either of dtype float32 or int32 depending on the output type on the C++ side.

Setup for examples

To get ready for the examples in the next sections, run the code below to set up necessary variables (you will also need the test datasets). This retrieves air temperature and precipitation from the observation, analysis, and forecast files as well as metadata about the stations.

import titanlib
import netCDF4
import numpy as np

with netCDF4.Dataset('obs.nc', 'r') as file:
    lats = file.variables['latitude'][:, 0]
    lons = file.variables['longitude'][:, 0]
    points = titanlib.Points(lats, lons)
    temp_obs = file.variables['air_temperature_2m'][:]
    precip_obs = file.variables['precipitation_amount'][:]