rotations: An R Package for SO ( 3 ) Data

In this article we introduce the rotations package which provides users with the ability to simulate, analyze and visualize three-dimensional rotation data. More speciﬁcally it includes four commonly used distributions from which to simulate data, four estimators of the central orientation, six conﬁdence region estimation procedures and two approaches to visualizing rotation data. All of these features are available for two different parameterizations of rotations: three-by-three matrices and quaternions. In addition, two datasets are included that illustrate the use of rotation data in practice.


Introduction
Data in the form of three-dimensional rotations have applications in many scientific areas, such as biomedical engineering, computer vision, and geological and materials sciences where such data represent the positions of objects within a three-dimensional reference frame. For example, Humbert et al. (1996), Bingham et al. (2009) and Bachmann et al. (2010) apply rotation data to study the orientation of cubic crystals on the surfaces of metal. Rancourt et al. (2000) use rotations to represent variations in human movement while performing a task.
A common goal shared in the analysis of rotation data across all fields is to estimate the main or central orientation for a sample of rotations. More formally, let SO(3) denote the rotation group, which consists of all real-valued 3 × 3 matrices R with determinant equal to +1. Then observations R 1 , . . . , R n ∈ SO(3) can be conceptualized as a random sample from a location model where S ∈ SO(3) is the fixed parameter of interest indicating the central orientation, and E 1 , . . . , E n ∈ SO(3) denote i.i.d. random rotations which symmetrically perturb S. Model (1) is a rotation-matrix analog of a location model for scalar data Y i = µ + e i , where µ ∈ R denotes a mean and e i ∈ R denotes an additive error symmetrically distributed around zero.
Assuming the perturbations E i symmetrically perturb S implies that the observations R i have no preferred direction relative to S and that E (R i ) = cS for some c ∈ R + for all i. Also note that under the symmetry assumption, (1) could be equivalently specified as R i = E i S, though the form given in (1) is the most common form in the literature (see Bingham et al. 2009 for details).
While there is a multitude of packages and functions available in R to estimate the mean in a location model, the toolbox for rotational data is limited. The orientlib (Murdoch, 2003) package includes the definition of an orientation class along with a few methods to summarize and visualize rotation data. A strength of the orientlib package is its thorough exploration of rotation representations, but the estimation and visualization techniques are lacking and no methods for inference are available. The onion (Hankin, 2011) package includes functions for rotation algebra but only the quaternion form is available and data analysis is not possible. The uarsbayes (Qiu, 2013) package includes functions for data generation and Bayes inference but this package is currently not publicly available. Packages for circular and spherical data, e.g. circular (Agostinelli and Lund, 2013) and SpherWave (Oh and Kim, 2013), can possibly be used but their extension to rotation data is not straightforward.
The rotations (Stanfill et al., 2014a) package fills this void by providing users with the tools necessary to simulate rotations from (1) with four distribution choices for the perturbation matrices E i . Estimation and inference for S in (1) is available along with two visualization techniques. The remainder of this manuscript introduces rotation data more fully and discusses the ways they are handled by the rotations package. For the latest on this package as well as a full list of available functions, see help(package = "rotations").

Rotation parametrizations
Several parametrizations of rotations exist. We consider two of the most commonly used: orthogonal 3 × 3 matrices with determinant one and four-dimensional unit vectors called quaternions. The rotations package allows for both parametrizations as input as well as transforming one into the other. We will briefly discuss each:

Matrix form
Rotations in three-dimensions can be represented by 3 × 3 orthogonal matrices with determinant one. Matrices with these characteristics form a group called the special orthogonal group, or rotation group, denoted SO(3). Every element in SO(3) is associated with a skew-symmetric matrix Φ (W ) where Applying the exponential operator to the matrix Φ (W ) results in the rotation R Since Φ (W ) is skew-symmetric, it can be shown that (2) reduces to where r = W , U = W / W . In the material sciences literature r and U ∈ R 3 are termed the misorientation angle and misorientation axis, respectively.
Given a rotation matrix R one can find the associated skew-symmetric matrix Φ (W ) by applying the logarithm operator defined by where r ∈ [−π, π) satisfies tr (R) = 1 + 2 cos r and tr(·) denotes the trace of a matrix. For more on the correspondence between SO(3) and skew-symmetric matrices see Stanfill et al. (2013).
The rotations package defines the S3 class "SO3", which internally stores a sample of n rotations as a n × 9 matrix. If n = 1 then an object of class "SO3" is printed as a 3 × 3 matrix but for n > 1 the n × 9 matrix is printed. Objects can be coerced into, or tested for the class "SO3" with the as.SO3 and is.SO3 functions, respectively. Any object passed to is.SO3 is tested for three characteristics: dimensionality, orthogonality and determinant one.
The as.SO3 function coerces the input into the class "SO3". There are three types of input supported by the as.SO3 function. Given a singe angle r and axis U, as.SO3 will form a rotation matrix according to (3). Equivalently one could supply a three-dimensional vector W, then the length of that vector will be taken to be the angle of rotation r = W and the axis is taken to be the unitvector in the direction of W, i.e. U = W / W . One can also supply a rotation Q in the quaternion representation. The as.SO3 function will return the matrix equivalent of Q. For all input types the function as.SO3 returns an n × 9 matrix of class "SO3" where each row corresponds to a rotation matrix. Below we illustrate the use of the as.SO3 function by constructing the 3 × 3 matrix associated with a 90 • rotation about the y-axis, i.e. r = π/2 and U = (0, 1, 0). In this example and all that follow, we have rounded the output to three digits for compactness.

## [1] TRUE
Given a rotation matrix R, the functions mis.angle and mis.axis will determine the misorientation angle and axis of an object with class "SO3" as illustrated in the next example.

Quaternion form
Quaternions are unit vectors in R 4 that are commonly written as where x l ∈ [−1, 1] for l = 1, 2, 3, 4 and i 2 = j 2 = k 2 = ijk = −1. We can write Q = (s, V ) as tuple of the scalar s for coefficient 1 and vector V for the remaining coefficients, i.e. s = x 1 and V = (x 2 , x 3 , x 4 ). A rotation around axis U by angle r translates to Q = (s, V ) with s = cos (r/2), V = U sin (r/2).
Note that rotations in quaternion form are over-parametrized: Q and −Q represent equivalent rotations. This ambiguity has no impact on the distributional models, parameter estimation or inference methods to follow. Hence, for consistency, the rotations package only generates quaternions satisfying x 1 ≥ 0. Data provided by the user does not need to satisfy this condition however. The S3 class "Q4" is defined for the quaternion representation of rotations. All the functionality of the "SO3" class also exists for the "Q4" class, e.g. is.Q4 and as.Q4 will test for and coerce to class "Q4", respectively. Internally, a sample of n quaternions is stored in the form of a n × 4 matrix with each row a unit vector. Single quaternions are printed according to the representation in (5) (see example below) while a sample of size n is printed as a n × 4 matrix with column names Real, i, j and k to distinguish between the four components.
The following code creates the same rotation from the previous section in the form of a quaternion with the as.Q4 function. This function works much the same way as the as.SO3 function in terms of possible inputs but returns a vector of length four of the class "Q4".

Data generation
If the rotation E i ∈ SO(3) from (1) has an axis U that is uniformly distributed on the unit sphere and an angle r that is independently distributed about zero according to some symmetric distribution function then E i is said to belong to the uniform-axis random spin, or UARS , class of distributions. From Bingham et al. (2009) the density for E i is given by where C(·|κ) is the distribution function associated with the angle of rotation r with concentration parameter κ. Members of the UARS family of distributions are differentiated based on the angular distribution C(·|κ).
The rotations package gives the user access to four members of the UARS class. Each member is differentiated by the distribution function for r: the uniform, the matrix Fisher (Langevin, 1905;Downs, 1972;Khatri and Mardia, 1977;Jupp and Mardia, 1979), the Cayley (Schaeben, 1997;León et al., 2006) and the circular-von Mises distribution (Bingham et al., 2009). Note: probability distribution functions on SO(3) such as (6) are defined with respect to the Haar measure, which we denote by λ. That is, the expectation of a random rotation R ∈ SO(3) with corresponding misorientation angle r is given by E (R) = Ω R f (R|κ) dλ where Ω = SO(3), dλ = [1 − cos(r)]dr/(2π) and dr is the derivative of r with respect to the Lebesgue measure. Because the Haar measure acts as the uniform measure on SO(3) and λ (Ω) = 1, then the angular distribution C(r) = [1 − cos(r)]/(2π) is referred to as the uniform distribution for misorientation angles r and has been included in the rotations package under the name .haar (see Table 1).
The spread of the Cayley, matrix Fisher and circular-von Mises distributions is controlled by the concentration parameter κ. Concentration is a distribution specific quantity and is not comparable across different distributions. To make comparisons across distributions possible we also allow for specification of the circular variance, which is defined as ν = 1 − E[cos(r)] where E[cos(r)] is often referred to as the mean resultant length (Fisher, 1996). The form of each angular distribution along with the circular variance as a function of the concentration parameter is given in Table 1.

circular-von Mises
.vmises Table 1: Circular densities and circular variance ν; I i (·) represents the modified Bessel function of order i and Γ(·) is the gamma function.
For a given concentration d, p and r take the same meaning as for the more familiar distributions such as dnorm. To simulate a sample of SO(3) data, the ruars function takes arguments n, rangle, and kappa to specify the sample size, angular distribution and concentration as shown below. Alternatively, one can specify the circular variance ν. Circular variance is used in the event that both circular variance and concentration are provided. The space argument determines the parametrization to form. When a sample of rotations is printed then a n × 9 matrix is printed with column titles that specify which element of the matrix each column corresponds to. For example, the R {1,1} element of a rotation matrix is printed under the column heading R11 as illustrated below.

Data analysis
In this section we present functions in the rotations package to compute point estimates and confidence regions for the central orientation S.

Estimation of central orientation
Given a sample of n observations R 1 , . . . , R n generated according to (1), the rotations package offers four built-in ways to estimate the central orientation S. These estimators are either Riemannian-or Euclidean-based in geometry and use either the L 1 -or L 2 -norm, i.e. they are median-or mean-type. We briefly discuss how the choice of geometry affects estimation of S.
The choice of geometry results in two different metrics to measure the distance between rotation matrices R 1 and R 2 ∈ SO(3). The Euclidean distance, d E , between two rotations is defined by where A F = tr(A A) denotes the Frobenius norm. The Euclidean distance between two rotation matrices corresponds to the length of the shortest path in R 3×3 that connects them and is therefore an extrinsic distance metric.
Estimators based on the Euclidean distance form the class of projected estimators. The name is derived from the method used to compute these estimators. That is, each estimator in this class is the projection of the the generic 3 × 3 matrix that minimizes the loss function into SO(3). For an object with class "SO3" the median or mean function with argument type = "projected" will return a 3 × 3 matrix in SO(3) that minimizes the first-or second-order loss function, respectively.
By staying in the Riemannian space SO(3) the natural distance metric becomes the Riemannian (or geodesic) distance, d R , which for two rotations R 1 , R 2 ∈ SO(3) is defined as where Log(R) denotes the logarithm of R defined in (4) and r ∈ [−π, π) is the misorientation angle of R 1 R 2 . The Riemannian distance corresponds to the length of the shortest path that connects R 1 and R 2 within the space SO (3) and is therefore an intrinsic distance metric. For this reason, the Riemannian distance is often considered the more natural metric on SO (3). As demonstrated in Stanfill et al. (2013), the Euclidean and Riemannian distances are related by d E (R 1 , R 2 ) = 2 √ 2 sin [d R (R 1 , R 2 )/2]. Estimators based on the Riemannian distance metric are called geometric estimators because they preserve the geometry of SO(3). These can be computed using the mean and median functions with the argument type = "geometric". Table 2 summarizes the four estimators including their formal definition and how they can be computed. Table 2 find estimates based on minimization of L 1 -and L 2 -norms in the chosen geometry. The function gradient.search provides the option to optimize for any other arbitrary minimization criterion. As the name suggests, the minimization is done along the gradient of the minimization function in the rotation space. Starting from an initial, user-specified rotation, the algorithm finds a (local) minimum by stepping iteratively in the direction of the steepest descent.

The estimators in
Step size is regulated internally by adjusting for curvature of the minimization function.
We highlight this process in the example below. The function L1.error is defined to minimize the intrinsic L 1 -norm, the result from the optimization should therefore agree with the geometric median of the sample. In fact, the difference between the two results is at the same level as the minimal difference (minerr) used for convergence of the gradient search. What is gained in flexibility of the optimization is, of course, paid for in terms of speed: the built-in median function is faster by far than the gradient search. Also illustrated in the example below is the rot.dist function, which computes the distance between two objects of class "SO3", e.g. R1 and R2. The argument method specifies which type of distance to compute: the "extrinsic" option will return the Euclidean distance and the "intrinsic" option will return the Riemannian distance. If R1 is an n × 9 matrix representing a sample of rotations, then rot.dist will return a vector of length n where the ith element represents the specified distance between R2 and the ith row of R1.

Estimator name Definition Code
Projected Mean Table 2: A summary of the estimators included in the rotations package. Rs is a sample of n rotations with class "SO3" or "Q4".

Confidence regions
Asymptotic results for the distribution of the projected mean S E and median S E can be used to construct confidence regions for the central orientation S. In the literature two approaches are available to justify the limiting distribution of the vector in R 3 associated with the centered estimator through (2). More specifically, the vector √ n h has been shown to have a trivariate normal distribution where h ∈ R 3 satisfies exp Φ h = S S E .
The first approach transforms a result from directional statistics while the second uses M-estimation theory in SO(3) directly. A summary of these methods is given next.
In the context of directional statistics, Prentice (1984) used results found in Tyler (1981) and the fact that S E is a function of the spectral decomposition of R = ∑ n i=1 R i /n in order to justify a multivariate normal limiting distribution for the scaled vector √ n h. Unsatisfied with the coverage rate achieved by Prentice (1986 proposed a pivotal bootstrap procedure that results in coverage rates closer to the nominal level for small samples. A transformation from unit vectors in R d to rotation matrices is required in order to apply the results of Prentice (1984) and  to SO(3), therefore they are called transformation-based . The projected median S E cannot be expressed as a function of the sample spectral decomposition, therefore this approach cannot be used to create confidence regions based on S E .
It has also been shown that both estimators S E and S E are M-estimators, which motivates a direct approach to confidence region estimation in SO(3) (Chang and Rivest, 2001). In Stanfill et al. (2014b), a pivotal bootstrap method based on the direct approach was implemented to improve coverage rates in small samples. Because the results in Chang and Rivest (2001) and Stanfill et al. (2014b) deal with SO(3) data directly, this approach is called direct .
The six possible confidence regions that result from these two methods are available through the wrapper function region. They are differentiated based on the method, type and estimator arguments. Set estimator = "mean" or estimator = "median" to estimate a region based on S E or S E , respectively. For S E one can choose method = "transformation" for the transformationbased methods or method = "direct" for the direct method. Since the transformation-based methods cannot be applied to S E an error is returned if estimator = "median" and method = "transformation" are combined. A bootstrap version of the specified method is implemented if type = "bootstrap" or the normal limiting distribution can be chosen with type = "asymptotic". If a bootstrap type region is specified one can additionally specify the bootstrap sample size with the m argument, which is set to 300 by default. Regardless of the method and type chosen a single value is returned on the interval (0, π]. This value corresponds to the radius of the confidence region centered at each of the axes of the specified estimator. In the example code below a sample of n = 50 rotations are drawn from the Cayley-UARS(I 3×3 , κ = 10) distribution then the four types of confidence regions based on the direct approach are constructed. For a graphical representation of this dataset along with an interpretation of the confidence regions see Figure 1.

Visualizations
The rotations package offers two methods to visualize rotation data in three-dimensions. Because rotation matrices are orthogonal, each column of a rotation matrix has length one and is perpendicular to the other axes. Therefore each column of a rotation matrix can be illustrated as a point on the surface of a unit sphere, which represents the position of the x-, yor z-axis for that rotation matrix. Since each sphere represents one of the three axes, three spheres are required to fully visualize a sample of rotations. Though the use of separate spheres to represent each axis can be seen as a disadvantage, the proposed visualization method makes the idea of a central orientation and a confidence region interpretable.
An existing function that can be used to illustrate rotation data is the boat3d function included in the orientlib package. Given a sample of rotations, the boat3d function produces either a static or interactive three-dimensional boat to represent the provided data. If only one rotation is of interest, the boat3d function is superior to the proposed method because it conveniently illustrates rotational data in a single image. If multiple rotations are provided, however, the boat3d function will produce separate side-by-side boats, which can be hard to interpret. In addition, the illustration of a estimated central orientation or a confidence region in SO(3) with the boat3d function is not presently possible.
The rotations package can be used to produce high-quality static plots within the framework of the ggplot2 package (Wickham, 2009). Static plots are specifically designed for datasets that are highly concentrated and for use in presentations or publications. Alternatively, the rotations package can produce interactive plots using functions included in the sphereplot package (Robotham, 2013). Interactive plots are designed so that the user can explore a dataset and visualize a diffuse sample.
Calling the plot function with a "SO3" or "Q4" object will result in an interactive or static sphere, differentiated by setting the argument interactive to TRUE or FALSE, respectively. The center argument defines the center of the plot and is usually set to the identity rotation id.SO3 or an estimate of the central orientation, e.g. mean(Rs). The user can specify which columns to visualize with the col argument with options 1, 2 and 3 representing the x-, yand zaxes, respectively. For static plots, multiple axes can be displayed simultaneously by supplying a vector to col; only one column will be displayed at a time for interactive plots. Also available to static plots is the argument to_range, which when set to TRUE will display the portion of the sphere where the observations are present.
All four estimates of the central orientation can be plotted along with a sample of rotations. Setting the argument estimates_show = "all" will display all four simultaneously. If only a few estimates are of interest then any combination of "proj.mean", "proj.median", "geom.mean" or "geom.median" are valid inputs. The estimators are indicated by color and a legend is provided, see Figure 1. Finally, the mean_regions and median_regions options allow the user to draw a circle on the surface of the sphere representing the confidence region for that axis, centered at S E and S E respectively. If estimators are plotted along with the different regions in static plots then shapes represent the estimators and colors represent the region methods, see Figure 1, while regions and estimators are always distinguished by colors for the interactive plots. Given the sample of rotations generated in a previous example, the example below illustrates how to produce static plots using the plot function for objects of class "SO3" and Figure 1 illustrates the results of these commands.

plot(
x = Rs, center = mean(Rs), show_estimates = "all" ) plot( x = Rs, center = mean(Rs), show_estimates = "proj.mean", mean_regions = "all", alp = .05 ) Figure 1: The x-axis of a random sample from the Cayley-UARS distribution with κ = 1 and n = 50. All four point estimates are displayed on the left and all three region methods along with the projected mean are on the right.

Datasets
Datasets drill and nickel are included in the rotations package to illustrate how the two representations of orientation data discussed here are used in practice. The drill dataset was collected to assess variation in human movement while performing a task (Rancourt, 1995). Eight subjects drilled into a metal plate while being monitored by infrared cameras. Quaternions are used to represent the orientation of each subjects' wrist, elbow and shoulder in one of six positions. For some subjects several replicates are available. See Rancourt et al. (2000) for one approach to analyzing these data. In the example below we load the drill dataset, coerce the observations for subject one's wrist into a form usable by the rotations package via as.Q4, then estimate the central orientation with the projected mean. In the nickel dataset, rotation matrices are used to represent the orientation of cubic crystals on the surface of a nickel sample measured with Electron Backscatter Diffraction. Each location on the surface of the nickel is identified by the xpos and ypos columns while the rep column identifies which of the fourteen replicate scans that measurement corresponds to. The last nine columns, denoted v1-v9, represent the elements of the rotation matrix at that location in vector form. See Bingham et al. (2009Bingham et al. ( , 2010 and Stanfill et al. (2013) for more details. In the example below we estimate the central orientation at location one.

Summary
In this manuscript we introduced the rotations package and demonstrated how it can be used to generate, analyze and visualize rotation data. The rotations package is compatible with the quaternion specific onion package by applying its as.quaternion function to a transposed "Q4" object.
Connecting to the onion package gives the user access to a wide range of algebraic functions unique to quaternions. Also compatible with the rotations package is the orientlib package, which includes additional parametrizations of rotations. To translate rotation matrices generated by the rotations package into a form usable by the orientlib package, first coerce a "SO3" object into a matrix of the same dimension, i.e. n × 9, then apply the rotvector function provided by the orientlib package. Quaternions are defined in the orientlib package by Q = x 1 i + x 2 j + x 3 k + x 4 , cf. (5), which may lead to confusion when translating quaternions between the orientlib package and either of the onion or rotations packages. Below is a demonstration of how quaternions and rotation matrices generated by the rotations package can be translated into a form usable by the onion and orientlib packages, respectively. See help(package = "onion") and help(package = "orientlib") for more on these packages.