# Leave one out regression
# ------------------------------------

x <- mtcars$wt
y <- mtcars$mpg

y <- c(y, predict(lm(y ~ x), data.frame(x=range(x))))
x <- c(x, range(x))

g <- ggobi(data.frame(x=x, y=y))
d <- g[1]

extras <- rep(c(FALSE, TRUE), c(length(x) - 2, 2))
edges(d) <- matrix(rownames(d)[extras], ncol=2)
glyph_type(d) <- ifelse(extras, 1, 6)

disp <- displays(g)[[1]]
edges(disp) <- d
imode(disp) <- "Identify"

# gSignalConnect(g, "identify-point", 
#   function(gg, plot, id, data) { 
#     print(id)
#   }
# )

# Scrolling along long time series
# ------------------------------------

df <- data.frame(x=1:10000, y=sin(1:10000 * pi/20) + runif(10000, max=0.5))
g <- ggobi_longitudinal(df[1:100, ])

df_g <- g[1]
d <- displays(g)[[1]]
ggobi_display_save_picture(d, "time-series-1.png")

i <- 5
df_g[, 2] <- df[i:(i + 99), 2]
ggobi_display_save_picture(d, "time-series-2.png")

i <- 10
df_g[, 2] <- df[i:(i + 99), 2]
ggobi_display_save_picture(d, "time-series-3.png")

i <- 15
df_g[, 2] <- df[i:(i + 99), 2]
ggobi_display_save_picture(d, "time-series-4.png")


# Hierarchical
# ------------------------------------

g <- ggobi(iris)
clustering <- hclust(dist(iris[,1:4]), method="average")
glyph_colour(g[1]) <- cuttree(clustering, 3)

d <- displays(g)[[1]]
ggobi_display_save_picture(d, "clustering.png")


# Edges example
# ------------------------------------

library(graph)
library(SNAData)

data(business, marital, florentineAttrs)

florentine <- data.frame(florentineAttrs, business.links = degree(business), marital.links = degree(marital))

g <- ggobi(florentine)
edges(g) <- business
edges(g) <- marital


# Maximum likelihood
# ------------------------------------

# At each iteration, want to show values of objective function
# + values of each of the parameters
# 
# scrolling might be tricky

fr <- function(x) {   ## Rosenbrock Banana function
    x1 <- x[1]
    x2 <- x[2]
    100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}
grr <- function(x) { ## Gradient of 'fr'
    x1 <- x[1]
    x2 <- x[2]
    c(-400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1),
       200 *      (x2 - x1 * x1))
}

mldf <- data.frame(iter=1:100, p1=0, p2=0, val=0)
par <- c(-1.2,1)
op <- optim(par, fr, grr, method = "BFGS", control=list(maxit=1))
mldf[1, 2] <- op$par[1]
mldf[1, 3] <- op$par[2]
mldf[1, 4] <- op$value

g <- ggobi_longitudinal(mldf)
mldf_g <- g[1]


for(i in 2:100) {
	op <- optim(op$par, fr, grr, method = "BFGS", control=list(maxit=1))
	mldf_g[i, 2] <- op$par[1]
	mldf_g[i, 3] <- op$par[2]
	mldf_g[i, 4] <- op$value	
}


# keamns
# ------------------------------------

x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
            matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
c1 <- kmeans(x, 2, iter.max=1)
c2 <- kmeans(x, 2, iter.max=1, centers=c1$centers)