SHTns 3.7
sht_rot.py

Shows how to perform arbitrary rotations of spherical harmonic fields; optionally displays the fields as 3D plots.

Shows how to perform arbitrary rotations of spherical harmonic fields; optionally displays the fields as 3D plots.

1
2from pylab import *
3import shtns
4
5Lmax = 13 # degree of fields to rotate. Note that arbitrary rotations require Mmax=Lmax
6
7sh = shtns.sht(Lmax) # Spherical Harmonic transform object
8rot = shtns.rotation(Lmax) # corresponding rotation object
9
10
11# Define the rotation:
12alpha = pi/2
13beta = pi/2
14gamma = 0
15rot.set_angles_ZYZ(alpha, beta, gamma) # defines rotation by giving Euler angles (alpha, beta, gamma), around axes Z,Y and Z respectively.
16# or alternatively:
17# rot.set_angles_ZXZ(alpha, beta, gamma) # same, but around axes Z, X and Z
18# rot.set_angle_axis(theta, Vx, Vy, Vz) # same, but rotation of angle "theta" around vector (Vx,Vy,Vz)
19
20
22
23
24Qlm = sh.spec_array() # empty spectral field
25Qlm[1] = 1. # a value somewhere
26
27Rlm = rot.apply_real(Qlm) # Rlm is the field Qlm rotated by the rotation defined above.
28print('rotated by (%g,%g,%g) degrees (ZYZ)' % (rot.alpha*180/pi, rot.beta*180/pi, rot.gamma*180/pi))
29
30sh.set_grid(nlat=64, nphi=128)
31q = sh.synth(Qlm)
32r = sh.synth(Rlm)
33
34# plot the fields if possible
35# inspired by: https://scipython.com/book/chapter-8-scipy/examples/visualizing-the-spherical-harmonics/
36
37try:
38 from matplotlib import cm, colors
39 from mpl_toolkits.mplot3d import Axes3D
40except:
41 print("matplotlib required to plot.")
42 exit()
43
44
45phi = arange(sh.nphi)*2*pi/sh.nphi
46theta = arccos(sh.cos_theta)
47phi, theta = meshgrid(phi, theta)
48# The Cartesian coordinates of the unit sphere
49x = sin(theta) * cos(phi)
50y = sin(theta) * sin(phi)
51z = cos(theta)
52
53# normalize to 0 - 1
54fmin, fmax = q.min(), q.max()
55q = (q-fmin)/(fmax-fmin)
56r = (r-fmin)/(fmax-fmin)
57
58fig = plt.figure(figsize=plt.figaspect(0.5))
59ax1 = fig.add_subplot(121, projection='3d')
60ax1.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(q))
61ax1.set_title('original')
62ax2 = fig.add_subplot(122, projection='3d')
63ax2.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(r))
64ax2.set_title('rotated')
65for ax in (ax1, ax2):
66 ax.set_xlabel('X')
67 ax.set_ylabel('Y')
68 ax.set_zlabel('Z')
69show()