---
title: "Step-by-Step Riemannian PCA with UMAP on Synthetic Data"
author: "Oldemar Rodríguez Rojas & Jennifer Lobo Vásquez"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Step-by-Step Riemannian PCA with UMAP on Synthetic Data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  fig.align = "center"
)
```

# Overview

This example explores a data set composed of 250 observations and 10 numeric variables. It also includes a column named `cluster`.

The numeric variables are used to perform the Riemannian analysis, while the `cluster` column is used only for visualization. In particular, this column allows the individuals to be colored according to the group they belong to.

In this data set, the first two variables, `x` and `y`, contain the most relevant structural information. The remaining variables correspond to added noise, included to increase the dimensionality of the problem.

The goal of this example is to explore the general structure of the data using Riemannian principal components and, using the known clusters, visualize possible patterns or characteristics among the individuals.

```{r load-package}
library(riemannianStats)
```

# 1. Load the data set


```{r locate-data, include=FALSE}
data.path <- system.file(
  "extdata",                  # Folder inside the package where the CSV file is stored
  "Data10D_250.csv",         # Name of the CSV file
  package = "riemannianStats" # Package where the file is searched
)
```


```{r file-path}
data.path
```

```{r read-data}
original.data<- read.csv(
  data.path, # It must be replaced with the path to the CSV file.
  sep = ",",
  dec = "."
)

original.data$cluster<- as.factor(original.data$cluster)

str(original.data)
```

# 2. Prepare the data

Since the Riemannian analysis is applied only to numeric variables, the `cluster` column is first separated from the data set used in the analysis. This column is kept for later visualizations, for example, to color individuals according to the group they belong to.

Additionally, since this method is based on calculating distances between observations, it is recommended to scale the numerical variables before performing the analysis. This allows all variables to contribute in a comparable way and prevents those with larger magnitudes from dominating the results.

```{r prepare-data}
clusters <- original.data$cluster

data.analysis <- original.data[, setdiff(names(original.data), "cluster"), drop = FALSE]

data.analysis.scaled <- scale(data.analysis)

data.analysis.scaled <- as.data.frame(data.analysis.scaled)

head(data.analysis.scaled)
```

# 3. Choose the number of neighbors

The `n.neighbors` parameter determines how many observations are considered in the local neighborhood of each point when constructing the UMAP similarity graph. As a practical rule, when a certain number of groups is known or expected in the data, it can be defined as the total number of observations divided by the expected number of groups.

```{r choose-neighbors}
expected.groups <- 5

n.neighbors <- as.integer(nrow(data.analysis) / expected.groups)
n.neighbors
```

# 4. Compute the UMAP similarities

This matrix represents the local similarity between observations.

```{r calculate-similarities}
umap.similarities <- riem.similarities.umap(
  data = data.analysis,
  n.neighbors = n.neighbors,
  min.dist = 0.1,
  metric = "euclidean"
)
umap.similarities[1:5, 1:5]
```

# 5. Compute the Rho matrix

The Rho matrix is computed as `1 - umap.similarities`. This matrix transforms local similarity into a local separation measure.

```{r calculate-rho}
rho <- riem.rho(umap.similarities)

rho[1:5, 1:5]
```

# 6. Compute the Riemannian vector differences

The Riemannian vector differences are stored in a three-dimensional array. The entry `riemannian.diff[i, j, ]` contains the weighted difference between observations `i` and `j`.

```{r calculate-riemannian-diff}
riemannian.diff <- riem.diff(
  data = data.analysis,
  rho = rho
)

riemannian.diff[1, 2, ]
```

# 7. Compute the UMAP-based Riemannian distance matrix

The distance matrix summarizes each Riemannian difference vector into a single distance value.

```{r calculate-distance-matrix}
umap.distance.matrix <- riem.dist(riemannian.diff)

umap.distance.matrix[1:5, 1:5]
```
# 8. Riemannian correlation matrix

The Riemannian correlation matrix is computed from the Riemannian covariance matrix.

```{r riemannian-correlation}
correlation.matrix <- riem.cor(
  data = data.analysis,
  rho = rho,
  umap.distance.matrix = umap.distance.matrix
)

correlation.matrix[1:5, 1:5]
```

# 10. Riemannian covariance matrix

The Riemannian covariance matrix is computed using the data centered with respect to the Riemannian mean observation.

```{r riemannian-covariance}
covariance.matrix <- riem.cov(
  data = data.analysis,
  rho = rho,
  umap.distance.matrix = umap.distance.matrix
)

covariance.matrix[1:5, 1:5]
```


# 10. Riemannian principal components

The Riemannian principal components are computed from the original data, the Riemannian correlation matrix, the Rho matrix, and the UMAP-based Riemannian distance matrix.


```{r riemannian-components}
components <- riem.ind.coord(
  data = data.analysis,
  correlation.matrix = correlation.matrix,
  rho = rho,
  umap.distance.matrix = umap.distance.matrix
)

components[1:5, 1:5]
dim(components)
```

Each row corresponds to an observation, and each column corresponds to a Riemannian principal component.

# 11. Explained inertia

Explained inertia measures the proportion of the total Riemannian variance represented by the selected components.

In R, indices start at 1. Therefore, the first two components are selected using `component1 = 1` and `component2 = 2`.

```{r explained-inertia}
inertia <- riem.inertia(
  correlation.matrix = correlation.matrix,
  component1 = 1,
  component2 = 2
) * 100

inertia
```

The result is multiplied by 100 to express it as a percentage.

# 12. Correlations between variables and components

The `riem.loadings()` function computes the Riemannian correlation between each original variable and the first two Riemannian principal components.

# Estan mal los resultado******************* Dan mal los negativos
```{r variable-component-correlations}
correlations <- riem.var.coord(
  data = data.analysis,
  components = components,
  rho = rho,
  umap.distance.matrix = umap.distance.matrix
)

correlations
```

These correlations help interpret the axes of the Riemannian principal plane. Variables with large absolute values are strongly associated with the corresponding component.

# 13. Visualizations

## 13.1 Principal plane

The principal plane is constructed from the Riemannian component matrix and represents the observations in the space generated by the first two principal components.

In this case, since the data set includes a column with cluster labels, each individual can be visualized on the principal plane and colored according to the cluster it belongs to. This makes it easier to visually explore the structure of the data and identify possible patterns, groupings, or separations between the different groups.

```{r plot-principal-plane-function, fig.width=7, fig.height=5}
riem.plot(
  data = data.analysis,
  choix = "ind",
  components = components,
  clusters = clusters,
  explained.inertia = inertia,
  show.labels = TRUE
)
```

```{r plot-principal-plane-function-interactive, fig.width=7, fig.height=5}
riem.plot(
  data = data.analysis,
  choix = "ind",
  components = components,
  clusters = clusters,
  explained.inertia = inertia,
  show.labels = TRUE,
  title = "Data10D_250",
  interactive = TRUE
)
```

## 13.2 Correlation circle

The correlation circle shows how the original variables are related to the first two Riemannian components.

```{r plot-correlation-circle, fig.width=7, fig.height=7}
riem.plot(
  data = data.analysis,
  choix = "var",
  correlations = correlations,
  explained.inertia = inertia,
  title = "Data10D_250"
)
```

Variables pointing in similar directions are positively related in the component space. Variables pointing in opposite directions have a negative association. Longer arrows indicate a stronger correlation with the plotted components.

## 13.3 Biplot

The biplot combines, in a single visualization, the representation of individuals on the principal plane and the information associated with the variables through arrows.

This type of plot makes it possible to jointly analyze the position of the observations and the contribution of the variables to the principal components. In other words, it helps interpret which variables are most related to the separation, grouping, or dispersion of individuals in the plane.

```{r biplot, fig.width=7, fig.height=7}
riem.biplot(
  data = data.analysis,
  components = components,
  correlations = correlations,
  clusters = clusters,
  explained.inertia = inertia,
  title = "Data10D_250"
)
```

```{r biplot-interactive, fig.width=7, fig.height=7}
riem.biplot(
  data = data.analysis,
  components = components,
  correlations = correlations,
  clusters = clusters,
  show.ind.labels = FALSE,
  show.var.labels = TRUE,
  var.color = "red",
  interactive = TRUE
)
```

## 13.4 3D plot

Before generating the three-dimensional plot, a new `data.frame` is created by combining the original variables, the column with cluster labels, and the previously computed Riemannian components.

In particular, the first three Riemannian components are added. These components allow each observation to be represented in a three-dimensional space.

The goal of this visualization is to explore the dispersion of individuals in the space defined by the Riemannian components. In addition, by coloring the points according to the `cluster` variable, it is possible to identify whether the known groups show differentiated patterns, separations, or structures in three dimensions.

```{r prepare-visualization-data}
data.viz <- original.data

data.viz$Riemannian.Component1 <- components[, 1]
data.viz$Riemannian.Component2 <- components[, 2]
data.viz$Riemannian.Component3 <- components[, 3]

head(data.viz)
```

The first three Riemannian components are visualized using a three-dimensional plot. This representation makes it possible to analyze the spatial distribution of the observations and facilitates the interpretation of possible groupings when a cluster variable is used to color the points.

```{r plot-3d-components, eval=FALSE}
riem.plot3d(
  data = data.viz,
  x.col = "Riemannian.Component1",
  y.col = "Riemannian.Component2",
  z.col = "Riemannian.Component3",
  cluster.col = "cluster",
  title = "Data10D_250 - Riemannian Components",
  explained.inertia = inertia
)
```

This example shows how to use `riemannianStats` with a higher-dimensional synthetic data set through a functional workflow. Starting from numeric data, it builds a UMAP-based Riemannian structure, extracts components, interprets variable contributions, and visualizes the resulting geometry.
