Introduction to pyshtools¶

pyshtools is a Python package that provides functions for working with spherical harmonics. These routines can be used to perform spherical harmonic transforms and reconstructions, rotations of data expressed in spherical harmonics, and multitaper spectral analyses on the sphere. The base functions are fast routines written in Fortran 95 from the SHTOOLS package. pyshtools provides easy access to these routines by use of Python-wrapper functions and a compact class interface.

To get started, import the standard matplotlib library for graphics, numpy for mathematical extensions to Python, and pyshtools:

In [1]:
%matplotlib inline
from __future__ import print_function # only necessary if using Python 2.x

import matplotlib.pyplot as plt
import numpy as np
import pyshtools


The pyshtools package contains the three classes SHCoeffs, SHGrid, and SHWindow, a subpackage shtools that contains the Python-wrapped Fortran functions, and a series of subpackages that contain both native python routines and refernces to routines in shtools (constant, legendre, expand, shio, spectralanalysis, rotate, gravmag, and util). The classes SHCoeffs, SHGrid, and SHWindow bundle the vast majority of pyshtools functionality, and in this notebook we will demonstrate how to use the classes related to grids and coefficients.

Grid and Coefficient classes¶

Let's start by first creating a power spectrum (i.e., the total power per degree) that follows a power law with exponent -2, up to and including degree 100. To avoid a division by zero, we will set the degree 0 term to zero:

In [2]:
degrees = np.arange(101, dtype=float)
degrees[0] = np.inf
power = degrees**(-2)


Next, we will create a random realization of spherical harmonic coefficients whose expected power is given by the spectrum we just created:

In [3]:
clm = pyshtools.SHCoeffs.from_random(power)


This creates a new class instance of SHCoeffs that contains several attributes and methods. By default, pyshtools assumes that the coefficients are real and that they are normalized using the '4pi' convention exlcuding the Condon-Shortley phase factor. This is the standard normalization in Geodesy and many fields of geophysics and spectral analysis. Other normalization can be specified explicitly by specifying the optional parameter normalization, which can be either '4pi', 'ortho', or 'schmidt'. The Condon-Shortley phase can be included by setting the optional parameter csphase to -1, and if you wanted complex coefficients, you could set kind='complex'.

from_random() is just one way to create a set of spherical harmonic coefficients. The other constructor methods are from_file() to read the coefficients from a shtools or npy formatted file, from_zeros() if you just want all the coefficients to be set to zero, and from_array() if you already have a numpy array of the coefficients.

Next, let's calculate the power spectrum and plot it. pyshtools provides a built in plotting function to do this, and as we will see below, the power spectrum can also be returned as a numpy array using the spectrum() method.

In [4]:
fig, ax = clm.plot_spectrum()


By default, this method plots the power in units of power per spherical harmonic degree (per_l), but you can also choose from the average power per coefficient as a function of spherical harmonic degree (per_lm) and the power per log bandwith (per_dlogl). You can visualize the power asociated with each spherical-harmonic coefficient using the plot_spectrum2d() method. In this example, we use the optional parameter vrange to scale the colormap from 1 to 1.e-7 times the maximum value.

In [5]:
fig, ax = clm.plot_spectrum2d(vrange=(1.e-7,1))


The spherical harmonic coefficients of a given SHCoeffs class instance can be converted easily to a different normalization using the convert() method. Here, we will convert the coeffients to the orthonormalized convention using the Condon-Shortley phase, which is common in many fields of physics and seismology. Also, let's just return the first 50 degrees of the function:

In [6]:
clm_ortho = clm.convert(normalization='ortho', csphase=-1, lmax=50)


If you ever forget how your data are normalized, you can use the built in info() method to remind you:

In [7]:
clm_ortho.info()

kind = 'real'
normalization = 'ortho'
csphase = -1
lmax = 50


We will next calculate the power spectra of our two functions and plot them along with our theoretical input spectrum:

In [8]:
fix, ax = plt.subplots(1,1)
ax.plot(clm.degrees(), power, '-k',
clm.degrees(), clm.spectrum(), '-r',
clm_ortho.degrees(), clm_ortho.spectrum(), '-b')
ax.set(yscale='log', xlabel='degree', ylabel='power')

Out[8]:
[None,
<matplotlib.text.Text at 0x10ccce978>,
<matplotlib.text.Text at 0x10cbf4320>]

The method degrees() was here used to return a numpy list of the degrees from 0 up to the maximum value of the coefficients. As you can see, the power spectrum of the random realization follows closely the input spectrum. Furthermore, the power spectra are seen to be independent of the chosen normalization.

Next, let's expand the data onto a grid and plot it. We first use the expand() method, which returns a new instance of the class SHGrid, and then plot the data using the built in method plot():

In [9]:
grid = clm.expand()
fig, ax = grid.plot()


When expanding data onto a grid, pyshtools provides three options. The default is to use grid='DH', which is an equally-sampled grid in latitude and longitude that conforms to Driscoll and Healy's (1994) sampling theorem. If you would like a grid that is oversampled in longitude by a factor or two, such that the number of longitude bands is twice that as the number of latitude bands, use grid='DH2' instead.

The third grid is constructed explicitly for use with Gauss-Legendre quadrature integration techniques. This grid contains about half as many latitude bands as an equivalent DH grid, but the latitudes are unequally sampled at the zeros of the Legendre polynomial of the maximum degree of the coefficients. The following commands show how to expand the spherical harmonic coefficents onto a GLQ grid, plot it, and output lists that contain the latitudes and longitudes (in degrees) for each row and column of the grid:

In [10]:
grid_glq = clm.expand(grid='GLQ')
grid_glq.plot()

lats = grid_glq.lats()
lons = grid_glq.lons()


If you ever forget how your grid was constructed, the info() method provides you with everything you need to know:

In [11]:
grid_glq.info()

kind = 'real'
grid = 'GLQ'
nlat = 101
nlon = 201
lmax = 100

In [12]:
grid.info()

kind = 'real'
grid = 'DH'
sampling = 1
nlat = 202
nlon = 202
lmax = 100


Sometimes you need to set individual spherical harmonic coefficients to a specified value. For example, for planetary topography, the degree 2 order 0 term can be atypically large as a result of the planet's rotation. Let's set this term equal to zero and replot it using an over-sampled DH grid. Though we will modify only a single coefficient here, you could also provide input arrays for l, m, and value. When using the set_coeffs() method, you set the cosine terms using positive values for the orders, and the sine terms using negative orders:

In [13]:
l = 2
m = 0
value = 0.

clm.set_coeffs(value, l, m)
grid_dh2 = clm.expand(grid='DH2')
fig, ax = grid_dh2.plot()
grid_dh2.info()

kind = 'real'
grid = 'DH'
sampling = 2
nlat = 202
nlon = 404
lmax = 100


If you want to save either the raw spherical harmonic coefficients to a file, or save the raw gridded data to a file, this can be done using the to_file() methods. If you want to extract the grid or coefficients as a numpy array, this can be done using the to_array() methods. Here, we will just extract the first few degrees of the spherical harmonic coefficients and verify that the coefficient was indeed set to zero:

In [14]:
coeffs = clm.to_array(lmax=4)
print(coeffs, end='\n\n')
print('c20 = {:f}'.format(coeffs[0,2,0]))

[[[ 0.          0.          0.          0.          0.        ]
[ 0.30287897  0.58429869  0.          0.          0.        ]
[ 0.         -0.17180174  0.13787514  0.          0.        ]
[-0.06050388  0.18306407  0.32657189 -0.02626378  0.        ]
[ 0.04834463  0.03530989  0.06574564  0.08903334  0.16478558]]

[[ 0.          0.          0.          0.          0.        ]
[ 0.         -0.63394991  0.          0.          0.        ]
[ 0.          0.28599939 -0.133225    0.          0.        ]
[ 0.         -0.06098247  0.06807531 -0.05889034  0.        ]
[ 0.          0.07136584  0.07161084 -0.04363804  0.02928771]]]

c20 = 0.000000


Calculating the spherical harmonic coefficients of a grid is as easy as expanding the coefficients onto a grid:

In [15]:
clm_new = grid_dh2.expand()


If you need to evaluate the spherical harmonic coefficients at a specific set of points, this can also be accomplished using the expand() method. All that needs to be done is to provide a list or numpy array of the latitude and longitude coordinates:

In [16]:
clm.expand(lat=[90., 10., -45., -90.], lon=[0., 90., 275., 0.])

Out[16]:
[0.3363420143090495,
-0.027557642307597163,
2.4238854219950854,
-0.07174671114853237]

It is also easy to rotate either the physical body or the underlying coordinate frame of the function expressed in spherical harmonics. This is accomplished using three Euler angles, alpha, beta and gamma. There are many different conventions for these angles, so please read the documentation before doing this blindly! Here, we will rotate the point at the north pole to 60 degrees north latitude and 180 degrees east longitude:

In [17]:
clat = 60.
clon = 180.

alpha = 0.
beta = -(90.-clat)
gamma = -clon

clm_rotated = clm.rotate(alpha, beta, gamma, degrees=True)
grid_rotated = clm_rotated.expand()
fig, ax = grid_rotated.plot()