---
title: "Kriging with Data on Various Support"
author: "D. Renard"
date: "2 janvier 2021"
output:
  pdf_document: default
  html_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(RGeostats)
rm(list=ls())
set.seed(3241)
constant.define("asp",1)
```

# Introduction

This script is made to demonstrate the use of kriging when samples are assigned support of different sizes

# Creating environment

The 2-D data base is created with 100 (*nech*) samples randomly spread in a square of 100 x 100 (*mesh*). 

```{r Db}
nech = 100
mesh = 100
db = db.create(x1 = mesh*runif(nech),
               x2 = mesh*runif(nech))
plot(db,title="Sample locations")
```

The sample support is created with 2-D extension varying equal to 0 (punctual), 5 (with proportion *p1*) and 20 (with proportion *p2*)

```{r Parameters}
p1 = 0.2
p2 = 0.1
rand = runif(nech)
dims = numeric(nech)
dims[rand < p1] = 5
dims[rand >= p1 & rand < p1+p2] = 20
db = db.add(db,dimx=dims)
db = db.add(db,dimy=dims)
db = db.locate(db,"dim*","dblk")

# Plot the samples with a size according to the sample support
plot(db,name="dimx",pch=15)
```

A target variable is simulated (unconditionally) following a spherical isotropic model with range (*range*) equal to one third of the field

```{r Model}
model = model.create(vartype="Spherical",range=mesh/3,sill=1)
db = simtub(,db,model)
db = db.rename(db,db$natt,"Data")
plot(db,pch=19,title="Data")
```

We now perform define a target point and a neighborhood with only 6 (*nmaxi*) points in the neighborhood).

```{r Target}
target = db.create(x1=50, x2=50)
nmaxi = 6
neigh = neigh.create(ndim=2,type=2,nmaxi=nmaxi,radius=30)
```

Perform the Kriging without taking the sample support into account.

```{r Reference_Kriging}
debug.reference(1)
a = kriging(db,target,model,neigh)
```

The same function is called, but accounting for the sample support this time

```{r Support_Kriging}
set.keypair("Data_Discretization",c(5,5))
a = kriging(db,target,model,neigh)
```

To check the convergence, increase the discretization

```{r Support_Kriging_2}
set.keypair("Data_Discretization",c(20,20))
a = kriging(db,target,model,neigh)
```

