## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)

## -----------------------------------------------------------------------------
library(GPTreeO)

set.seed(42)

X <- matrix(runif(200), ncol = 2)
colnames(X) <- c("X1", "X2")
target <- function(x) list(y = mean(sin(2*pi*x) + 0.2*sin(8*pi*x) + 0.1*rnorm(1)), 
                           y_var = 0.1**2)

## -----------------------------------------------------------------------------
gptree <- GPTree$new(Nbar = 50)

## -----------------------------------------------------------------------------
predictions <- NULL

for (i in 1:nrow(X)) {
  x <- X[i,]
  predictions <- rbind(gptree$joint_prediction(x), predictions)
  target_output <- target(x)
  gptree$update(x, target_output$y, target_output$y_var) 
}

## -----------------------------------------------------------------------------
gptree$plot_tree_structure(include_shared = TRUE)

## -----------------------------------------------------------------------------
library(ggplot2)
library(tidyr)
library(dplyr)

leaf_keys <- apply(X, 1, gptree$get_leaf_key_from_input_point, include_shared = FALSE)
train_data_with_keys <- data.frame(X, leaf_keys, check.names = FALSE)

ggplot(data = train_data_with_keys, aes(x = X1, y = X2, colour = leaf_keys)) + 
  geom_point(size = 5) +
  theme_minimal() 

## -----------------------------------------------------------------------------
leaf_keys <- t(apply(X, 1, gptree$get_leaf_key_from_input_point, include_shared = TRUE))
colnames(leaf_keys) <- paste0("key_", gptree$leaf_keys)

train_data_with_keys <- data.frame(X, leaf_keys, check.names = FALSE) %>% 
  pivot_longer(cols = starts_with("key"),
               names_to = "keys") %>% 
  filter(value == TRUE) %>% 
  select(-value)

ggplot(data = train_data_with_keys, aes(x = X1, y = X2, colour = keys, size = keys)) +
  geom_point(alpha = 0.3) +
  scale_size_discrete(range = c(4, 7)) +
  theme_minimal()

## -----------------------------------------------------------------------------
gptree <- GPTree$new(Nbar = 25)
for (i in 1:nrow(X)) {
  x <- X[i,]
  target_output <- target(x)
  gptree$update(x, target_output$y, target_output$y_var) 
}
gptree$plot_tree_structure(include_shared = TRUE)


## -----------------------------------------------------------------------------
gptree <- GPTree$new(Nbar = 50, theta = 0.1, gradual_split = FALSE)
for (i in 1:nrow(X)) {
  x <- X[i,]
  target_output <- target(x)
  gptree$update(x, target_output$y, target_output$y_var) 
}
leaf_keys <- apply(X, 1, gptree$get_leaf_key_from_input_point, include_shared = FALSE)
train_data_with_keys <- data.frame(X, leaf_keys, check.names = FALSE)

ggplot(data = train_data_with_keys, aes(x = X1, y = X2, colour = leaf_keys)) + 
  geom_point(size = 5) +
  theme_minimal() 

