## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE)
library(Rveg)
examples <- system.file(
  "extdata", "ExampleDB", package = "Rveg", mustWork = TRUE
)
example_db <- file.path(examples, "example_2")
work_dir <- tempfile("rveg-manual-")
dir.create(work_dir)

## ----installation, eval=FALSE-------------------------------------------------
# install.packages("Rveg")
# 
# install.packages("Rveg_0.2.0.tar.gz", repos = NULL, type = "source")
# 
# library(Rveg)
# packageVersion("Rveg")
# vignette("Rveg")
# help("addReleve", package = "Rveg")
# news(package = "Rveg")

## ----start, eval=FALSE--------------------------------------------------------
# library(Rveg)
# 
# addReleve(
#   save = "meadow_survey",
#   metadata = c("Meadow survey", "Permanent plots in Prague-Suchdol")
# )

## ----inspect-first, eval=FALSE------------------------------------------------
# meadow <- RvegLoad("meadow_survey", variation = 4)
# meadow$HeaderDATA["X1", c("DATE", "FieldCODE", "PlotSize")]
# meadow$RelDATA["X1", c("Trifolium pratense_1", "Sambucus nigra_2")]

## ----reopen, eval=FALSE-------------------------------------------------------
# addReleve(
#   database = "meadow_survey",
#   save = "meadow_edited",
#   extrahead = c("Management", "ObserverNotes")
# )

## ----custom-header, eval=FALSE------------------------------------------------
# addReleve(
#   save = "wetland_reference",
#   customhead = c("DATE", "FieldCODE", "PlotSize", "VegetationUnit"),
#   metadata = c("Wetland reference plots", "Plots with reviewed labels")
# )

## ----inspect-checklist--------------------------------------------------------
default_checklist <- system.file(
  "extdata", "RvChecklist", "cz_dh2012.txt",
  package = "Rveg", mustWork = TRUE
)
dictionary <- read.delim(default_checklist, encoding = "UTF-8")
dictionary[dictionary$ShortName %in% c("BELSPER", "TRIFPRA"),
           c("ShortName", "FullName")]

## ----create-checklist---------------------------------------------------------
species_names <- c(
  "Galium aparine", "Galium x pomeranicum",
  "Primula veris", "Primula veris subsp. veris",
  "Carex flava agg.", "Taraxacum sect. Taraxacum"
)
made <- CreateChecklist(species_names, export = file.path(work_dir, "survey_taxa"))
made[made$FullName %in% species_names, ]

## ----checklist-file, eval=FALSE-----------------------------------------------
# CreateChecklist("botanical_names", export = "survey_taxa")

## ----use-checklist, eval=FALSE------------------------------------------------
# addReleve(save = "my_custom_survey", checklist = "survey_taxa.txt")

## ----load-variations----------------------------------------------------------
combined <- RvegLoad(example_db)
combined[1:3, c("ShortName", "fullName", "layer", "X1")]

raw <- RvegLoad(example_db, variation = 2)
names(raw)
head(raw$RelDATA[, c("ShortName", "X1")], 4)

named <- RvegLoad(example_db, variation = 3)
head(named$RelDATA[, c("ShortName", "fullName", "layer", "X1")], 4)

## ----plot-tables--------------------------------------------------------------
plots <- RvegLoad(example_db, variation = 4)
plots$HeaderDATA[, c("LOCALITY", "PlotSize")]
plots$RelDATA[, c("Carex elata_1", "Phragmites australis_1")]

identical(rownames(plots$HeaderDATA), rownames(plots$RelDATA))
plots$RelDATA["X1", "Carex elata_1"]

## ----analysis-table-----------------------------------------------------------
site <- plots$HeaderDATA
site$plot_id <- rownames(site)
site$plot_area_m2 <- as.numeric(site$PlotSize)
site[, c("plot_id", "LOCALITY", "plot_area_m2")]

## ----spreadsheet-export-------------------------------------------------------
cover <- plots$RelDATA
cover$plot_id <- rownames(cover)
write.csv(site, file.path(work_dir, "plot_headers.csv"), row.names = FALSE)
write.csv(cover, file.path(work_dir, "plot_cover.csv"), row.names = FALSE)

## ----load-convert, eval=FALSE-------------------------------------------------
# converted <- RvegLoad(
#   database = "meadow_custom_scale", customscale = TRUE, variation = 4
# )

## ----inspect-database, eval=FALSE---------------------------------------------
# RvegCheck(
#   database = "meadow_custom_scale",
#   export = "meadow_percentage"
# )

## ----combine-example, eval=FALSE----------------------------------------------
# RvegCombine(
#   database = "woodland_survey",
#   export = "woodland_layers_combined"
# )

## ----merge-databases----------------------------------------------------------
merged_db <- file.path(work_dir, "merged")
RvegMerge(database_1 = example_db, database_2 = example_db,
          export = merged_db)
merged <- RvegLoad(merged_db, variation = 4)
nrow(plots$HeaderDATA)
nrow(merged$HeaderDATA)
merged$HeaderDATA[, c("ID", "LOCALITY")]

## ----merge-across-checklists, eval=FALSE--------------------------------------
# RvegMerge("survey_dh2012", "survey_kaplan2019", export = "joined_surveys")
# joined <- RvegLoad("joined_surveys", variation = 2)
# subset(joined$RelDATA, ShortName == "BELSPER_1")
# joined$meta$checklist

## ----import-files, eval=FALSE-------------------------------------------------
# examples <- system.file(
#   "extdata", "ExampleDB", package = "Rveg", mustWork = TRUE
# )
# 
# TvToRveg(
#   tv = file.path(examples, "tvexport.xml"),
#   export = "liberec_from_xml",
#   checklist = "Czechia_slovakia_2015"
# )
# # For the bundled XML, enter BB when asked about the cover scale.
# 
# TvToRveg(
#   tv = file.path(examples, "tvexport.csv"),
#   export = "liberec_from_csv",
#   checklist = "Czechia_slovakia_2015"
# )
# # For the bundled spreadsheet, enter P.

## ----turboveg-export----------------------------------------------------------
tv3_name <- file.path(work_dir, "turboveg3")
tv2_name <- file.path(work_dir, "turboveg2")
RvegToTv(example_db, export = tv3_name)
RvegToTv(example_db, export = tv2_name, ver = 2)
basename(c(paste0(tv3_name, ".csv"), paste0(tv2_name, c("R.csv", "H.csv"))))

## ----juice-export-------------------------------------------------------------
juice_name <- file.path(work_dir, "juice_export")
RvegToJuice(example_db, export = juice_name)
basename(paste0(juice_name, c("R.csv", "H.csv")))

## ----classify-bundled---------------------------------------------------------
classification_dir <- file.path(work_dir, "classification")
result <- RvegClassify(
  database = example_db,
  method = c("esy", "vegkey"),
  top_n = 2L,
  output = classification_dir
)
names(result)
result$esy$summary
result$vegkey$summary[, c("plot_id", "vegkey_code", "n_used_taxa")]

## ----join-classification------------------------------------------------------
review <- result$esy$summary
review$locality <- plots$HeaderDATA[
  match(review$plot_id, rownames(plots$HeaderDATA)), "LOCALITY"
]
review[, c("plot_id", "locality", "esy_n_matches", "esy_code")]

## ----read-classification------------------------------------------------------
exported <- read.csv(file.path(classification_dir, "classification.csv"))
taxa <- read.csv(file.path(classification_dir, "taxa.csv"))
exported[exported$plot_id == "X3",
         c("method", "status", "association_code", "score")]
head(taxa[, c("taxon_id", "method", "status")])

## ----classify-fpfi------------------------------------------------------------
full <- RvegClassify(
  database = example_db, rules = "CzechVeg-ESy-full",
  plot_id = c("X1", "X3"), top_n = 2L
)
full$summary
full$fpfi_ranked[, c("plot_id", "rank", "association_code",
                     "fpfi", "n_used_taxa")]

## ----vegkey-ranking-----------------------------------------------------------
result$vegkey$vegkey_ranked[, c(
  "plot_id", "rank", "unit_code", "relative_score", "n_training"
)]

## ----synonym-file, eval=FALSE-------------------------------------------------
# read.delim("project_synonyms.tsv", fileEncoding = "UTF-8", quote = "")
# 
# use_local_names <- RvegClassify(
#   "my_survey",
#   method = "vegkey",
#   synonym_file = "project_synonyms.tsv"
# )
# use_local_names$taxon_map

## ----unmatched----------------------------------------------------------------
subset(result$vegkey$taxon_map, is.na(matched_name))

## ----custom-esy---------------------------------------------------------------
wetland_rules <- data.frame(
  code = c("SEDGE", "WET"),
  name = c("Tall-sedge stand", "General wetland stand"),
  formula = c(
    "<Carex elata GR 30> AND <#TC WetSedges GE 35>",
    "<Carex elata GR 5> OR <Phragmites australis GR 5>"
  ),
  priority = c("7", "5")
)
rule_file <- file.path(work_dir, "wetland_rules.txt")
CreateESyRules(
  definitions = wetland_rules, file = rule_file,
  groups = list(WetSedges = c("Carex elata", "Carex acutiformis"))
)

wetland_esy <- RvegClassify(example_db, rules = rule_file)
wetland_esy$summary
wetland_esy$all_matches[, c("plot_id", "association_code")]

## ----several-rules------------------------------------------------------------
second_file <- file.path(work_dir, "reed_rules.txt")
CreateESyRules(
  definitions = data.frame(
    code = "REED", name = "Reed stand", priority = "8",
    formula = "<Phragmites australis GR 5>"
  ),
  file = second_file
)

files <- c(rule_file, second_file)
separate <- RvegClassify(example_db, plot_id = "X1", rules = files)
pooled <- RvegClassify(
  example_db, plot_id = "X1", rules = files, esy_mode = "merge"
)

separate$summary[, c("plot_id", "esy_code", "rule_source")]
pooled$summary[, c("plot_id", "esy_code", "rule_source")]

## ----header-uncertainty-------------------------------------------------------
header_rules <- data.frame(
  code = c("WET", "LARGE"),
  name = c("Wetland stand", "Large wetland plot"),
  formula = c(
    "<Carex elata GR 5>",
    "<Carex elata GR 5> AND <$$N SurveyArea GE 16>"
  ),
  priority = c("5", "8")
)
header_file <- file.path(work_dir, "header_rules.txt")
CreateESyRules(header_rules, file = header_file)
header_result <- RvegClassify(
  example_db, rules = header_file, plot_id = "X1"
)
header_result$summary

## ----train-from-database, eval=FALSE------------------------------------------
# reference_model <- CreateVegKey(
#   database = "wetland_reference",
#   unit_column = "VegetationUnit",
#   unit_name_column = "UnitName",
#   file = "wetland_reference.rds",
#   source = "Reviewed wetland reference plots, 2026"
# )
# 
# RvegClassify("new_wetland_plots", method = "vegkey", model = reference_model)

## ----train-from-tables--------------------------------------------------------
reference <- list(
  headers = data.frame(
    plot_id = c("p1", "p2", "p3", "p4"),
    unit = c("A1", "A1", "A2", "A2"),
    label = c("Sedge stand", "Sedge stand", "Reed stand", "Reed stand")
  ),
  species = data.frame(
    plot_id = c("p1", "p1", "p2", "p3", "p4", "p4"),
    taxon_name = c(
      "Carex elata", "Phragmites australis", "Carex elata",
      "Phragmites australis", "Carex elata", "Phragmites australis"
    ),
    layer = "6",
    cover_pct = c(55, 8, 30, 70, 7, 45)
  )
)

reference_file <- file.path(work_dir, "reference_model.rds")
CreateVegKey(
  database = reference, unit_column = "unit",
  unit_name_column = "label", file = reference_file,
  source = "Four illustrative reference plots"
)
fitted <- readRDS(reference_file)

## ----inspect-fitted-model-----------------------------------------------------
fitted$units
fitted$presence
fitted$dominant

## ----train-synoptic-----------------------------------------------------------
synoptic <- data.frame(
  unit_code = c("A1", "A1", "A2", "A2"),
  unit_name = rep(c("Sedge stand", "Reed stand"), each = 2),
  taxon_name = rep(c("Carex elata", "Phragmites australis"), 2),
  constancy = c(95, 10, 10, 95),
  dominant_constancy = c(60, 2, 2, 65),
  n_plots = c(40L, 40L, 35L, 35L)
)

synoptic_file <- file.path(work_dir, "wetland_synoptic.csv")
write.csv(synoptic, synoptic_file, row.names = FALSE)
model_file <- file.path(work_dir, "wetland_model.rds")
CreateVegKey(synoptic = synoptic_file, file = model_file,
             source = "Illustrative wetland synoptic table")

## ----predict-own-model--------------------------------------------------------
wetland <- RvegClassify(
  example_db, method = "vegkey", model = model_file,
  plot_id = c("X1", "X3")
)
wetland$summary[, c("plot_id", "vegkey_code", "n_used_taxa")]
wetland$vegkey_ranked[, c("plot_id", "rank", "unit_code",
                          "relative_score", "n_training")]

occurrence_only <- RvegClassify(
  example_db, method = "vegkey", model = readRDS(model_file),
  candidate_units = "A1", use_dominance = FALSE, plot_id = "X1"
)
occurrence_only$summary

