1. Instalação do pacote SITS

# ("run" se ainda não estiver instalado na sua máquina)
# install.packages("sits", dependencies = TRUE)

2. Carregar pacotes e bibliotecas

library(sits)
## SITS - satellite image time series analysis.
## Loaded sits v1.5.4.
##         See ?sits for help, citation("sits") for use in publication.
##         Documentation avaliable in https://e-sensing.github.io/sitsbook/
# https://github.com/e-sensing/sits

library(tibble)
# https://tibble.tidyverse.org/
# pacote para manipulação de tabelas no formato "tibble";
# oferece melhor visualização, indexação mais clara e integração com pacotes do tidyverse.trtrtrrtrtrt

library(dplyr)
## 
## Anexando pacote: 'dplyr'
## Os seguintes objetos são mascarados por 'package:stats':
## 
##     filter, lag
## Os seguintes objetos são mascarados por 'package:base':
## 
##     intersect, setdiff, setequal, union
# https://dplyr.tidyverse.org/
# pacote para manipulação eficiente de dados tabulares;
# essencial para análise de dados, especialmente em fluxos de trabalho do tidyverse.

3. Criar diretórios

# criar diretórios:

treinamento_dir <- "~/treinamento_sits_prodes"

dir.create(treinamento_dir, recursive = TRUE)
## Warning in dir.create(treinamento_dir, recursive = TRUE):
## 'C:\Users\User\Documents\treinamento_sits_prodes' já existe
# diretório de dados
data_dir <- "~/treinamento_sits_prodes/data_dir"


temp_dir <- "~/treinamento_sits_prodes/data_dir/temp_dir"
dir.create(temp_dir, recursive = TRUE)
## Warning in dir.create(temp_dir, recursive = TRUE):
## 'C:\Users\User\Documents\treinamento_sits_prodes\data_dir\temp_dir' já existe

_____________________________________________________________________________4_

4. Cubos

4.1. Cubo não-regular

# usar a função sits_cube para criar cubo de dados.

cube <- sits_cube(
  source = "MPC", 
# (https://planetarycomputer.microsoft.com/dataset/sentinel-2-l2a)
  collection = "SENTINEL-2-L2A",
  bands = c("B11", "B8A", "B04"),
  tiles = "20LMR",
  start_date = '2022-08-23', 
  end_date = '2022-12-23'
  )
##   |                                                                              |                                                                      |   0%  |                                                                              |======================================================================| 100%

4.1.1 Visualizar timeline

# timeline do cubo irregular

sits_timeline(cube)
##  [1] "2022-08-23" "2022-08-26" "2022-08-28" "2022-08-31" "2022-09-02"
##  [6] "2022-09-05" "2022-09-07" "2022-09-10" "2022-09-12" "2022-09-15"
## [11] "2022-09-17" "2022-09-20" "2022-09-22" "2022-09-25" "2022-09-27"
## [16] "2022-09-30" "2022-10-02" "2022-10-05" "2022-10-07" "2022-10-10"
## [21] "2022-10-12" "2022-10-15" "2022-10-17" "2022-10-20" "2022-10-22"
## [26] "2022-10-25" "2022-10-27" "2022-10-30" "2022-11-01" "2022-11-04"
## [31] "2022-11-06" "2022-11-09" "2022-11-11" "2022-11-14" "2022-11-16"
## [36] "2022-11-19" "2022-11-21" "2022-11-24" "2022-11-26" "2022-11-29"
## [41] "2022-12-01" "2022-12-04" "2022-12-06" "2022-12-09" "2022-12-11"
## [46] "2022-12-14" "2022-12-16" "2022-12-19" "2022-12-21"

4.1.2 Plotar uma imagem do cubo

# plot cubo  - não regularizado
plot(cube, red = "B11", green = "B8A", blue = "B04", date = "2022-11-24")
## Warning in CPL_gdalinfo(if (missing(source)) character(0) else source, options,
## : GDAL Message 1: HTTP response code on
## https://sentinel2l2a01.blob.core.windows.net/sentinel2-l2/20/L/MR/2022/08/23/S2B_MSIL2A_20220823T142709_N0400_R053_T20LMR_20220824T143741.SAFE/GRANULE/L2A_T20LMR_A028536_20220823T143247/IMG_DATA/R10m/T20LMR_20220823T142709_B04_10m.tif?st=2026-02-05T03%3A05%3A43Z&se=2026-02-06T03%3A50%3A43Z&sp=rl&sv=2025-07-05&sr=c&skoid=9c8ff44a-6a2c-4dfb-b298-1c9212f64d9a&sktid=72f988bf-86f1-41af-91ab-2d7cd011db47&skt=2026-02-05T21%3A33%3A32Z&ske=2026-02-12T21%3A33%3A32Z&sks=b&skv=2025-07-05&sig=eNT4s5oscKxUVcVm5NP648TS2wpnIzjumrrc%2FTeXFhI%3D.vat.dbf:
## 403

4.2. Cubo regular

- os dados utilizados para construção desse cubo já passaram pelo processo de regularização (sits_regularize);
# pasta com imagens regularizadas

images <- paste0(data_dir,"/images")

4.2.1 Carregar cubo regularizado

cube_reg <- sits_cube(
  source = "MPC", 
  collection = "SENTINEL-2-L2A",
  tiles = "20LMR",
  bands = c("B11", "B8A","B08", "B04"), 
  start_date = '2022-08-23', 
  end_date = '2022-12-23',
  data_dir =  images
)
##   |                                                                              |                                                                      |   0%  |                                                                              |=========                                                             |  12%  |                                                                              |==================                                                    |  25%  |                                                                              |==========================                                            |  38%  |                                                                              |===================================                                   |  50%  |                                                                              |============================================                          |  62%  |                                                                              |====================================================                  |  75%  |                                                                              |=============================================================         |  88%  |                                                                              |======================================================================| 100%

42.1 Visualizar timeline

# timeline do cubo regular (16 dias)

sits_timeline(cube_reg)
## [1] "2022-09-02" "2022-09-18" "2022-10-04" "2022-10-20" "2022-11-05"
## [6] "2022-11-21" "2022-12-07" "2022-12-23"

4.2.2 Plotar uma imagem do cubo

# plot cubo Regularizado
plot(cube_reg, red = "B11", green = "B8A", blue = "B04", date = "2022-11-21")

____________________________________________________________________________5__

5. Operações com cubos

5.1 Calculando de NDVI

- Uso da função sits_select()

# filtrar cube_reg
cube_ndvi<- sits_select(cube_reg,                         
                        bands = c('B11', 'B08', 'B04'),                        
                        start_date = '2022-09-23',                          
                        end_date = '2022-12-23')    

- Operação de bandas

# filtrar cubo
cube_ndvi <- sits_apply (cube_ndvi, 
                         NDVI = (B08 - B04)/(B08 + B04),
                         output_dir = temp_dir)
##   |                                                                              |                                                                      |   0%  |                                                                              |============                                                          |  17%  |                                                                              |=======================                                               |  33%  |                                                                              |===================================                                   |  50%  |                                                                              |===============================================                       |  67%  |                                                                              |==========================================================            |  83%  |                                                                              |======================================================================| 100%
# visulizar bandas
sits_bands(cube_ndvi)
## [1] "B04"  "B08"  "B11"  "NDVI"
# timeline
sits_timeline(cube_ndvi)
## [1] "2022-10-04" "2022-10-20" "2022-11-05" "2022-11-21" "2022-12-07"
## [6] "2022-12-23"

- Plot NDVI

plot(cube_ndvi, band = "NDVI", date = "2022-11-05")

____________________________________________________________________________6__

6. Dataset Rondônia

6.1 Carregar dataset

# caminho para acessar o dataset
samples_path <- ("~/treinamento_sits_prodes/data_dir/samples/deforestation_samples_v18.rds")
#samples_path <- paste0(data_dir,"/samples/deforestation_samples_v18.rds")

# Carregando o arquivo dataset
deforestation_samples_v18 <- readRDS(samples_path)

6.2 Exploração do dataset

6.2.1 Visualização da espacialização do dataset

sits_view(deforestation_samples_v18)
## Registered S3 method overwritten by 'jsonify':
##   method     from    
##   print.json jsonlite

6.2.2 Acessando dataset

- Balanceamento

summary(deforestation_samples_v18)
## # A tibble: 9 × 3
##   label                 count   prop
##   <chr>                 <int>  <dbl>
## 1 Clear_Cut_Bare_Soil     944 0.157 
## 2 Clear_Cut_Burned_Area   983 0.164 
## 3 Clear_Cut_Vegetation    603 0.100 
## 4 Forest                  964 0.160 
## 5 Mountainside_Forest     211 0.0351
## 6 Riparian_Forest        1247 0.208 
## 7 Seasonally_Flooded      731 0.122 
## 8 Water                   109 0.0181
## 9 Wetland                 215 0.0358

- Manipulação

deforestation_samples_v18_CCBS <- dplyr::filter(deforestation_samples_v18, label %in% c("Clear_Cut_Bare_Soil"))

summary(deforestation_samples_v18_CCBS)
## # A tibble: 1 × 3
##   label               count  prop
##   <chr>               <int> <dbl>
## 1 Clear_Cut_Bare_Soil   944     1

- Visualização das datas que compoem a série temporal

sits_timeline(deforestation_samples_v18)
##  [1] "2022-01-05" "2022-01-21" "2022-02-06" "2022-02-22" "2022-03-10"
##  [6] "2022-03-26" "2022-04-11" "2022-04-27" "2022-05-13" "2022-05-29"
## [11] "2022-06-14" "2022-06-30" "2022-07-16" "2022-08-01" "2022-08-17"
## [16] "2022-09-02" "2022-09-18" "2022-10-04" "2022-10-20" "2022-11-05"
## [21] "2022-11-21" "2022-12-07" "2022-12-23"

- Visualizaçao de séries temporais (original):

# séries temporais originais 

deforestation_samples_v18  |> dplyr::filter(label %in% c("Clear_Cut_Bare_Soil"))|>
                                            sits_select(bands = c("B11", "B08", "B04")) |> 
                                            plot()

- Visualizaçao suavizada dos padrões das séries: (modelo aditivo generativo)

# séries GAM

deforestation_samples_v18 |> dplyr::filter(label %in% c("Clear_Cut_Bare_Soil"))|> 
                             sits_select(bands = c("B11", "B08", "B04")) |> 
                             sits_patterns() |> 
                             plot()

Visualizaçao individual de séries (instância)

deforestation_samples_v18 |> dplyr::filter(label %in% c("Clear_Cut_Bare_Soil"))|> slice(1)|>
                                                                                  plot()

___________________________________________________________________________7___

7. Extraindo séries temporais

7.1 Construção do cubo completo

cube_reg_completo <- sits_cube(
  source = "MPC", 
  collection = "SENTINEL-2-L2A",
  tiles = "20LMR",
  bands = c("B11", "B8A","B08", "B04"), 
  start_date = '2022-01-05', 
  end_date = '2022-12-23',
  data_dir =  images
)
##   |                                                                              |                                                                      |   0%  |                                                                              |===                                                                   |   4%  |                                                                              |======                                                                |   9%  |                                                                              |=========                                                             |  13%  |                                                                              |============                                                          |  17%  |                                                                              |===============                                                       |  22%  |                                                                              |==================                                                    |  26%  |                                                                              |=====================                                                 |  30%  |                                                                              |========================                                              |  35%  |                                                                              |===========================                                           |  39%  |                                                                              |==============================                                        |  43%  |                                                                              |=================================                                     |  48%  |                                                                              |=====================================                                 |  52%  |                                                                              |========================================                              |  57%  |                                                                              |===========================================                           |  61%  |                                                                              |==============================================                        |  65%  |                                                                              |=================================================                     |  70%  |                                                                              |====================================================                  |  74%  |                                                                              |=======================================================               |  78%  |                                                                              |==========================================================            |  83%  |                                                                              |=============================================================         |  87%  |                                                                              |================================================================      |  91%  |                                                                              |===================================================================   |  96%  |                                                                              |======================================================================| 100%

7.2 Preparação do dado

# criação de um novo dataset, sem a coluna "time_series"

deforestation_samples_v18_novo <- deforestation_samples_v18 |> 
                                  dplyr::select(-time_series) #apagando timeseries

7.3 Extração de séries temporais

series_temporais_2022 <- sits_get_data(
  cube = cube_reg_completo,
  samples = deforestation_samples_v18_novo,
  start_date = '2022-01-05', 
  end_date = '2022-12-23',
  progress = FALSE
)
series_temporais_2022 |> dplyr::filter(label %in% c("Clear_Cut_Bare_Soil"))|> 
                             sits_select(bands = c("B11", "B08", "B04")) |> 
                             sits_patterns() |> 
                             plot()