-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-DiSTATIS.Rmd
executable file
·264 lines (200 loc) · 11.9 KB
/
08-DiSTATIS.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# (PART) Multi Table Analysis {-}
# DiSTATIS
```{r include=FALSE}
# A clean start
rm(list=ls())
graphics.off()
# Loading required libraries
library(DistatisR)
library(ggplot2)
library(PTCA4CATA)
# Loading the datasets
Musical_Sorting <- read.csv("Data/natural36_constrained_forR(4).csv", row.names = 1)
Sorting_Data <- Musical_Sorting[-38,]
Design_Data <- read.csv("Data/sortingsubjectdesign.csv", row.names = 1)
Sorted <- (Musical_Sorting[c(1:36),])
musicalExp <- Sorting_Data[]
Design <- read.csv("Data/design_musical.csv", row.names = 1)
# DistanceFromSort() converts the data matrix into a matrix of distances
DistanceCube <- DistanceFromSort(Sorted)
# distatis() is a function from the package DistatisR that do the distance scaling
resDistasis <- distatis(DistanceCube)
# Bootstrap Sampling
Boots <- BootFactorScores(resDistasis$res4Splus$PartialF)
# Permutation test
permDistatis <- perm4PTCA(DistanceCube)
```
DISTATIS is a generalization of classical multidimensional scaling. Its goal is to analyze several distance matrices computed on the same set of objects. DISTATIS first evaluates the similarity between distance matrices. From this analysis, a compromise matrix is computed which represents the best aggrigate of the original matrices. The original distance matrices are then projected onto the compromise[@DiSTATIS].
To illustrate DISTATIS we will use the `Musical Sorting` Data. Three different "composers" are compared, each of them computing a distance matrix between the subjects. Heatmap of the distance cube for the given dataset is shown in figure \@ref(fig:DISTATISHeat)
```{r DISTATISHeat, fig.width=7, fig.height=7, out.width="50%", fig.align="center", fig.cap="Heatmap of S Plus Matrix", fig.pos="H", echo=FALSE, message=FALSE, warning=FALSE}
# RColorBrewer helps to choose colors from a palatte
require(RColorBrewer)
# Rowv,Colv = NA prevents the function from clustering the variables
corrplot::corrplot(resDistasis$res4Cmat$C, method = "color", cl.pos = "n", tl.col = "black")
#col= colorRampPalette(brewer.pal(5, "Blues"))(256))
```
## Computation
The given dataset is first convereted into an indicator matrix $L$ and this indicator matrix is transformed into a co-occurance matrix as: $$\mathbf{R_{[t]} = L_{[t]}L_{[t]}^T}$$ The co-occurance matrix is transformed then into a distance matrix by sustracting the co-occurance matrix from a conformable matrix filled with 1's. $$\mathbf{D_{[t]}=1-R_{[t]}}$$
Distance matrices cannot be analyzed directly and need to be transformed. This step corresponds to MDS and transforms a distance matrix into a corss-product matrix.
The corss product matrix denoted by $\mathbf{\hat{S}}$
is obtained as $$\mathbf{\hat{S}=-\frac{1}{2} \Xi D \Xi^T}$$ where $\mathbf{\Xi = 1- 1m^T}$, $\mathbf{m}$ is the vector of mass.
The compromise matrix is a cross product matrix that gives the best compromise of the studies. It is obtained as a weighted average of the study cross-product matrices. The weights are chosen so that studies agreeing the most with other studies will have the larger weights.
## Comparing the studies
To analyze the similarity structure of the studies we start by creating a between study cosine matrix $\mathbf{C}$. This cosine, aslo known as the $\mathbf{R_V}$ coefficient is defined as $$\mathbf{R_V} = \frac{trace\{ \mathbf{S_{[t]}^T S_{[t']} }\}}{\sqrt{trace\{ \mathbf{S_{[t]}^T S_{[t]} }\} \times trace\{ \mathbf{S_{[t']}^T S_{[t']} }\}}}$$
## PCA of the cosine matrix
The cosine matrix has the following eigendecomposition: $$\mathbf{C=P \Theta P^T}$$ with $\mathbf{P^TP = I}$, where $\mathbf{P}$ is the matrix of eigenvectors and $\mathbf{\Theta}$ is the diagonal matrix of the eigenvalues of $\mathbf{C}$. The Scree Plot is shown in figure \@ref(fig:DISTATISScree).
```{r plotScreeDISTATIS, include=FALSE}
# Create a function to plot the scree
# ev: the eigen values to plot. no default
# max.ev the max eigen value
# needed because ExPosition does not return all ev
# but only the requested one. but return all tau
# so if max.ev is specified, it is used to recompute
# all eigenvalues
# p.ep: the probabilities associated to the ev
# alpha: threshold for significance. Default = .05
# col.ns = color for ns ev. Default is Green
# col.sig = color for significant ev. Default is Violet
PlotScree <- function(ev,p.ev=NULL,max.vp=NULL,
alpha=.05,
col.ns = '#006D2C',col.sig='#54278F',
title = "Explained Variance per Dimension"
){
# percentage of inertia
val.tau = (100*ev/sum(ev))
Top.y = ceiling(max(val.tau)*.1)*10
# if ev is already a percentage convert it back
if (!is.null(max.vp)){ev = ev*(max.vp/ev[1])}
p <- ggplot(ev, aes(x = c(1:35), y= ev))
p +
# drawing a line that passes through all the ploted points
geom_line() +
# Printing y-axis label
ylab("Inertia Extracted by the Components") +
scale_x_continuous(name='Dimensions', breaks = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35)) +
geom_line() +
scale_y_continuous(sec.axis = sec_axis(~./sum(ev)*100,name="Percentage of Explained Variance")) +
geom_point(col=ifelse(p.ev<alpha, 'blue', 'indianred3'), size=2) +theme_get()
} # end of function PlotScree
```
`r if (knitr:::is_html_output()) '# References {-}'`
```{r DISTATISScree, out.width="60%", fig.align="center", fig.cap="Scree Plot for DISTATIS", fig.pos='H', fig.width=7.5, fig.height=4.5, echo=FALSE}
PlotScree(as.data.frame(permDistatis$fixedEigenvalues), p.ev = permDistatis$pEigenvalues)
```
```{r include=FALSE}
require(ggplot2)
require(ggpubr)
# A function for plotting the Distatis Rv
ggGraphDistatisRv = function(RvFS, axis1=1, axis2=2, ZeTitle="Distatis-Rv Map",
participant.colors = NULL, nude=F, RvCtr = NULL, lab = NULL)
{
# if there is no colors passes, assigns colors based on design matrix
if (is.null(participant.colors)){
participant.design <- diag(dim(RvFS)[1])
participant.colors <- as.matrix(createColorVectorsByDesign(participant.design)$oc)
}
LeMinimum = apply(RvFS, 2, min)
LeMaximum = apply(RvFS, 2, max)
petitx = min(c(0, LeMinimum[axis1]))
petity = LeMinimum[axis2]
grandx = LeMaximum[axis1]
grandy = LeMaximum[axis2]
fudgeFact_H = (grandx - petitx)/9
fudgeFact_V = (grandy - petity)/9
constraints <- list(minx = petitx - fudgeFact_H, maxx = grandx +
fudgeFact_H, miny = petity - fudgeFact_V, maxy = grandy +
fudgeFact_V)
if (is.null(RvCtr)) {
RvF2 <- RvFS^2
RvSF2 <- apply(RvF2, 2, sum)
RvCtr <- t(t(RvF2)/RvSF2)
}
p <- ggplot()
# Plotting the points
p + geom_point(aes(x=RvFS[axis1], y=RvFS[axis2]),
size=3, label=row.names(resDistasis$res4Cmat$G)) +
geom_text_repel(aes(x=RvFS[axis1], y=RvFS[axis2]), label=row.names(resDistasis$res4Cmat$G))+
# Printing thr title
ggtitle(ZeTitle) +
# Scaling the x and y axis
scale_x_continuous(name = "", limits = c(minx = petitx - fudgeFact_H,
maxx = grandx +
fudgeFact_H)) +
scale_y_continuous(name="", limits = c(miny = petity - fudgeFact_V,
maxy = grandy +
fudgeFact_V))+
# Drawing the x and y axis
geom_vline(xintercept = 0)+
geom_hline(yintercept = 0)
}
```
An element of a given eigenvector represents the projection of one study on this eigenvector. Thus the $T$ studies can be represented as points in the eigenspace and their similarities analyzed visually. Figure \@ref(fig:DISTATISRvMap) displays the projection of subjects onto the first and second component.
```{r DISTATISRvMap, fig.height=5, fig.width=9, echo=FALSE, warning=FALSE, message=FALSE, fig.pos="H", fig.align="center", fig.cap="Plot of the between-composers space", out.width="75%"}
ggGraphDistatisRv(as.data.frame(resDistasis$res4Cmat$G))
```
```{r include=FALSE}
# A function for plotting the compromise
ggGraphDistatisCompromise = function(FS, axis1 = 1, axis2 = 2, constraints = NULL, item.colors = NULL,ZeTitle = "Distatis-Compromise", nude = FALSE, Ctr = NULL, lab=NULL)
{ # Assigning colors with respect to design matrix if no color details passed
if (is.null(item.colors)) {
item.design <- diag(dim(FS)[1])
item.colors <- as.matrix(createColorVectorsByDesign(item.design)$oc)
}
# Computing the constraints
if (is.null(constraints) || sum(names(constraints) %in% c("minx",
"maxx", "miny", "maxy")) != 4) {
print("Making constraints")
real.minimum <- min(FS)
real.maximum <- max(FS)
real.value <- max(c(abs(real.minimum), abs(real.maximum)))
constraints <- list(minx = -real.value, maxx = real.value,
miny = -real.value, maxy = real.value)
}
if (is.null(Ctr)) {
F2 <- FS^2
SF2 <- apply(F2, 2, sum)
Ctr <- t(t(F2)/SF2)
}
p <- ggplot()
p +
# Plotting the points
geom_point(aes(x=FS[axis1], y=FS[axis2],colour = item.colors ),
size=3)+
# Printing the title
ggtitle(ZeTitle)+
# Scaling the axis based on the plotting constraints
scale_x_continuous(name = "", limits = c(minx = -real.value,
maxx = real.value)) +
scale_y_continuous(name="", limits = c(miny = -real.value,
maxy = real.value)) +
# Drawing the x and y axis
geom_vline(xintercept = 0)+
geom_hline(yintercept = 0)+
# Printing labels
geom_text_repel(aes(x=FS[axis1], y=FS[axis2],
label=lab), size=3)
}
```
## Computing the compromise
As for STATIS the weights are obtained by dividing each element of $\mathbf{p_1}$ by their sum. The vector containing these weights is denoted $\mathbf{\alpha}$. With $\alpha_t$ denoting the weight for the t-th study, the compromise matrix, denoted $$\mathbf{S}_{[+]} = \sum_t^T \alpha_t \mathbf{S}_{[t]}$$
The eigendecomposition of the compromise is: $$\mathbf{S}_{[+]} = \mathbf{V \Lambda V^T}$$ and the compromise factor scores for the observations are computed as: $$\mathbf{F} =\mathbf{V \Lambda^{\frac{1}{2} } }$$
The compromise plot of the music is shown in figure \@ref(fig:DISTATISCompromise). The music are color coded based on their composer.
```{r DISTATISCompromise, fig.height=8, fig.width=9, echo=FALSE, warning=FALSE, fig.pos="H", fig.align="center", fig.cap="Analysis of the compromise: Plot of the subjects in the plane defined by the first two components of the compromise matrix", out.width="75%", message=FALSE}
labelsCompromise <- as.data.frame(labels(resDistasis$res4Splus$F)[[1]])
require(ggrepel)
ggGraphDistatisCompromise(FS = as.data.frame(resDistasis$res4Splus$F) ,
lab = labelsCompromise, ZeTitle = "" , item.colors = Design$composer)
```
## Bootstrap
A bootstrap sampling was conducted to compute the confidence intervals and the compromise plot with the bootstrap intervals is shown in figure \@ref(fig:DISTATISCompromiseBoot)
```{r DISTATISCompromiseBoot, fig.height=8, fig.width=9, echo=FALSE, warning=FALSE, fig.pos="H", fig.align="center", fig.cap="Compromise with Bootstraped Confidence Intervals", out.width="75%", message=FALSE}
# ggGraphDistatisCompromise() is a user defined function for plotting the Compromise
ggGraphDistatisCompromise(FS = as.data.frame(resDistasis$res4Splus$F) ,
lab = labelsCompromise, ZeTitle = "",
item.colors = Design$composer) +
# stat_conf_ellipse draws the confidence ellipse
stat_conf_ellipse(aes(x=as.data.frame(resDistasis$res4Splus$F)[,1],
y=as.data.frame(resDistasis$res4Splus$F)[,2],
color=Design$composer),
inherit.aes = T, bary = T, linetype=2)
```