## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 8,
  fig.height = 5
)

## ----setup--------------------------------------------------------------------
library(taxdiv)

## ----veri---------------------------------------------------------------------
# Tur bolluklari (ornek alanindaki birey sayisi)
topluluk <- c(
  Quercus_coccifera    = 25,
  Quercus_infectoria   = 18,
  Pinus_brutia         = 30,
  Pinus_nigra          = 12,
  Juniperus_excelsa    = 8,
  Juniperus_oxycedrus  = 5,
  Cedrus_libani        = 15,
  Abies_cilicica       = 7,
  Fagus_orientalis     = 20,
  Carpinus_betulus      = 10
)

# Taksonomik hiyerarsi (7 seviye: Tur, Cins, Familya, Takim, Sinif, Bolum, Alem)
agac <- build_tax_tree(
  species = names(topluluk),
  Genus   = c("Quercus", "Quercus", "Pinus", "Pinus",
              "Juniperus", "Juniperus", "Cedrus", "Abies",
              "Fagus", "Carpinus"),
  Family  = c("Fagaceae", "Fagaceae", "Pinaceae", "Pinaceae",
              "Cupressaceae", "Cupressaceae", "Pinaceae", "Pinaceae",
              "Fagaceae", "Betulaceae"),
  Order   = c("Fagales", "Fagales", "Pinales", "Pinales",
              "Pinales", "Pinales", "Pinales", "Pinales",
              "Fagales", "Fagales"),
  Class   = c("Magnoliopsida", "Magnoliopsida", "Pinopsida", "Pinopsida",
              "Pinopsida", "Pinopsida", "Pinopsida", "Pinopsida",
              "Magnoliopsida", "Magnoliopsida"),
  Phylum  = c("Magnoliophyta", "Magnoliophyta", "Pinophyta", "Pinophyta",
              "Pinophyta", "Pinophyta", "Pinophyta", "Pinophyta",
              "Magnoliophyta", "Magnoliophyta"),
  Kingdom = c("Plantae", "Plantae", "Plantae", "Plantae",
              "Plantae", "Plantae", "Plantae", "Plantae",
              "Plantae", "Plantae")
)

agac

## ----klasik-------------------------------------------------------------------
# Shannon cesitliligi (dogal logaritma)
H <- shannon(topluluk)
cat("Shannon H':", round(H, 4), "\n")

# Simpson indeksleri
D <- simpson(topluluk, type = "dominance")       # Baskinlik
GS <- simpson(topluluk, type = "gini_simpson")    # 1 - D
inv_D <- simpson(topluluk, type = "inverse")      # 1 / D

cat("Simpson baskinlik (D):", round(D, 4), "\n")
cat("Gini-Simpson (1-D):", round(GS, 4), "\n")
cat("Ters Simpson (1/D):", round(inv_D, 4), "\n")

## ----duzeltme-----------------------------------------------------------------
H_duz <- shannon(topluluk, correction = "chao_shen")
cat("Shannon (Chao-Shen duzeltmeli):", round(H_duz, 4), "\n")
cat("Shannon (duzeltmesiz):         ", round(H, 4), "\n")

## ----mesafe-------------------------------------------------------------------
mesafe <- tax_distance_matrix(agac)
round(mesafe, 1)

## ----cw-----------------------------------------------------------------------
# Delta: Taksonomik cesitlilik (bolluk agirlikli)
d <- delta(topluluk, agac)
cat("Delta (taksonomik cesitlilik):", round(d, 4), "\n")

# Delta*: Taksonomik ayirt edicilik (bolluk agirlikli, ayni tur ciftleri haric)
ds <- delta_star(topluluk, agac)
cat("Delta* (taksonomik ayirt edicilik):", round(ds, 4), "\n")

# AvTD (Delta+): Ortalama taksonomik ayirt edicilik (sadece tur listesi, bolluk onemsiz)
turler <- names(topluluk)
avg_td <- avtd(turler, agac)
cat("AvTD (Delta+):", round(avg_td, 4), "\n")

# VarTD (Lambda+): Taksonomik ayirt edicilik varyasyonu
var_td <- vartd(turler, agac)
cat("VarTD (Lambda+):", round(var_td, 4), "\n")

## ----pto----------------------------------------------------------------------
sonuc <- ozkan_pto(topluluk, agac)

cat("uTO  (agirliksiz cesitlilik):", round(sonuc$uTO, 4), "\n")
cat("TO   (agirlikli cesitlilik):", round(sonuc$TO, 4), "\n")
cat("uTO+ (agirliksiz uzaklik):", round(sonuc$uTO_plus, 4), "\n")
cat("TO+  (agirlikli uzaklik):", round(sonuc$TO_plus, 4), "\n")

## ----ed_seviyeleri------------------------------------------------------------
cat("Taksonomik seviye bazinda Deng entropisi:\n")
for (i in seq_along(sonuc$Ed_levels)) {
  cat("  ", names(sonuc$Ed_levels)[i], ":",
      round(sonuc$Ed_levels[i], 4), "\n")
}

## ----max_level----------------------------------------------------------------
# Tum seviyeler (varsayilan)
r_full <- ozkan_pto(topluluk, agac, max_level = NULL)
cat("Tum seviyeler: uTO =", round(r_full$uTO, 4),
    " TO =", round(r_full$TO, 4), "\n")

# Otomatik seviye secimi
r_auto <- ozkan_pto(topluluk, agac, max_level = "auto")
cat("Auto seviye:   uTO =", round(r_auto$uTO, 4),
    " TO =", round(r_auto$TO, 4), "\n")
cat("Bilgilendirici seviye:", r_auto$max_informative_level, "\n")

# Sadece ilk 3 seviye
r_3 <- ozkan_pto(topluluk, agac, max_level = 3)
cat("Ilk 3 seviye:  uTO =", round(r_3$uTO, 4),
    " TO =", round(r_3$TO, 4), "\n")

## ----sekiz_bilesen------------------------------------------------------------
sonuc8 <- ozkan_pto(topluluk, agac, max_level = "auto")
cat("Standart:  uTO =", round(sonuc8$uTO, 4),
    " TO =", round(sonuc8$TO, 4), "\n")
cat("Max-level: uTO_max =", round(sonuc8$uTO_max, 4),
    " TO_max =", round(sonuc8$TO_max, 4), "\n")
cat("Bilgilendirici seviye sayisi:", sonuc8$max_informative_level, "\n")

## ----bilesenler---------------------------------------------------------------
pto_components(topluluk, agac)

## ----islem2-------------------------------------------------------------------
islem2 <- ozkan_pto_resample(topluluk, agac, n_iter = 101, seed = 42)

cat("=== Islem 1 (deterministik) ===\n")
cat("uTO+:", round(islem2$uTO_plus_det, 4), "\n")
cat("TO+: ", round(islem2$TO_plus_det, 4), "\n")
cat("uTO: ", round(islem2$uTO_det, 4), "\n")
cat("TO:  ", round(islem2$TO_det, 4), "\n\n")

cat("=== Islem 2 (maksimum,", islem2$n_iter, "iterasyon) ===\n")
cat("uTO+:", round(islem2$uTO_plus_max, 4), "\n")
cat("TO+: ", round(islem2$TO_plus_max, 4), "\n")
cat("uTO: ", round(islem2$uTO_max, 4), "\n")
cat("TO:  ", round(islem2$TO_max, 4), "\n")

## ----islem3-------------------------------------------------------------------
islem3 <- ozkan_pto_sensitivity(topluluk, agac, islem2, seed = 123)

cat("=== Islem 3 (duyarlilik analizi) ===\n")
cat("Islem 3 max uTO+:", round(islem3$run3_uTO_plus_max, 4), "\n")
cat("Islem 3 max TO+: ", round(islem3$run3_TO_plus_max, 4), "\n\n")

cat("=== Genel maksimum (Islem 1 + 2 + 3) ===\n")
cat("uTO+:", round(islem3$uTO_plus_max, 4), "\n")
cat("TO+: ", round(islem3$TO_plus_max, 4), "\n")
cat("uTO: ", round(islem3$uTO_max, 4), "\n")
cat("TO:  ", round(islem3$TO_max, 4), "\n")

## ----olasiliklar--------------------------------------------------------------
olasiliklar <- islem3$species_probs
veri_cercevesi <- data.frame(
  Tur = names(olasiliklar),
  Olasilik = round(olasiliklar, 4)
)
print(veri_cercevesi, row.names = FALSE)

## ----full_pipeline------------------------------------------------------------
tam <- ozkan_pto_full(topluluk, agac, n_iter = 101, seed = 42)

cat("Pipeline: Islem 1 -> Islem 2 -> Islem 3\n\n")
cat("          uTO+      TO+       uTO       TO\n")
cat("Islem 1:", sprintf("%9.4f %9.4f %9.4f %9.4f",
    tam$run1$uTO_plus, tam$run1$TO_plus,
    tam$run1$uTO, tam$run1$TO), "\n")
cat("Islem 2:", sprintf("%9.4f %9.4f %9.4f %9.4f",
    tam$run2$uTO_plus_max, tam$run2$TO_plus_max,
    tam$run2$uTO_max, tam$run2$TO_max), "\n")
cat("Islem 3:", sprintf("%9.4f %9.4f %9.4f %9.4f",
    tam$run3$uTO_plus_max, tam$run3$TO_plus_max,
    tam$run3$uTO_max, tam$run3$TO_max), "\n")

## ----jackknife----------------------------------------------------------------
jk <- ozkan_pto_jackknife(topluluk, agac)

cat("Tam sonuc uTO+:", round(jk$full_result$uTO_plus, 4), "\n")
cat("Tam sonuc TO+: ", round(jk$full_result$TO_plus, 4), "\n")
cat("Mutlu turler:  ", jk$n_happy, "/", jk$n_happy + jk$n_unhappy, "\n\n")

# Her turun cikarildiginda sonuc nasil degisiyor?
head(jk$jackknife_results)

## ----batch--------------------------------------------------------------------
# Coklu ornek alan verisi
veri <- data.frame(
  Site = rep(c("Alan_A", "Alan_B"), each = 5),
  Species = rep(c("Pinus_brutia", "Pinus_nigra", "Quercus_coccifera",
                  "Juniperus_excelsa", "Cedrus_libani"), 2),
  Abundance = c(30, 12, 25, 8, 15, 5, 40, 10, 3, 2),
  Genus = rep(c("Pinus", "Pinus", "Quercus", "Juniperus", "Cedrus"), 2),
  Family = rep(c("Pinaceae", "Pinaceae", "Fagaceae",
                 "Cupressaceae", "Pinaceae"), 2),
  Order = rep(c("Pinales", "Pinales", "Fagales", "Pinales", "Pinales"), 2)
)

sonuc_batch <- batch_analysis(veri)
print(sonuc_batch)

## ----rarefaction--------------------------------------------------------------
rare <- rarefaction_taxonomic(topluluk, agac,
                               index = "shannon",
                               steps = 10, n_boot = 100, seed = 42)
cat("Rarefaction sonuclari (Shannon):\n")
print(round(rare, 4))

## ----simulasyon---------------------------------------------------------------
sim <- simulate_td(agac, n_sim = 100, seed = 42)
summary(sim)

## ----dendogram, fig.width=9, fig.height=5.5, fig.alt="Akdeniz ormani turlerinin familya bazinda taksonomik agac dendogrami"----
plot_taxonomic_tree(agac, community = topluluk,
                    color_by = "Family", label_size = 3.5,
                    title = "Akdeniz Ormani - Familya Bazinda")

## ----heatmap, fig.width=9, fig.height=8, fig.alt="Turler arasi taksonomik mesafeleri gosteren isi haritasi"----
plot_heatmap(agac, label_size = 2.8,
             title = "Taksonomik Mesafe Isi Haritasi")

## ----karsilastirma_veri-------------------------------------------------------
# Baskin topluluk: ayni turler, farkli bolluk dagilimi
baskin_topluluk <- c(
  Quercus_coccifera   = 80, Quercus_infectoria  = 5,
  Pinus_brutia        = 3,  Pinus_nigra         = 2,
  Juniperus_excelsa   = 2,  Juniperus_oxycedrus = 1,
  Cedrus_libani       = 3,  Abies_cilicica      = 1,
  Fagus_orientalis    = 2,  Carpinus_betulus     = 1
)

topluluklar <- list(
  Cesitli = topluluk,
  Baskin  = baskin_topluluk
)

## ----karsilastirma, fig.width=10, fig.height=6, fig.alt="Cesitli ve baskin topluluklar icin 14 cesitlilik indeksinin cubuk grafigi karsilastirmasi"----
sonuc_plot <- compare_indices(topluluklar, agac, plot = TRUE)
sonuc_plot$plot

## ----tablo--------------------------------------------------------------------
sonuc_plot$table

## ----iterasyon, fig.width=9, fig.height=5, fig.alt="Islem 2 stokastik yeniden orneklemedeki TO degerlerinin iterasyon grafigi"----
plot_iteration(islem2, component = "TO",
               title = "Islem 2 - TO Degerleri")

## ----balon, fig.width=10, fig.height=7, fig.alt="Her turun cesitlilige katkisini gosteren familya bazinda balon grafigi"----
plot_bubble(topluluk, agac, color_by = "Family",
            title = "Tur Katkilari - Familya Bazinda")

## ----radar, fig.width=8, fig.height=8, fig.alt="Cesitli ve baskin topluluklar icin normalize edilmis indeks degerlerinin radar grafigi"----
plot_radar(topluluklar, agac,
           title = "Cesitli vs Baskin - Radar Karsilastirmasi")

## ----rarefaction_plot, fig.width=8, fig.height=5, fig.alt="Shannon indeksi icin orneklem buyuklugune karsi seyreltme egrisi"----
plot_rarefaction(rare)

## ----huni, fig.width=9, fig.height=6, fig.alt="AvTD icin beklenen aralik ve gercek deger gosteren huni grafigi"----
plot_funnel(sim, observed = data.frame(
              site  = "Akdeniz Ormani",
              s     = length(topluluk),
              value = avg_td),
            index = "avtd",
            title = "AvTD - Huni Grafigi")

## ----ornek_veri---------------------------------------------------------------
# 5 turlu kucuk bir topluluk
ornek_topluluk <- c(
  Pinus_nigra     = 4,
  Pinus_brutia    = 3,
  Quercus_cerris  = 2,
  Fagus_orientalis = 1,
  Cedrus_libani   = 2
)

ornek_agac <- build_tax_tree(
  species = names(ornek_topluluk),
  Genus   = c("Pinus", "Pinus", "Quercus", "Fagus", "Cedrus"),
  Family  = c("Pinaceae", "Pinaceae", "Fagaceae", "Fagaceae", "Pinaceae"),
  Order   = c("Pinales", "Pinales", "Fagales", "Fagales", "Pinales")
)

cat("Topluluk:\n")
print(ornek_topluluk)
cat("\nTaksonomik agac:\n")
print(ornek_agac)

## ----ornek_shannon------------------------------------------------------------
# Toplam birey: 4 + 3 + 2 + 1 + 2 = 12
N <- sum(ornek_topluluk)
cat("Toplam birey (N):", N, "\n\n")

# Oransal bolluklar
p <- ornek_topluluk / N
cat("Oransal bolluklar (p_i):\n")
for (i in seq_along(p)) {
  cat("  ", names(p)[i], ":", round(p[i], 4), "\n")
}

# Shannon: H' = -sum(p * ln(p))
H_elle <- -sum(p * log(p))
H_fonksiyon <- shannon(ornek_topluluk)
cat("\nElle hesaplanan H':", round(H_elle, 4), "\n")
cat("shannon() sonucu:  ", round(H_fonksiyon, 4), "\n")

## ----ornek_mesafe-------------------------------------------------------------
# Mesafe matrisi
m <- tax_distance_matrix(ornek_agac)
cat("Taksonomik mesafe matrisi:\n")
print(round(m, 1))
cat("\nOrnek yorumlar:\n")
cat("  Pinus_nigra - Pinus_brutia: Ayni cins -> mesafe = 1\n")
cat("  Pinus_nigra - Cedrus_libani: Ayni familya (Pinaceae) -> mesafe = 2\n")
cat("  Pinus_nigra - Quercus_cerris: Farkli takim (Pinales vs Fagales) -> mesafe = 3\n")

## ----ornek_avtd---------------------------------------------------------------
# AvTD = tum tur ciftleri arasindaki ortalama mesafe
# S = 5, S*(S-1)/2 = 10 cift
S <- length(ornek_topluluk)
cift_sayisi <- S * (S - 1) / 2
cat("Tur sayisi (S):", S, "\n")
cat("Cift sayisi:", cift_sayisi, "\n\n")

# Tum ciftlerin mesafelerini topla
toplam_mesafe <- 0
for (i in 1:(S - 1)) {
  for (j in (i + 1):S) {
    d_ij <- m[i, j]
    cat("  ", rownames(m)[i], "-", colnames(m)[j], ":", d_ij, "\n")
    toplam_mesafe <- toplam_mesafe + d_ij
  }
}

avtd_elle <- toplam_mesafe / cift_sayisi
avtd_fonksiyon <- avtd(names(ornek_topluluk), ornek_agac)
cat("\nToplam mesafe:", toplam_mesafe, "\n")
cat("Elle hesaplanan AvTD:", round(avtd_elle, 4), "\n")
cat("avtd() sonucu:      ", round(avtd_fonksiyon, 4), "\n")

## ----ornek_deng---------------------------------------------------------------
# Tur seviyesinde: her tur tek basina bir grup (|F_i| = 1)
# Esit agirlik: m_i = 1/S = 1/5 = 0.2
# Ed = -sum(m_i * ln(m_i / (2^1 - 1))) = -sum(0.2 * ln(0.2)) = ln(5)
Ed_tur <- log(S)
cat("Tur seviyesinde Deng entropisi:\n")
cat("  Ed_species = ln(S) = ln(", S, ") =", round(Ed_tur, 4), "\n")
cat("  (Bu Shannon entropisiyle ayni, cunku |F_i| = 1)\n\n")

# Cins seviyesinde: Pinus(2 tur), Quercus(1), Fagus(1), Cedrus(1)
# 4 grup, esit agirlikli: m_i = grup_tur_sayisi / toplam_tur_sayisi
cat("Cins seviyesinde:\n")
cat("  Pinus: 2 tur, Quercus: 1 tur, Fagus: 1 tur, Cedrus: 1 tur\n")
cat("  m_Pinus = 2/5 = 0.4, |F| = 2\n")
cat("  m_diger = 1/5 = 0.2, |F| = 1\n\n")

# Ed = -(0.4 * ln(0.4 / (2^2 - 1))) - 3*(0.2 * ln(0.2 / (2^1 - 1)))
Ed_cins <- -(0.4 * log(0.4 / (2^2 - 1))) - 3 * (0.2 * log(0.2 / (2^1 - 1)))
cat("  Ed_genus = -(0.4 * ln(0.4/3)) - 3*(0.2 * ln(0.2/1))\n")
cat("           =", round(Ed_cins, 4), "\n")

## ----ornek_pto----------------------------------------------------------------
# Fonksiyonla hesapla
pto_sonuc <- ozkan_pto(ornek_topluluk, ornek_agac)

cat("Ozkan pTO sonuclari:\n")
cat("  uTO  =", round(pto_sonuc$uTO, 4), "\n")
cat("  TO   =", round(pto_sonuc$TO, 4), "\n")
cat("  uTO+ =", round(pto_sonuc$uTO_plus, 4), "\n")
cat("  TO+  =", round(pto_sonuc$TO_plus, 4), "\n\n")

cat("Seviye bazinda Deng entropisi:\n")
for (i in seq_along(pto_sonuc$Ed_levels)) {
  cat("  ", names(pto_sonuc$Ed_levels)[i], ":",
      round(pto_sonuc$Ed_levels[i], 4), "\n")
}

