---
title: ""
output: 
  bookdown::word_document2

bibliography: alpha_div_bib.bib
csl: ecography.csl
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

__From earthquakes to island area: multi-scale effects upon local diversity__  
 
```{r co-auths,message=F,error=F,echo=F,warning=F}

setwd("/Users/liamtrethowan/Documents/Indo_alpha_diversity")
library(tidyverse)

Institute_order=read_csv('AUTHORSHIP_alpha diversity_submission.csv') %>% 
  rename('conf'='Confirmed co-authorship') %>% 
  drop_na('conf') %>% 
  select(Name,Email,Address) %>%
  distinct(Address) %>%
  mutate(Address=str_replace(Address,'&','and'),
         Address=str_replace(Address,'-',', '),
         Address=str_replace(Address,'\\ ,',',')) %>%
  separate(Address,into = c('Address_1','Address_2','Address_3'),sep = '; ') %>%
  pivot_longer(starts_with('Address'),names_to='Add_no',values_to = 'Address') %>%
  select(Address) %>%
  drop_na() %>%
  mutate(Address=str_replace(Address,'Jawa, Barat','Jawa Barat'),
         Address=str_replace(Address,'\\, and',' and'),
         Address=str_replace(Address,'National Research and Innovation Agency of the Republic of Indonesia','National Research and Innovation Agency (BRIN), Indonesia'),
         Address=str_replace(Address,'Etnobiology','Ethnobiology'),
         Address=str_remove(Address,'. JL Raya Jakarta Bogor km 46, Cibinong West Java, Indonesia'),
         Address=str_replace(Address,'Kota Bogor, Jawa Barat, Indonesia.','Gunung Batu, Bogor, Indonesia'),
         Address=str_remove(Address,'Jalan Inamberi Susweni, Manokwari,  Papua barat, '),
         Address=str_remove(Address,'Chester Street, Manchester, M1 5GD, '),
         Address=str_remove(Address,'Jalan Tungku Link, Gadong, BE1410, '),
         Address=str_remove(Address,'11800 Penang, '),
         Address=str_remove(Address,' 98314'),
         Address=str_remove(Address,'Jalan Gunung Salju Amban, '),
         Address=str_replace(Address,'Sceineces','Sciences'),
         Address=str_replace(Address,'  ',' '),
         Address=str_replace(Address,'2109 ',''),
         Address=str_replace(Address,'Suitainability','Sustainability'),
         Address=str_replace(Address,'Tanaman Industri, West Kalimantan','Tanaman Industri, West Kalimantan, Indonesia'),
         Address=str_remove(Address,'Untere Karspüle 2, 37073 '),
         Address=str_remove(Address,'Zollikerstrasse 107, 8008 '),
         Address=str_replace(Address,'Reboisasi Eden Papua','Reboisasi Eden Papua, Indonesia'),
         Address=str_replace(Address,'Wilmar Business Indonesia Polytechnic',
                             'Wilmar Business Indonesia Polytechnic, Medan, Indonesia'),
         Address=str_replace(Address,'Direktorat Pengelolaan Koleksi Ilmiah','Directorate of Scientific Collection Management'),
         Address=str_replace(Address,'Universitas Syiah Kuala, Aceh',
                             'Universitas Syiah Kuala, Aceh, Indonesia'),
         Address=str_remove(Address,' 20001')) %>%
    distinct() %>%
  add_column('Institute_order'=1:nrow(.))

Author_order=Author_data_clean=read_csv('AUTHORSHIP_alpha diversity_submission.csv') %>% 
  rename('conf'='Confirmed co-authorship') %>% 
  drop_na('conf') %>% 
  select(Name)

Author_data_clean=read_csv('AUTHORSHIP_alpha diversity_submission.csv') %>% 
  rename('conf'='Confirmed co-authorship') %>% 
  drop_na('conf') %>% 
  select(Name,Email,Address) %>%
  mutate(Address=str_replace(Address,'&','and'),
         Address=str_replace(Address,'-',', '),
         Address=str_replace(Address,'\\ ,',',')) %>%
  separate(Address,into = c('Address_1','Address_2','Address_3'),sep = '; ') %>%
  pivot_longer(starts_with('Address'),names_to='Add_no',values_to = 'Address') %>% 
  drop_na() %>%
  select(-Add_no) %>%
  mutate(Address=str_replace(Address,'Jawa, Barat','Jawa Barat'),
         Address=str_replace(Address,'\\, and',' and'),
         Address=str_replace(Address,'National Research and Innovation Agency of the Republic of Indonesia','National Research and Innovation Agency (BRIN), Indonesia'),
         Address=str_replace(Address,'Direktorat Pengelolaan Koleksi Ilmiah','Directorate of Scientific Collection Management'),
         Address=str_replace(Address,'Etnobiology','Ethnobiology'),
         Address=str_remove(Address,'. JL Raya Jakarta Bogor km 46, Cibinong West Java, Indonesia'),
         Address=str_replace(Address,'Kota Bogor, Jawa Barat, Indonesia.','Gunung Batu, Bogor, Indonesia'),
         Address=str_remove(Address,'Jalan Inamberi Susweni, Manokwari,  Papua barat, '),
         Address=str_remove(Address,'Chester Street, Manchester, M1 5GD, '),
         Address=str_remove(Address,'Jalan Tungku Link, Gadong, BE1410, '),
         Address=str_remove(Address,'11800 Penang, '),
         Address=str_remove(Address,' 98314'),
         Address=str_remove(Address,'Jalan Gunung Salju Amban, '),
         Address=str_replace(Address,'Sceineces','Sciences'),
         Address=str_replace(Address,'  ',' '),
         Address=str_replace(Address,'2109 ',''),
         Address=str_replace(Address,'Suitainability','Sustainability'),
         Address=str_replace(Address,'Tanaman Industri, West Kalimantan','Tanaman Industri, West Kalimantan, Indonesia'),
         Address=str_replace(Address,'Universitas Papua, Manokwari, Indonesia','Fakultas Kehutanan, Universitas Papua, Manokwari, Papua Barat, Indonesia'),
         Address=str_remove(Address,'Untere Karspüle 2, 37073 '),
         Address=str_remove(Address,'Zollikerstrasse 107, 8008 '),
         Address=str_replace(Address,'Reboisasi Eden Papua','Reboisasi Eden Papua, Indonesia'),
         Address=str_replace(Address,'Wilmar Business Indonesia Polytechnic',
                             'Wilmar Business Indonesia Polytechnic, Medan, Indonesia'),
         Address=str_replace(Address,'Universitas Syiah Kuala, Aceh',
                             'Universitas Syiah Kuala, Aceh, Indonesia'),
         Address=str_remove(Address,' 20001')) %>%
    distinct() %>% left_join(Institute_order,by='Address') %>%
  arrange(Institute_order) 

List_author=left_join(Author_order,Author_data_clean) %>%
  select(Name,Institute_order) %>% 
  pivot_wider(values_from = Institute_order,names_from ='Name') %>% 
  pivot_longer(1:ncol(.),names_to='Name',values_to = 'Institute_no') %>% 
  mutate(Institute_no=str_replace_all(Institute_no,':','\\,'),
         Institute_no=str_remove(Institute_no,'c\\('),
         Institute_no=str_remove(Institute_no,'\\)'),
         Institute_no=str_replace_all(Institute_no,'\\, ','\\,')) %>% 
  add_column(up_case='^') %>% 
  unite('Institute_no',c('up_case','Institute_no'),sep = '',remove=F) %>%
  unite('Institute_no',c('Institute_no','up_case'),sep = '') %>%
  unite('Name_Inst',c('Name','Institute_no'),sep = ' ') 

List_institutes=Institute_order %>%
  add_column(up_case='^') %>% 
  unite('Institute_order',c('up_case','Institute_order'),sep = '',remove=F) %>%
  unite('Institute_order',c('Institute_order','up_case'),sep = '') %>%
  unite('Inst_list',c('Institute_order','Address'),sep = ' ')
 
Names_vect=as.character(List_author)
Inst_vect=as.character(List_institutes)


```

`r str_remove_all(Names_vect,'\\"') %>% str_remove('c\\(') %>% str_remove_all('\\)') `  

`r str_remove_all(Inst_vect,'\\"') %>% str_remove('c\\(') %>% str_remove('\\)$') `

__Acknowledgements__  
LAT was supported by the Botanical Research Fund, Coalbourn Trust, Bentham Moxon Trust and Emily Holmes scholarships. FQB and colleagues were supported by the British Council grant 217539700. TMAU and GLCB were supported by NERC/Newton fund grant NE/S007059/1. We thank all our colleagues and field assistants who helped with forest plot censuses across Indonesia over many years. We are particularly grateful to our late colleagues: George Argent, David Frodin, John Proctor, Soedarsono Riswan, Kade Sidiyasa, Suriantata and Tim Whitmore whose work contributed to this manuscript and who made broader contributions to our understanding of Indonesian biogeography and ecology.  
We acknowledge the research permits provided by LIPI, RisTek and BRIN for work in Indonesia over many years: 88/SIP/FRP/E5/Dit.KI/11/2016, 351/E5/E5.4/SIP/2019, 149/SIP/IV/FR/3/2023 (LAT), 5244/V.3/KS/1998, 3943/V3/KS/1999, 2010/IPH.1/KS.01/2005, 1790/FRP/SM/VIII/2008 (FQB), 034/SIP/FRP/II/2011 (FB), 385/SIP/FRP/E5/Dit.KI/IX/2016 (RCL), 0251/SIP/FRP/XI/2010 (and extensions) (COW). In addition, we thank forestry departments across Indonesia for granting SIMAKSI paperwork for access to protected areas.

__From earthquakes to island area: multi-scale effects upon local diversity__  

__Abstract__ (198/300 words max)

Tropical forests occupy small coral atolls to the vast Amazon basin. They occur across bioregions with different geological and climatic history. Differences in area and bioregional history shape species immigration, extinction and diversification. How this effects local diversity is unclear. The Indonesian archipelago hosts thousands of tree species whose coexistence should depend upon these factors. Using a novel dataset of 215 Indonesian forest plots, across fifteen islands ranging in area from 120 km^2^ to 785,000 km^2^, we apply Gaussian mixed effects models to examine the simultaneous effects of environment, earthquake proximity, island area and bioregion upon tree diversity for trees $\geq$ 10 cm diameter at breast height. We find that tree diversity declines with precipitation seasonality and increases with island area. Accounting for the effects of environment and island area we show that the westernmost bioregion Sunda has greater local diversity than Wallacea, which in turn has greater local diversity than easternmost Sahul. However, when the model includes geological activity (here proximity to major earthquakes), bioregion differences are reduced. Overall, results indicate that multi-scale, current and historic effects dictate tree diversity. These multi-scale drivers should not be ignored when studying biodiversity gradients and their impacts upon ecosystem function. 

__Keywords:__ biogeographic regions, biodiversity, diversity gradients, echo pattern, forest plots, island biogeography  

\newpage

__Introduction__

The determinants of local species diversity are scale dependent [@willis_species_2002]. Thus, local conditions interplay with large-scale speciation and extinction that controls the number of species that can disperse and persist in a community [@zobel_relative_1997; @spasojevic_integrating_2018; @trethowan_environment-dependent_2023; @brodie_fruit_2022; @ricklefs_species_1993]. In Indonesia and neighbouring countries, we find high plant species richness unmatched in other archipelagoes [@joyce_checklist_2020]. There are many factors that may influence the country's local diversity [van @van_steenis_hierarchy_1950; @whitmore_vegetation_1984]. For example, island area and biogeographic history may influence diversification dynamics and thus the number of tree species that locally co-exist [@blonder_predictability_2017; @germain_species_2016; @herrera-alsina_ancient_2021; @kooyman_origins_2019; @mccullough_wallacean_2022; @craven_dissecting_2019].  Climate and local soil conditions, in turn, also influence local tree diversity [@slik_environmental_2009; @laumonier_last_2018]. So far, however, our understanding of the multi-scale drivers of local plant diversity in tropical archipelagos has been limited [@brambach_diversity_2017; @trethowan_floristics_2020]. 

Tropical tree diversity at small spatial scales (e.g. < 10 ha) may be determined by local environmental conditions [@ricklefs_community_1987]. For instance, tree diversity declines with elevation because many species do not tolerate lower temperatures [@slik_environmental_2009; @brambach_diversity_2017; @rehm_freezing_2015; @trethowan_plant_2023]. Likewise, seasonally dry forests have lower diversity because fewer species can cope with extended periods of drought [@davidar_changes_2005; @baltzer_role_2008]. Infertile soils, similarly, remove species with high nutrient requirements [@draper_peatland_2018; @slik_environmental_2009; @camara-leret_modelling_2017]. Indonesia is part of the largest tropical archipelago in the world and encompasses a wide range of environmental gradients: from mangroves to alpine grasslands and from constantly wet to seasonally dry [@trethowan_environmental_2022; @kooyman_origins_2019]. Therefore, Indonesia provides a great opportunity to study the relationship between environmental variation and local tree species diversity (Fig. 1a).

Additionally, the impacts of geological activity upon Indonesian diversity require attention. Volcanic eruptions and earthquakes may cause major species turnover events that could have an archipelago-wide impact upon current diversity [@lavigne_source_2013; @whelley_frequency_2015; @sadili_forest_2022]. 

Island area is often cited as a key driver of the number of species that can coexist locally [@karger_island_2014; @ibanez_regional_2018; @schrader_plants_2019; @schrader_requirements_2019]. Larger islands support a larger species pool for local communities, which therefore have more potential species [@ricklefs_community_1987]. This ‘echo pattern’ coined by  @rosenzweig_echo_1999 also accounts for the fact that on larger islands species that go locally extinct may, over time, re-establish because they survived in neighbouring populations. Larger islands also have higher immigration rates [@brown_turnover_1977] and are more likely to witness in-situ speciation, increasing the pool of species available at local scales [@ricklefs_comprehensive_2004; @borges_time_2009]. Unlike tropical continental forests, island area effects could be prominent in tropical archipelagoes like Indonesia where there are numerous islands with considerable variation in size [@schrader_plants_2019; @roos_species_2004; @sin_bird_2022].

Geological history has left an imprint upon current diversity patterns across the world's biogeographic regions or 'bioregions' which we use here for brevity [@herrera-alsina_ancient_2021; @ricklefs_region_2016; @hagen_earth_2021]. Indonesia straddles three island-dominated bioregions that differ in their histories of uplift, persistence above sea level and climate [@kooyman_origins_2019; @ali_wallaces_2021; @morley_complex_2018]. Mesozoic emergence of the backbone of Sunda, the westernmost bioregion, preceded Java formed during the Pliocene [@hall_southeast_2009]. Wet tropical forest became widespread across Sunda by the Miocene [@morley_assembly_2018; @wilf_first_2022]. Sunda's land area fluctuated during the Quaternary when island connections increased during glacials and decreased during interglacials [@voris_maps_2000; @cannon_current_2009; @husson_evidence_2020]. The easternmost region of Sahul began to emerge in the Oligocene but formation of most of New Guinea's land area and central mountain range occurred in the late Miocene and Pliocene [@van_ufford_cenozoic_2005; @toussaint_towering_2014]. During Pleistocene glacial maxima, lower sea levels resulted in land connections between New Guinea and Australia, although Sahul was largely characterized by dry desert [@hope_quatenary_1994; @toon_relationships_2017; @byrne_birth_2008; @lohman_biogeography_2011]. Sulawesi the largest island in the central Wallacean region amalgamated from a number of small islands in the Pliocene and Pleistocene, this was likely when Halmahera formed its current configuration [@nugraha_late_2018; @hall_late_1988]. Other Wallacean islands are even younger; Timor, Yamdena and Seram's uplift occurring in the late Pliocene [@hall_southeast_2009]. Previous palynological and phylogenetic studies have mainly concerned the presence of lineages [@morley_assembly_2018; @kooyman_origins_2019; @yap_filters_2018; @hamilton_16000-year_2019; @crayn_sahulsunda_2015]. Here, we propose hypotheses that consider the impact of geological and climatic histories on diversity. The rapid recent formation of Wallacea and Sahul's environmental gradients could have promoted diversification and resulted in greater local diversity [@rowe_oceanic_2019; @kennedy_diversification_2022; @toussaint_towering_2014; @struebig_safeguarding_2022; @mccullough_wallacean_2022; @roycroft_new_2022]. More likely, the longer residence time of terrestrial areas in Sunda may have resulted in the build-up of greater regional diversity increasing the possible number of species able to coexist locally [de @de_bruyn_borneo_2014; @oconnell_within-island_2018]. Added to that, widespread drought during glacial maxima except for equatorial Sunda likely caused the extinction of many tropical species in Wallacea and Sahul [@wurster_savanna_2019; @byrne_decline_2011; @hamilton_16000-year_2019; @morley_development_1981; @cannon_current_2009; @cannon_phylogeography_2003]. Whilst, the legacy of paleoclimate and bioregion has recently been shown to influence vertebrate distributions [@skeels_paleoenvironments_2023], we do not have a clear idea of effects upon local diversity.

Here we test predictions that local tree diversity __(1)__ declines with elevation, precipitation seasonality, soil infertility and geological activity, __(2)__ increases with island area and __(3)__ is greater in the older geological and climatically stable setting of Sunda compared to Wallacea and Sahul. We therefore test the fine scale effects of prediction __(1)__ and large scale, historic, species-pool effects of predictions __(2)__ and __(3)__.  Allowing examination of these predictions, in cohort, for the first time across a megadiverse region.

```{r data-gather-clean,eval=F,message=F,error=F,echo=F}

setwd("/Users/liamtrethowan/Documents/Indo_alpha_diversity")
library(tidyverse)

clean_plot_meta=read_csv('AlphaDiversity_22_04_22.csv') %>%
  filter(Composition_data_gathered=='yes',
         !is.na(Lat)) %>%
  mutate(Location=case_when(Island=='Yamdena'~Plot_code,
                            Location=='Danau Kalimpa\'a'~'Danau Kalimpaa',
                            T~Location)) %>%
  dplyr::select(Location, Island,Lat,Long,
                Elevation='Elevation (m)',
                Area='Plot Size (ha)') %>%
  mutate(Area=as.numeric(Area)) %>%
  arrange(Long) %>% 
  mutate(num = 1:n()) %>% 
  unite('ID',c(num,Island),remove = F) %>% dplyr::select(-num)

#write_csv(clean_plot_meta,'clean_plot_meta.csv')

plot_data=rbind(read_csv('Ferry_plots.csv') %>% 
  select(Location,Family,Species='species (original)') %>%
  inner_join(clean_plot_meta,'Location') %>%
  group_by(ID,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Ferry_collaborator_data.csv') %>% 
  select(Location,Family,Species='species (original)') %>%
  filter(!str_detect(Location,'Heist')) %>% 
  mutate(Location=case_when(str_detect(Location,'T-')~'Malinau',
                            T~Location)) %>% 
  inner_join(clean_plot_meta,'Location') %>% 
  filter(!is.na(Species)) %>% 
  mutate(Species=str_replace(Species,'\\?','sp.')) %>%
  group_by(ID,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Inventory_Data_Sulawesi_LLNP.csv') %>% 
  filter(Individual==1 & Dbh >= 10) %>%
  select(Plot,Elevation,Family,genus,sp_epithet,Individual) %>%
  unite('Species',c(genus,sp_epithet),sep=' ') %>% 
  mutate(Location=case_when(Plot=='S0700'~'Rantena',
                            Plot=='S0850'~'Tokepangana',
                            Plot=='S1200'~'Tarara',
                            Plot=='S1450'~'Torongkilo',
                            Plot=='S1650'~'Balamba',
                            Plot=='S1950'~'Pantakleabae',
                            Plot=='S2150'~'Tutu Malemo',
                            Plot=='S2350'~'Rorekautimbu 2')) %>%
  select(Location,Family,Species) %>%
  inner_join(clean_plot_meta,'Location') %>%
  group_by(ID,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Yamdena_YL.csv') %>% 
  select(Location='Plot ID', GENUS,SPECIES) %>%
  unite('Species',c(GENUS,SPECIES),sep=' ') %>%
  inner_join(clean_plot_meta,'Location') %>%
  group_by(ID,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Wilkie_Kalimantan.csv') %>% 
  select(PLOT,GENUS,SPECIES,Dbh='diameter (cm)') %>% 
  filter(Dbh >=10) %>%
  unite('Species',c(GENUS,SPECIES),sep=' ',na.rm=T) %>%
  add_column(place='Wanariset Sangai') %>%
  unite('Location',c(place,PLOT),sep='_') %>%
  select(-Dbh) %>%
  inner_join(clean_plot_meta,'Location') %>%
  group_by(ID,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Pulau_Weh.csv') %>% 
  select(Plot,Species) %>% 
  mutate(Location=case_when(Plot==1~'Ujong Nol 1',
                            Plot==2~'Lhong Angeen 1',
                            Plot==3~'Lhong Angeen 2',
                            Plot==4~'KM Nol 1',
                            Plot==5~'Paya Sinara')) %>%
  select(Location,Species) %>%
  inner_join(clean_plot_meta,'Location') %>%
  group_by(ID,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Batang Gadis_composition.csv') %>% 
  add_column(Location='Batang Gadis, Aek Nangali') %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Foja_composition.csv') %>% 
  add_column(Location='Foja') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Halmahera Tapayo_composition.csv') %>% 
  add_column(Location='Halmahera, Tapayo') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Kerinci_composition.csv') %>%
  add_column(Location='Gunung Kerinci') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Halmahera Weda Bay_composition.csv') %>%
  add_column(Location='Halmahera, Weda Bay') %>% 
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
  read_csv('Sulawesi Kalimpa_composition.csv') %>% 
  add_column(Location='Danau Kalimpaa') %>% 
  select(Species,abundance,Location) %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Wawouwai 300m_composition.csv') %>%
  add_column(Location='Bukit Wawouwai_300') %>% 
  select(Species,abundance,Location) %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Wawouwai 500m_composition.csv') %>%
  add_column(Location='Bukit Wawouwai_500') %>% 
  select(Species,abundance,Location) %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Bodogol_composition.csv') %>%
  add_column(Location='Bodogol') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Buton Utara_composition.csv') %>%
  add_column(Location='Buton Utara') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Gunung Keneng_composition.csv') %>% 
  add_column(Location='Gunung Keneng') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Kayan Mentarang Selatan_composition.csv') %>%
  add_column(Location='Kayan Mentarang_South') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Kayan Mentarang Utara_composition.csv') %>%
  add_column(Location='Kayan Mentarang_North') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('LL Petak 1_composition.csv') %>%
  add_column(Location='Lore Lindu_Petak_1') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('LL Petak 2_composition.csv') %>%
  add_column(Location='Lore Lindu_Petak_2') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('LL Petak 3_composition.csv') %>%
  add_column(Location='Lore Lindu_Petak_3') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Mensemat Sambas_composition.csv') %>%
  add_column(Location='Mensemat-Sambas') %>% 
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Pasir Ipis_composition.csv') %>%
  add_column(Location='Pasir Ipis') %>%
  select(Species,abundance,Location) %>%
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Willis 1500_composition.csv') %>%
  add_column(Location='Gunung Willis_1500') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Willis 1300_composition.csv') %>%
  add_column(Location='Gunung Willis_1300') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Willis 1400_composition.csv') %>%
  add_column(Location='Gunung Willis_1400') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Willis 1200_composition.csv') %>%
  add_column(Location='Gunung Willis_1200') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Willis 1100_composition.csv') %>%
  add_column(Location='Gunung Willis_1100') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Wanariset Samboja_composition.csv') %>%
  add_column(Location='Wanariset') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Sulawesi_updated_2.csv') %>%
  select(PLOT,Species='original identification') %>%
  mutate(Location=case_when(PLOT==1~'Bualemo_1',
                            PLOT==2~'Bualemo_2',
                            PLOT==3~'Wawonii_1',
                            PLOT==4~'Wawonii_2',
                            PLOT==5~'Wawonii_3',
                            PLOT==6~'Wawonii_4',
                            PLOT==7~'Morowali_1',
                            PLOT==8~'Morowali_2',
                            PLOT==9~'Bualemo_3',
                            PLOT==10~'Bualemo_4')) %>%
  select(-PLOT) %>%
  group_by(Location,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Sumbawa_plots_composition.csv') %>% 
  select(plot,Species) %>%
  mutate(Location=case_when(plot==1~'Mataiyang_1',
                            plot==2~'Mataiyang_2',
                            plot==3~'Mataiyang_3',
                            plot==4~'Mataiyang_4',
                            plot==5~'Mataiyang_5',
                            plot==6~'Mataiyang_6',
                            plot==7~'Mataiyang_7',
                            plot==8~'Mataiyang_8',
                            plot==9~'Mataiyang_9',
                            plot==10~'Mataiyang_10',
                            plot==11~'Mataiyang_11',
                            plot==12~'Mataiyang_12',
                            plot==13~'Pedauh_1',
                            plot==14~'Pedauh_2',
                            plot==15~'Pedauh_3',
                            plot==16~'Pedauh_4')) %>%
  select(-plot) %>%
  group_by(Location,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Barito Ulu_composition.csv') %>% 
  filter(Genus!='unknown',
         Genus!='Unknown') %>% 
  add_column(Location='Barito Ulu') %>%
  mutate(Plot=Plot-18) %>%
  unite('Location',c('Location','Plot'),sep='_') %>%
  select(Location,Species) %>%
  group_by(Location,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Bangka_composition.csv') %>% 
  add_column(Location='Bangka') %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('GunungMeja_2021-12-08_abundance.csv') %>%
  add_column(Location='Gunung Meja') %>% 
   inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('TTL.csv') %>% select(PlotID,Species) %>% add_column('Location'='TTL') %>% 
  unite('Location',c(Location,PlotID),sep='_') %>% group_by(Location,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('Wapoga.csv') %>% select(PlotID,Species) %>% add_column('Location'='Wapoga') %>% 
  unite('Location',c(Location,PlotID),sep='_') %>% group_by(Location,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long),
read_csv('MML.csv') %>% select(PlotID,Species) %>% add_column('Location'='MML') %>% 
  unite('Location',c(Location,PlotID),sep='_') %>% group_by(Location,Species) %>% 
  mutate(abundance=n()) %>%
  distinct() %>% 
  inner_join(clean_plot_meta,'Location') %>%
  select(Species,abundance,Location,ID,Island,Lat,Long)) %>%
  ungroup()
  
plot_data_clean_1=plot_data %>% 
  filter(!str_detect(Species,'Unknown')) %>%
  filter(!str_detect(Species,'Indet')) %>%
  filter(!str_detect(Species,'Need Check')) %>%
  filter(Species!='',
         Species!='? ?') %>% 
  separate(Species,c('Species','Auth'),sep='\\(') %>%
  select(-Auth) %>% 
  mutate(Species=str_replace(Species,'sp ','sp.'),
         Species=str_replace(Species,'cf ','cf\\. '),
         Species=str_replace(Species,'aff\\ ','aff\\.'),
         Species=str_replace(Species,'\\. ','\\.'),
         Species=str_replace(Species,'\\ \\ ','\\ '),
         Species=str_replace(Species,'indet','sp.'),
         Species=str_replace(Species,'Dipt\\.','Dipterocarpus\\ ')) %>% 
  separate(Species,c('Genus','Species','Auth'),sep=' ') %>%
  select(-Auth) %>% 
  mutate(Species=str_remove(Species,'\\d$'),
         Species=str_remove(Species,'\\d$'),
         Species=str_remove(Species,'\\?'),
         Species=str_replace(Species,'sp\\.','sp'),
         Species=str_replace(Species,'^$','sp'),
         Species=str_remove(Species,'_'),
         Species=replace_na(Species,'sp'),
         Genus=str_replace(Genus,'teijsmanniodendron','Teijsmanniodendron'),
         Genus=str_replace(Genus,'Teijsmanniodendron0','Teijsmanniodendron')) %>% 
  separate(Species,'Species',sep='\\/') %>% 
  filter(Genus!='Annonaceae',
         Genus!='Apocynaceae',
         Genus!='Rosaceae',
         Genus!='Rubiaceae',
         Genus!='Rubiaceae?',
         Genus!='Rutaceae',
         Genus!='Sapindaceae',
         Genus!='Sterculiaceae',
         Genus!='Theaceae',
         Genus!='Anacardiaceae',
         Genus!='Bombacaceae',
         Genus!='Burseraceae',
         Genus!='Dipterocarpaceae',
         Genus!='Elaeocarpaceae',
         Genus!='Euphorbiaceae',
         Genus!='Fabaceae',
         Genus!='Fagaceae',
         Genus!='Flacourtiaceae',
         Genus!='Lauraceae',
         Genus!='Leguminosae',
         Genus!='Melaiceae',
         Genus!='Melastomataceae',
         Genus!='Meliaceae',
         Genus!='Mimosaceae',
         Genus!='Moraceae',
         Genus!='Myristicaceae',
         Genus!='Myrsinaceae',
         Genus!='Oxalidaceae',
         Genus!='Pentaceae',
         Genus!='Sapotaceae',
         Genus!='Dead',
         Genus!='NA',
         Genus!='Unidentified') %>%
  unite('Species',c('Genus','Species'),sep=' ') %>%
  mutate(Species=str_replace(Species,'spnov\\.','sp'),
         Species=str_replace(Species,'spA','sp'),
         Species=str_replace(Species,'\\[racemosasp\\]','racemosa'),
         Species=str_remove(Species,'\\d'),
         Species=str_remove(Species,'^cf\\.'),
         Species=str_remove(Species,'\\,')) %>%
  filter(Species!='SA HERB34')


##library(kewr)
####### download wcvp via kewr

plot_data_clean_2=plot_data_clean_1 %>%
  filter(Species!='Cephalomapha sp',
         Species!='Cowica sp',
         Species!='Heotrewia sp',
         Species!='Hyporosa sp',
         Species!='Polidocarpus majadum',
         Species!='Crisophyllum sp',
         Species!='Euphorbiaceae sp') %>%
  mutate(Species=str_replace(Species,'Achidendron','Archidendron'),
         Species=str_replace(Species,'Aceratium hirsutum','Aceratium sp'),
         Species=str_replace(Species,'Adzarachta','Azadirachta'),
         Species=str_replace(Species,'Anispotera','Anisoptera'),
         Species=str_replace(Species,'Agalia','Aglaia'),
         Species=str_replace(Species,'Agalai','Aglaia'),
         Species=str_replace(Species,'Aglaia specibs','Aglaia sp'),
         Species=str_replace(Species,'Alangeum','Alangium'),
         Species=str_replace(Species,'Aleurites moluccana','Aleurites moluccanus'),
         Species=str_replace(Species,'Alseodaphne ceratoxylon','Alseodaphne sp'),
         Species=str_replace(Species,'Alseodaphne umbellifolia','Alseodaphne umbelliflora'),
         Species=str_replace(Species,'Anthocephalus indicus','Neolamarckia cadamba'),
         Species=str_replace(Species,'Anthiaris','Antiaris'),
         Species=str_replace(Species,'Antidesma tetrandum','Antidesma tetrandrum'),
         Species=str_replace(Species,'Aporosa elemeri','Aporosa elmeri'),
         Species=str_replace(Species,'Aporosa sphaeridophora','Aporosa sphaeridiophora'),
         Species=str_replace(Species,'Aporusa','Aporosa'),
         Species=str_replace(Species,'Archidendro','Archidendron'),
         Species=str_replace(Species,'Archidendronn','Archidendron'),
         Species=str_replace(Species,'Archidendron clyperaea','Archidendron clypearia'),
         Species=str_replace(Species,'Archidendron clyperea','Archidendron clypearia'),
         Species=str_replace(Species,'Artocarpus integra','Artocarpus integer'),
         Species=str_replace(Species,'Artocarpus tamara$','Artocarpus tamaran'),
         Species=str_replace(Species,'Astronia javanica','Astronia sp'),
         Species=str_replace(Species,'Astronia spectablis','Astronia spectabilis'),
         Species=str_replace(Species,'Averrhola','Averrhoa'),
         Species=str_replace(Species,'Baccaurea parvifolia','Baccaurea parviflora'),
         Species=str_replace(Species,'Baccaurea tetandra','Baccaurea tetrandra'),
         Species=str_replace(Species,'Barringtonia giganto','Barringtonia gigantostachya'),
         Species=str_replace(Species,'Blumeodendron elatriospermum','Blumeodendron sp'),
         Species=str_replace(Species,'Bombax velutinii','Bombax valetonii'),
         Species=str_replace(Species,'Borassodendron borneensis','Borassodendron borneense'),
         Species=str_replace(Species,'Botryphora','Botryophora'),
         Species=str_replace(Species,'Brackenridgea palultris','Brackenridgea palustris'),
         Species=str_replace(Species,'Buchanania sessilifolia','Buchanania sessifolia'),
         Species=str_replace(Species,'Calophyllum nodusum','Calophyllum nodosum'),
         Species=str_replace(Species,'Canarium patentinervum','Canarium patentinervium'),
         Species=str_replace(Species,'Canthium umbelliferum','Canthium umbelligerum'),
         Species=str_replace(Species,'Canthium aff.arborescens','Canthium aff.arboreum'),
         Species=str_replace(Species,'Carydaphnopsis','Caryodaphnopsis'),
         Species=str_replace(Species,'Castanopsis aviformis','Castanopsis oviformis'),
         Species=str_replace(Species,'Castonopsis','Castanopsis'),
         Species=str_replace(Species,'Casuarina junghuniana','Casuarina junghuhniana'),
         Species=str_replace(Species,'Celtis lauricum','Celtis sp'),
         Species=str_replace(Species,'Celtis philippinensis','Celtis philippensis'),
         Species=str_replace(Species,'Chisoceton','Chisocheton'),
         Species=str_replace(Species,'Cheisocheton','Chisocheton'),
         Species=str_replace(Species,'Cheliosa','Cheilosa'),
         Species=str_replace(Species,'Chionanthes','Chionanthus'),
         Species=str_replace(Species,'Chionanthus fluriflorus','Chionanthus pluriflorus'),
         Species=str_replace(Species,'Chionantus','Chionanthus'),
         Species=str_replace(Species,'Chisocheton maerophyllus','Chisocheton macrophyllus'),
         Species=str_replace(Species,'Chisocheton tripetala','Chisocheton sp'),
         Species=str_replace(Species,'Cinnamomom','Cinnamomum'),
         Species=str_replace(Species,'Cinnamonum','Cinnamomum'),
         Species=str_replace(Species,'Cleistanthus psuedopodocarpus','Cleistanthus pseudopodocarpus'),
         Species=str_replace(Species,'Cleistanthus subcaudatus','Cleistanthus sp'),
         Species=str_replace(Species,'Cleistocalyx paxii','Cleistocalyx sp'),
         Species=str_replace(Species,'Cotylobium','Cotylelobium'),
         Species=str_replace(Species,'Crataeva','Crateva'),
         Species=str_replace(Species,'Cryptocarya cumingii','Cryptocarya sp'),
         Species=str_replace(Species,'Cryptocarya griffithii','Cryptocarya griffithiana'),
         Species=str_replace(Species,'Cryptocarya intectoria','Cryptocarya sp'),
         Species=str_replace(Species,'Cryptocarya obtusa','Cryptocarya sp'),
         Species=str_replace(Species,'Ctenolophon parviflorus','Ctenolophon parvifolius'),
         Species=str_replace(Species,'Cyathea contaminan$','Cyathea contaminans'),
         Species=str_replace(Species,'Cyathocalyx sumatrana','Cyathocalyx sumatranus'),
         Species=str_replace(Species,'Cyathocaylx carinatus','Cyathocaylx sp'),
         Species=str_replace(Species,'Dacriodes','Dacryodes'),
         Species=str_replace(Species,'Dacryodes costrata','Dacryodes costata'),
         Species=str_replace(Species,'Dehaasia borneensis','Dehaasia paradoxa'),
         Species=str_replace(Species,'Delonix redgia','Delonix regia'),
         Species=str_replace(Species,'Diailium indum','Dialium indum'),
         Species=str_replace(Species,'Dialium indicatum','Dialium indum'),
         Species=str_replace(Species,'Dialium indicum','Dialium indum'),
         Species=str_replace(Species,'Didymocarpus longan','Dimocarpus longan'),
         Species=str_replace(Species,'Dillenia grandiflora','Dillenia grandifolia'),
         Species=str_replace(Species,'Dillenia Pteropoda','Dillenia pteropoda'),
         Species=str_replace(Species,'Dimelodendron','Pimelodendron'),
         Species=str_replace(Species,'Dimocarpus jumatus','Dimocarpus fumatus'),
         Species=str_replace(Species,'Diospyros boerlageana','Diospyros sp'),
         Species=str_replace(Species,'Diospyros ferruginascens','Diospyros ferruginescens'),
         Species=str_replace(Species,'Diospyros laevigata','Diospyros foxworthyi'),
         Species=str_replace(Species,'Diospyros oblongata','Diospyros maritima'),
         Species=str_replace(Species,'Diospyros topsioides','Diospyros sp'),
         Species=str_replace(Species,'Diospyros venusa','Diospyros sp'),
         Species=str_replace(Species,'Dipterocarpus crinatus','Dipterocarpus crinitus'),
         Species=str_replace(Species,'Dipterocarpus curryncus','Dipterocarpus eurhynchus'),
         Species=str_replace(Species,'Dipterocarpus curyncus','Dipterocarpus eurhynchus'),
         Species=str_replace(Species,'Dipterocarpus eurynchus','Dipterocarpus eurhynchus'),
         Species=str_replace(Species,'Dipterocarpus euryncus','Dipterocarpus eurhynchus'),
         Species=str_replace(Species,'Disopyros','Diospyros'),
         Species=str_replace(Species,'Dryobalanops cf.sumatraensis','Dryobalanops cf.sumatrensis'),
         Species=str_replace(Species,'Dryobanalops','Dryobalanops'),
         Species=str_replace(Species,'Drypetes minahasae','Drypetes minahassae'),
         Species=str_replace(Species,'Drypetes minahase','Drypetes minahassae'),
         Species=str_replace(Species,'Drypetes pendulata','Drypetes pendula'),
         Species=str_replace(Species,'Durio graviolens','Durio graveolens'),
         Species=str_replace(Species,'Durio testudinarum','Durio testudinarius'),
         Species=str_replace(Species,'Dysoxylum pachyrache','Dysoxylum pachyrhache'),
         Species=str_replace(Species,'Dysoxylum rubiginosa','Dysoxylum sp'),
         Species=str_replace(Species,'Elaeocarpus oxypyrens','Elaeocarpus oxypyren'),
         Species=str_replace(Species,'Elaeocarpus polystachys','Elaeocarpus polystachyus'),
         Species=str_replace(Species,'Elaeocarpus sphaeriscus','Elaeocarpus sphaericus'),
         Species=str_replace(Species,'Elastostachys','Elattostachys'),
         Species=str_replace(Species,'Engelhardtia','Engelhardia'),
         Species=str_replace(Species,'Erytroxylum','Erythroxylum'),
         Species=str_replace(Species,'Eugenia cerin$','Eugenia cerina'),
         Species=str_replace(Species,'Eugenia cuminii','Eugenia cumini'),
         Species=str_replace(Species,'Eusisideroxylon zwageri','Eusideroxylon zwageri'),
         Species=str_replace(Species,'Eusyderoxylem zwagerii','Eusideroxylon zwageri'),
         Species=str_replace(Species,'Evodia malayana','Euodia malayana'),
         Species=str_replace(Species,'Evodia speciosa','Euodia speciosa'),
         Species=str_replace(Species,'Ficus ampelas','Ficus ampelos'),
         Species=str_replace(Species,'Ficus crassiramica','Ficus sp'),
         Species=str_replace(Species,'Ficus stupender','Ficus stupenda'),
         Species=str_replace(Species,'Ficus tracipison','Ficus trachypison'),
         Species=str_replace(Species,'Flacourtia caesaria','Flacourtia sp'),
         Species=str_replace(Species,'Fragraea','Fagraea'),
         Species=str_replace(Species,'Ganua motleana','Ganua mottleyana'),
         Species=str_replace(Species,'Ganua motleaua','Ganua mottleyana'),
         Species=str_replace(Species,'Garcinia cf.rheadii','Garcinia cf.rheedii'),
         Species=str_replace(Species,'Garcinia homriana','Garcinia hombroniana'),
         Species=str_replace(Species,'Garcinia laterifolia','Garcinia lateriflora'),
         Species=str_replace(Species,'Garcinia malaccesis','Garcinia malaccensis'),
         Species=str_replace(Species,'Gironniera coltidifolia','Gironniera celtidifolia'),
         Species=str_replace(Species,'Gluta rhengas','Gluta renghas'),
         Species=str_replace(Species,'Gluta torguata','Gluta torquata'),
         Species=str_replace(Species,'Gluta velotina','Gluta velutina'),
         Species=str_replace(Species,'Glutta cf.rengas','Gluta cf.renghas'),
         Species=str_replace(Species,'Gomphandra glabosa','Gomphandra sp'),
         Species=str_replace(Species,'Gordonia amboinense','Gordonia amboinensis'),
         Species=str_replace(Species,'Gordonia cordifolia','Gordonia sp'),
         Species=str_replace(Species,'Gordonia singaporioana','Gordonia singaporeana'),
         Species=str_replace(Species,'Grewia cf.desmatifolia','Grewia sp'),
         Species=str_replace(Species,'Guensia pentandra','Geunsia pentandra'),
         Species=str_replace(Species,'Guettada speciosa','Guettarda speciosa'),
         Species=str_replace(Species,'Gymnacran thera','Gymnacranthera sp'),
         Species=str_replace(Species,'Gymnacranthera bancanus','Gymnacranthera bancana'),
         Species=str_replace(Species,'Gymnacranthera sp','Gymnacranthera sp'),
         Species=str_replace(Species,'Gymnancrahthera','Gymnacranthera'),
         Species=str_replace(Species,'Gymnancrahthera forbesii','Gymnacranthera forbesii'),
         Species=str_replace(Species,'Gymnostoma sumatrana','Gymnostoma sumatranum'),
         Species=str_replace(Species,'Harpulia bogoriensis','Harpulia sp'),
         Species=str_replace(Species,'Heliacia sp','Helicia sp'),
         Species=str_replace(Species,'Herieteria sumatrana','Heritiera sumatrana'),
         Species=str_replace(Species,'Hoescorthechinia kingii','Neoscortechinia kingii'),
         Species=str_replace(Species,'Homolanthus populneus','Homalanthus populneus'),
         Species=str_replace(Species,'Hopea dryobalaniodes','Hopea dryobalanoides'),
         Species=str_replace(Species,'Hopea dyobalanoides','Hopea dryobalanoides'),
         Species=str_replace(Species,'Hopea mengerawan','Hopea mengarawan'),
         Species=str_replace(Species,'Horsefieldia sp','Horsfieldia sp'),
         Species=str_replace(Species,'Horsfieldia grandiflora','Horsfieldia sp'),
         Species=str_replace(Species,'Horsfieldia palultris','Horsfieldia sp'),
         Species=str_replace(Species,'Hydnocarpus kuenstleri','Hydnocarpus kunstleri'),
         Species=str_replace(Species,'Inocarpus fagiferus','Inocarpus fagifer'),
         Species=str_replace(Species,'Jackia ornata','Jackiopsis ornata'),
         Species=str_replace(Species,'Jackiopsis sumatrana','Jackiopsis sp'),
         Species=str_replace(Species,'Knema furtaraceae','Knema furfuracea'),
         Species=str_replace(Species,'Knema latericea','Knema latericia'),
         Species=str_replace(Species,'Knema laterifolia','Knema sp'),
         Species=str_replace(Species,'Laportea stimulan','Laportea stimulans'),
         Species=str_replace(Species,'Licania splenden$','Licania splendens'),
         Species=str_replace(Species,'Lithocarpus benitii','Lithocarpus bennettii'),
         Species=str_replace(Species,'Lithocarpus cantleyana','Lithocarpus cantleyanus'),
         Species=str_replace(Species,'Lithocarpus encleisacarpus','Lithocarpus encleisacarpus'),
         Species=str_replace(Species,'Lithocarpus meijerisp','Lithocarpus meijeri'),
         Species=str_replace(Species,'Lithocarpus seriobalanus','Lithocarpus sericobalanos'),
         Species=str_replace(Species,'Litsea accendens','Litsea accedens'),
         Species=str_replace(Species,'Litsea affinis','Litsea sp'),
         Species=str_replace(Species,'Litsea michilifolia','Litsea sp'),
         Species=str_replace(Species,'Litsea timoryana','Litsea timoriana'),
         Species=str_replace(Species,'Litsrea cubeba','Litsea cubeba'),
         Species=str_replace(Species,'Lophopetelum javanicum','Lophopetalum javanum'),
         Species=str_replace(Species,'Macaranga aff.allorobinsii','Macaranga aff.allorobinsonii'),
         Species=str_replace(Species,'Macaranga allorobinsii','Macaranga allorobinsonii'),
         Species=str_replace(Species,'Macaranga giganta','Macaranga gigantea'),
         Species=str_replace(Species,'Macaranga recorvata','Macaranga recurvata'),
         Species=str_replace(Species,'Macaranga rhinizoides','Macaranga rhizinoides'),
         Species=str_replace(Species,'Macarange','Macaranga'),
         Species=str_replace(Species,'Madhuca lanceifolia','Madhuca lancifolia'),
         Species=str_replace(Species,'Madhuca mangifera','Madhuca sp'),
         Species=str_replace(Species,'Magnolia illifera','Magnolia liliifera'),
         Species=str_replace(Species,'Mallotus echinanthus','Mallotus echinatus'),
         Species=str_replace(Species,'Mallotus lowii','Mallotus sp'),
         Species=str_replace(Species,'Mallotus penagensis','Mallotus penangensis'),
         Species=str_replace(Species,'Mallotus philippinensis','Mallotus philippensis'),
         Species=str_replace(Species,'Mallotus reginosus','Mallotus resinosus'),
         Species=str_replace(Species,'Mallotus rhinoides','Mallotus sp'),
         Species=str_replace(Species,'Malothus philipinensis','Mallotus philippensis'),
         Species=str_replace(Species,'Mastixia tricholoma','Mastixia trichotoma'),
         Species=str_replace(Species,'Mastixiodendron paxicladus','Mastixiodendron pachyclados'),
         Species=str_replace(Species,'Melanochyla densifolia','Melanochyla densiflora'),
         Species=str_replace(Species,'Melanochyla fulvinersis','Melanochyla fulvinervis'),
         Species=str_replace(Species,'Melastoma malabatrichum','Melastoma malabathricum'),
         Species=str_replace(Species,'Memecylon lauritium','Memecylon laurinum'),
         Species=str_replace(Species,'Memocylon','Memecylon'),
         Species=str_replace(Species,'Mesua borneensis','Kayea borneensis'),
         Species=str_replace(Species,'Mesua caroidea','Mesua sp'),
         Species=str_replace(Species,'Mesua conoidea','Mesua sp'),
         Species=str_replace(Species,'Mesua lepiduta','Mesua lepidota'),
         Species=str_replace(Species,'Microdesmis caseariaefolia','Microdesmis caseariifolia'),
         Species=str_replace(Species,'Mimosopsi elengi','Mimosopsis sp'),
         Species=str_replace(Species,'Mischocarpus pentallatus','Mischocarpus pentapetalus'),
         Species=str_replace(Species,'Miscocarpus pentalatus','Mischocarpus pentapetalus'),
         Species=str_replace(Species,'Miscocharpus pentapetalus','Mischocarpus pentapetalus'),
         Species=str_replace(Species,'Monocarpia eneura','Monocarpia euneura'),
         Species=str_replace(Species,'Myristica gaulterifolia','Myristica guatteriifolia'),
         Species=str_replace(Species,'Myristica guatteriaefolia','Myristica guatteriifolia'),
         Species=str_replace(Species,'Myristica lanceifolia','Myristica lancifolia'),
         Species=str_replace(Species,'Myristica latericia','Knema latericia'),
         Species=str_replace(Species,'Myristica laterifolia','Knema latifolia'),
         Species=str_replace(Species,'Myristica latifolia','Knema latifolia'),
         Species=str_replace(Species,'Neanotis hirsutis','Neanotis hirsuta'),
         Species=str_replace(Species,'Neotrewia kingii','Neotrewia sp'),
         Species=str_replace(Species,'Nezzetia havilandii','Mezzetia havilandii'),
         Species=str_replace(Species,'Northaphoebe','Nothaphoebe'),
         Species=str_replace(Species,'Notaphoebe','Nothaphoebe'),
         Species=str_replace(Species,'Nothaphoebe albipes','Nothaphoebe sp'),
         Species=str_replace(Species,'Nothaphoebe umbellifrora','Nothaphoebe umbelliflora'),
         Species=str_replace(Species,'Ochanaostachys','Ochanostachys'),
         Species=str_replace(Species,'Octomelis','Octomeles'),
         Species=str_replace(Species,'Olinia didyma','Olinia sp'),
         Species=str_replace(Species,'Oncopsperma','Oncosperma'),
         Species=str_replace(Species,'Palaguium callophyllum','Palaquium calophyllum'),
         Species=str_replace(Species,'Palaguium quercifolium','Palaquium quercifolium'),
         Species=str_replace(Species,'Palaquium amboinensis','Palaquium amboinense'),
         Species=str_replace(Species,'Palaquium cf.eryscalyx','Palaquium cf.eriocalyx'),
         Species=str_replace(Species,'Palaquium cochlearium','Palaquium cochleariifolium'),
         Species=str_replace(Species,'Palaquium qercifolium','Palaquium quercifolium'),
         Species=str_replace(Species,'Palaquium quorcifolium','Palaquium quercifolium'),
         Species=str_replace(Species,'Paraseriathes falcataria','Paraserianthes falcataria'),
         Species=str_replace(Species,'Parashorea paniifolia','Parashorea parvifolia'),
         Species=str_replace(Species,'Paratocarpus venenosa','Parartocarpus venenosus'),
         Species=str_replace(Species,'Parinarium corymbosum','Parinari corymbosa'),
         Species=str_replace(Species,'Parkia sericea','Parkia sp'),
         Species=str_replace(Species,'Payaena sericeum','Payena sericea'),
         Species=str_replace(Species,'Pellacalyx aff.pustulatus','Pellacalyx aff.pustulata'),
         Species=str_replace(Species,'Pellacalyx cf.lobii','Pellacalyx cf.lobbii'),
         Species=str_replace(Species,'Pellacalyx lobii','Pellacalyx lobbii'),
         Species=str_replace(Species,'Pentace odenophora','Pentace adenophora'),
         Species=str_replace(Species,'Pheobe laevis','Phoebe laevis'),
         Species=str_replace(Species,'Phoebe lucidula','Phoebe lucida'),
         Species=str_replace(Species,'Pimeleodendron','Pimelodendron'),
         Species=str_replace(Species,'Pimeliodendron','Pimelodendron'),
         Species=str_replace(Species,'Platymitra multiflora','Platymitra sp'),
         Species=str_replace(Species,'Polyalthia latericia','Polyalthia lateritia'),
         Species=str_replace(Species,'Polyalthia lateritica','Polyalthia lateritia'),
         Species=str_replace(Species,'Polyalthia laterifolia','Polyalthia lateriflora'),
         Species=str_replace(Species,'Polyosma celebica','Polyosma sp'),
         Species=str_replace(Species,'Polyosma illicofolia','Polyosma ilicifolia'),
         Species=str_replace(Species,'Pometia coriaceae','Pometia coriacea'),
         Species=str_replace(Species,'Pometia pinanta','Pometia pinnata'),
         Species=str_replace(Species,'Potemia pinata','Pometia pinnata'),
         Species=str_replace(Species,'Prainia','Prainea'),
         Species=str_replace(Species,'Prunus gricea','Prunus grisea'),
         Species=str_replace(Species,'Pseudouvaria','Pseuduvaria'),
         Species=str_replace(Species,'Pseudovaria','Pseuduvaria'),
         Species=str_replace(Species,'Pterigota horsfieldia','Pterygota horsfieldii'),
         Species=str_replace(Species,'Ptychophyxis','Ptychopyxis'),
         Species=str_replace(Species,'Pygeum lompogum','Pygeum lampongum'),
         Species=str_replace(Species,'Quercus gamelliflora','Quercus sp'),
         Species=str_replace(Species,'Quercus gmeliflora','Quercus sp'),
         Species=str_replace(Species,'Rhodamnia cinerva','Rhodamnia cinerea'),
         Species=str_replace(Species,'Rhotmannia','Rothmannia'),
         Species=str_replace(Species,'Sandoricum kotjape','Sandoricum koetjape'),
         Species=str_replace(Species,'Santira','Santiria'),
         Species=str_replace(Species,'Saurauria','Saurauia'),
         Species=str_replace(Species,'Saurauwia','Saurauia'),
         Species=str_replace(Species,'Scaphium borneensis','Scaphium borneense'),
         Species=str_replace(Species,'Scapium macropudum','Scaphium macropodum'),
         Species=str_replace(Species,'Scolopia pinnata','Scolopia sp'),
         Species=str_replace(Species,'Scorodacarpus','Scorodocarpus'),
         Species=str_replace(Species,'Semecarpus burbuyanus','Semecarpus bunburyanus'),
         Species=str_replace(Species,'Shore pauciflora','Shorea pauciflora'),
         Species=str_replace(Species,'Shorea acuminitissima','Shorea acuminatissima'),
         Species=str_replace(Species,'Shorea artinervosa','Shorea atrinervosa'),
         Species=str_replace(Species,'Shorea baccariana','Shorea beccariana'),
         Species=str_replace(Species,'Shorea beccariania','Shorea beccariana'),
         Species=str_replace(Species,'Shorea excelliptica','Shorea exelliptica'),
         Species=str_replace(Species,'Shorea new','Shorea sp'),
         Species=str_replace(Species,'pau$','pauciflora'),
         Species=str_replace(Species,'Shorea scabrrima','Shorea scaberrima'),
         Species=str_replace(Species,'Shorea sepatulata','Shorea sp'),
         Species=str_replace(Species,'Shorea venlosa','Shorea venulosa'),
         Species=str_replace(Species,'Shorea venulos$','Shorea venulosa'),
         Species=str_replace(Species,'Sindoro','Sindora'),
         Species=str_replace(Species,'Spatheostemon','Spathiostemon'),
         Species=str_replace(Species,'Spondias Chyterea','Spondias cytherea'),
         Species=str_replace(Species,'Stemonurus javanica','Stemonurus javanicus'),
         Species=str_replace(Species,'Steumonorus','Stemonurus'),
         Species=str_replace(Species,'Symplocos coccinensis','Symplocos cochinchinensis'),
         Species=str_replace(Species,'Symplocos sessifolium','Symplocos sessilifolia'),
         Species=str_replace(Species,'Syxygium','Syzygium'),
         Species=str_replace(Species,'Syzygium cf.ocneocarpum','Syzygium cf.ochneocarpum'),
         Species=str_replace(Species,'Syzygium cuprea','Syzygium sp'),
         Species=str_replace(Species,'Syzygium filiformis','Syzygium filiforme'),
         Species=str_replace(Species,'Syzygium flosculiflorum','Syzygium flosculiferum'),
         Species=str_replace(Species,'Syzygium gracilis','Syzygium gracile'),
         Species=str_replace(Species,'Syzygium incamatum','Syzygium incarnatum'),
         Species=str_replace(Species,'Syzygium oligomyrmum','Syzygium oligomyrum'),
         Species=str_replace(Species,'Syzygium opaca','Syzygium sp'),
         Species=str_replace(Species,'Syzygium perspicuinerivum','Syzygium perspicuinervium'),
         Species=str_replace(Species,'Syzygium samaranganse','Syzygium samarangense'),
         Species=str_replace(Species,'Teijsmanniodendron sarawakanium','Teijsmanniodendron sarawakanum'),
         Species=str_replace(Species,'Tetradium celebicum','Tetradium sp'),
         Species=str_replace(Species,'Trema orientalis','Trema orientale'),
         Species=str_replace(Species,'Tristania sepatulata','Tristania sp'),
         Species=str_replace(Species,'Turpinia spaerocarpa','Turpinia sphaerocarpa'),
         Species=str_replace(Species,'Urophyllum borneensis','Urophyllum borneense'),
         Species=str_replace(Species,'Vatica macrantha','Vatica sp'),
         Species=str_replace(Species,'Vatica ombonata','Vatica umbonata'),
         Species=str_replace(Species,'Vatica ombunata','Vatica umbonata'),
         Species=str_replace(Species,'Vavae amicorum','Vavaea amicorum'),
         Species=str_replace(Species,'Villebrunea rubescen$','Villebrunea rubescens'),
         Species=str_replace(Species,'Vitex quintata','Vitex quinata'),
         Species=str_replace(Species,'Wendelandia','Wendlandia'),
         Species=str_replace(Species,'Willughbea coriacea','Willughbeia coriacea'),
         Species=str_replace(Species,'Willughbea coriocea','Willughbeia coriacea'),
         Species=str_replace(Species,'Xanthophyllum eurhycum','Xanthophyllum eurhynchum'),
         Species=str_replace(Species,'Xanthophyllum eurhyncum','Xanthophyllum eurhynchum'),
         Species=str_replace(Species,'Xanthophyllum scootechiinii','Xanthophyllum scortechinii'),
         Species=str_replace(Species,'Xanthophylum schortechinii','Xanthophyllum scortechinii'),
         Species=str_replace(Species,'Xathophyllum','Xanthophyllum'),
         Species=str_replace(Species,'Xylopia fetruginea','Xylopia ferruginea'),
         Species=str_replace(Species,'Zantoxylum myriachantum','Zanthoxylum myriacanthum'),
         Species=str_replace(Species,'Ziziphus oneplia','Ziziphus oenopolia'),
         Species=str_replace(Species,'Zyzypus','Ziziphus'),
         Species=str_replace(Species,'Eugenia sp','Syzygium sp'),
         Species=str_replace(Species,'Adenanthera novoguinensis','Adenanthera novoguineensis'),
         Species=str_replace(Species,'Aglaia sylvestris','Aglaia silvestris'),
         Species=str_remove(Species,'cf.'),
         Species=str_replace(Species,'Dacryodes $','Dacryodes sp'),
         Species=str_replace(Species,'Alangium ridleyii','Alangium ridleyi'),
         Species=str_replace(Species,'Albizzia chinensis','Albizia chinensis'),
         Species=str_replace(Species,'Allophyllus cobbe','Allophylus cobbe'),
         Species=str_replace(Species,'Anisophylla','Anisophyllea'),
         Species=str_replace(Species,'Ardisia myristicaefolia','Ardisia myristicifolia'),
         Species=str_replace(Species,'Artocarpus elastica','Artocarpus elasticus'),
         Species=str_replace(Species,'Artocarpus gomeziana','Artocarpus gomezianus'),
         Species=str_replace(Species,'Artocarpus nitida','Artocarpus nitidus'),
         Species=str_replace(Species,'Artocarpus odoratisima','Artocarpus odoratissimus'),
         Species=str_replace(Species,'Artocarpus odoratissima','Artocarpus odoratissimus'),
         Species=str_replace(Species,'Artocarpus teysmanii','Artocarpus teysmannii'),
         Species=str_replace(Species,'Arytera littoralis','Arytera litoralis'),
         Species=str_replace(Species,'Bacccaurea','Baccaurea'),
         Species=str_replace(Species,'Baringtonia','Barringtonia'),
         Species=str_replace(Species,'Callophyllum','Calophyllum'),
         Species=str_replace(Species,'Calophyllum soulatri','Calophyllum soulattri'),
         Species=str_replace(Species,'Calophyllum soullatri','Calophyllum soulattri'),
         Species=str_replace(Species,'Calophyllum teysmanni','Calophyllum teysmannii'),
         Species=str_replace(Species,'Campnosperma auriculata','Campnosperma auriculatum'),
         Species=str_replace(Species,'Castanopsis tungurut','Castanopsis tungurrut'),
         Species=str_replace(Species,'Cleistocalyx operculata','Cleistocalyx operculatus'),
         Species=str_replace(Species,'Clerodendron','Clerodendrum'),
         Species=str_replace(Species,'Corynocarpus australasica','Corynocarpus australasicus'),
         Species=str_replace(Species,'Cratoxylon','Cratoxylum'),
         Species=str_replace(Species,'Ctenolophon parvifolia','Ctenolophon parvifolius'),
         Species=str_replace(Species,'Deehasia','Dehaasia'),
         Species=str_replace(Species,'Dehassia','Dehaasia'),
         Species=str_replace(Species,'Diospyros dayakensis','Diospyros dajakensis'),
         Species=str_replace(Species,'Diospyros foxworthyii','Diospyros foxworthyi'),
         Species=str_replace(Species,'Diospyros minahasae','Diospyros minahassae'),
         Species=str_replace(Species,'Diospyros oblongus','Diospyros oblonga'),
         Species=str_replace(Species,'Diospyros pseudo-malabarica','Diospyros pseudomalabarica'),
         Species=str_replace(Species,'Dipterocarpus caudiferus','Dipterocarpus caudifer'),
         Species=str_replace(Species,'Dipterocarpus costulata','Dipterocarpus costulatus'),
         Species=str_replace(Species,'Dipterocarpus costullatus','Dipterocarpus costulatus'),
         Species=str_replace(Species,'Dipterocarpus kerii','Dipterocarpus kerrii'),
         Species=str_replace(Species,'Dipterocarpus pachyphylla','Dipterocarpus pachyphyllus'),
         Species=str_replace(Species,'Dripetes','Drypetes'),
         Species=str_replace(Species,'Durio malacensis','Durio malaccensis'),
         Species=str_replace(Species,'Dysoxyllum','Dysoxylum'),
         Species=str_replace(Species,'Dysoxylon','Dysoxylum'),
         Species=str_replace(Species,'Dysoxylum mollisimum','Dysoxylum mollissimum'),
         Species=str_replace(Species,'Elaeocarpus parvifolius','Elaeocarpus parviflorus'),
         Species=str_replace(Species,'Elmerillia','Elmerrillia'),
         Species=str_replace(Species,'Erythroxylon','Erythroxylum'),
         Species=str_replace(Species,'Eugenia densiflora','Syzygium densiflorum'),
         Species=str_replace(Species,'Euodia eleryana','Euodia elleryana'),
         Species=str_replace(Species,'Eusyderoxylon zwagerii','Eusideroxylon zwageri'),
         Species=str_replace(Species,'Ficus erithrosperma','Ficus erythrosperma'),
         Species=str_replace(Species,'Ficus xanthophylla','Ficus sp'),
         Species=str_replace(Species,'Ganua mottleyana','Ganua motleyana'),
         Species=str_replace(Species,'Garcinia andersonii','Garcinia sp'),
         Species=str_replace(Species,'Garcinia havilandi$','Garcinia havilandii'),
         Species=str_replace(Species,'Garcinia rheedii','Garcinia rheedei'),
         Species=str_replace(Species,'Glochidion philipicum','Glochidion philippicum'),
         Species=str_replace(Species,'Glochidion philippense','Glochidion philippicum'),
         Species=str_replace(Species,'Glutta','Gluta'),
         Species=str_replace(Species,'Goniothalamus macrophylla','Goniothalamus macrophyllus'),
         Species=str_replace(Species,'Gonocaryum littorale','Gonocaryum litorale'),
         Species=str_replace(Species,'Gonystylus acuminata','Gonystylus acuminatus'),
         Species=str_replace(Species,'Gonystylus afinis','Gonystylus affinis'),
         Species=str_replace(Species,'Gonystylus confusa','Gonystylus confusus'),
         Species=str_replace(Species,'Gordonia singaporeana','Gordonia sp'),
         Species=str_replace(Species,'Gynotroches axilaris','Gynotroches axillaris'),
         Species=str_replace(Species,'Haplolobus celebica','Haplolobus celebicus'),
         Species=str_replace(Species,'Haplolobus floribunda','Haplolobus floribundus'),
         Species=str_replace(Species,'Harpulia','Harpullia'),
         Species=str_replace(Species,'Heritiera symplicifolia','Heritiera simplicifolia'),
         Species=str_replace(Species,'Hopea bulatifolia','Hopea bullatifolia'),
         Species=str_replace(Species,'Hydnocarpus anomala','Hydnocarpus anomalus'),
         Species=str_replace(Species,'Hydnocarpus beccariana','Hydnocarpus beccarianus'),
         Species=str_replace(Species,'Hydnocarpus polypetala','Hydnocarpus polypetalus'),
         Species=str_replace(Species,'Hymenodyction','Hymenodictyon'),
         Species=str_replace(Species,'Knema stenophyla','Knema stenophylla'),
         Species=str_replace(Species,'Koompassia malacensis','Koompassia malaccensis'),
         Species=str_replace(Species,'Lepisanthes erectus','Lepisanthes erecta'),
         Species=str_replace(Species,'Lithocarpus bennetii','Lithocarpus bennettii'),
         Species=str_replace(Species,'Lithocarpus monticolus','Lithocarpus monticola'),
         Species=str_replace(Species,'Lithocarpus pseudo-kunstleri','Lithocarpus pseudokunstleri'),
         Species=str_replace(Species,'Lithocarpus pseudomolucca','Lithocarpus pseudomoluccus'),
         Species=str_replace(Species,'Lithocarpus pussilus','Lithocarpus pusillus'),
         Species=str_replace(Species,'Lophopetalum javanum','Lophopetalum javanicum'),
         Species=str_replace(Species,'Lophopetalum torricelense','Lophopetalum torricellense'),
         Species=str_replace(Species,'Macaranga caladifolia','Macaranga caladiifolia'),
         Species=str_replace(Species,'Macaranga repando-dentata','Macaranga repandodentata'),
         Species=str_replace(Species,'Macaranga tanaria','Macaranga tanarius'),
         Species=str_replace(Species,'Macropanax dispermum','Macropanax dispermus'),
         Species=str_replace(Species,'Madhuca mallacensis','Madhuca malaccensis'),
         Species=str_replace(Species,'Magnolia candolii$','Magnolia candollei'),
         Species=str_replace(Species,'Magnolia candolli$','Magnolia candollei'),
         Species=str_replace(Species,'Magnolia candollii$','Magnolia candollei'),
         Species=str_replace(Species,'Memecylon laevigata','Memecylon laevigatum'),
         Species=str_replace(Species,'Memecylon oleaefolium','Memecylon oleifolium'),
         Species=str_replace(Species,'Mezettia','Mezzettia'),
         Species=str_replace(Species,'Mezzetia','Mezzettia'),
         Species=str_replace(Species,'Mezzettia havilandi$','Mezzettia havilandii'),
         Species=str_replace(Species,'Micromellum','Micromelum'),
         Species=str_replace(Species,'Micromelon','Micromelum'),
         Species=str_replace(Species,'Milletia','Millettia'),
         Species=str_replace(Species,'Mmyristica','Myristica'),
         Species=str_replace(Species,'Musaendopsis','Mussaendopsis'),
         Species=str_replace(Species,'Myristica eliptica','Myristica elliptica'),
         Species=str_replace(Species,'Myristica kjelbergii','Myristica kjellbergii'),
         Species=str_replace(Species,'Neouvaria acuminatissima','Neo-uvaria acuminatissima'),
         Species=str_replace(Species,'Nephelium maingayii','Nephelium maingayi'),
         Species=str_replace(Species,'Palaquium calophhyllum','Palaquium calophyllum'),
         Species=str_replace(Species,'Pandanus polycephallus','Pandanus polycephalus'),
         Species=str_replace(Species,'Parartocarpus venenosa','Parartocarpus venenosus'),
         Species=str_replace(Species,'Payena lerii','Payena leerii'),
         Species=str_replace(Species,'Pellacalyx axilaris','Pellacalyx axillaris'),
         Species=str_replace(Species,'Planchonela','Planchonella'),
         Species=str_replace(Species,'Pometia pinata','Pometia pinnata'),
         Species=str_replace(Species,'Pisonia umbelifera','Pisonia umbellifera'),
         Species=str_replace(Species,'Prunus polystachia','Prunus polystachya'),
         Species=str_replace(Species,'Pterocymbium tinctoria','Pterocymbium tinctorium'),
         Species=str_replace(Species,'Pyrrenaria','Pyrenaria'),
         Species=str_replace(Species,'Rhyticarium','Ryticaryum'),
         Species=str_replace(Species,'Rothmannia schoemanii','Rothmannia schoemannii'),
         Species=str_replace(Species,'Saprosma arboreum','Saprosma arborea'),
         Species=str_replace(Species,'Saracca','Saraca'),
         Species=str_replace(Species,'Scutinanthe brunea','Scutinanthe brunnea'),
         Species=str_replace(Species,'Semecarpus glauca','Semecarpus glaucus'),
         Species=str_replace(Species,'Shorea agamii','Shorea agami'),
         Species=str_replace(Species,'Shorea mecistopterix','Shorea mecistopteryx'),
         Species=str_replace(Species,'Shorea pubistylla','Shorea pubistyla'),
         Species=str_replace(Species,'Stemonurus javanicus','Stemonurus sp'),
         Species=str_replace(Species,'Stenolophon','Ctenolophon'),
         Species=str_replace(Species,'Streblus elongata','Streblus elongatus'),
         Species=str_replace(Species,'Styrax paralleloneurum','Styrax paralleloneurus'),
         Species=str_replace(Species,'Symplocos barringtonifolia','Symplocos barringtoniifolia'),
         Species=str_replace(Species,'Symplocos baringtonifolia','Symplocos barringtoniifolia'),
         Species=str_replace(Species,'Syzigium','Syzygium'),
         Species=str_replace(Species,'Syzygium acuminatissima','Syzygium acuminatissimum'),
         Species=str_replace(Species,'Syzygium boerlagii','Syzygium boerlagei'),
         Species=str_replace(Species,'Syzygium chlorantha','Syzygium chloranthum'),
         Species=str_replace(Species,'Syzygium densiflora','Syzygium densiflorum'),
         Species=str_replace(Species,'Syzygium ecostulata','Syzygium ecostulatum'),
         Species=str_replace(Species,'Syzygium flosculifera','Syzygium flosculiferum'),
         Species=str_replace(Species,'Syzygium gracile','Syzygium gracilipes'),
         Species=str_replace(Species,'Syzygium lineata','Syzygium lineatum'),
         Species=str_replace(Species,'Syzygium oblata','Syzygium oblatum'),
         Species=str_replace(Species,'Syzygium ochneocarpa','Syzygium ochneocarpum'),
         Species=str_replace(Species,'Syzygium picnanthum','Syzygium pycnanthum'),
         Species=str_replace(Species,'Syzygium ridleyii','Syzygium ridleyi'),
         Species=str_replace(Species,'Talauma candollii','Talauma candollei'),
         Species=str_replace(Species,'Tarrena','Tarenna'),
         Species=str_replace(Species,'Teijsmanniodendron0','Teijsmanniodendron'),
         Species=str_replace(Species,'Teijsmaniodendron','Teijsmanniodendron'),
         Species=str_replace(Species,'Tetractomia holtumii','Tetractomia holttumii'),
         Species=str_replace(Species,'Timonius teysmanii','Timonius teysmannii'),
         Species=str_replace(Species,'Trioma','Triomma'),
         Species=str_replace(Species,'Tristania bakhuizeni$','Tristania bakhuizenii'),
         Species=str_replace(Species,'Vatica sect.vatica','Vatica sp'),
         Species=str_replace(Species,'Vatica sumatrana','Vatica sp'),
         Species=str_replace(Species,'Vilebrunea','Villebrunea'),
         Species=str_replace(Species,'Vitex cofasus','Vitex cofassus'),
         Species=str_replace(Species,'Wetria macrophylla','Wetria sp'),
         Species=str_replace(Species,'Xanthophyllum afine','Xanthophyllum affine'),
         Species=str_replace(Species,'Xanthophyllum lanceolatum','Xanthophyllum lanceatum'),
         Species=str_replace(Species,'Xanthostemon confertiflorum','Xanthostemon confertiflorus'),
         Species=str_replace(Species,'Zyzyphus','Ziziphus'),
         Species=str_replace(Species,'Zizyphus','Ziziphus'),
         Species=str_replace(Species,'Ziziphus angustifolius','Ziziphus angustifolia'),
         Species=str_replace(Species,'Achronichia','Acronychia'),
         Species=str_replace(Species,'Achronycha','Acronychia'),
         Species=str_replace(Species,'Achtinodaphne','Actinodaphne'),
         Species=str_replace(Species,'Actinodapne','Actinodaphne'),
         Species=str_replace(Species,'Actinoidaphne','Actinodaphne'),
         Species=str_replace(Species,'Aglaiaa','Aglaia'),
         Species=str_replace(Species,'Alpithonia','Alphitonia'),
         Species=str_replace(Species,'Alpithotia','Alphitonia'),
         Species=str_replace(Species,'Anisopthera','Anisoptera'),
         Species=str_replace(Species,'Anisothera','Anisoptera'),
         Species=str_replace(Species,'Archidendon','Archidendron'),
         Species=str_replace(Species,'Archinodendron','Archidendron'),
         Species=str_replace(Species,'Archiodendron','Archidendron'),
         Species=str_replace(Species,'Arthocarpus','Artocarpus'),
         Species=str_replace(Species,'Astroenia','Astronia'),
         Species=str_replace(Species,'Beicmeldia','Beilschmiedia'),
         Species=str_replace(Species,'Beicsmeldia','Beilschmiedia'),
         Species=str_replace(Species,'Belischmiedia','Beilschmiedia'),
         Species=str_replace(Species,'Beicmeldia nitida','Beilschmiedia sp'),
         Species=str_replace(Species,'Camnosperma','Campnosperma'),
         Species=str_replace(Species,'Canarim','Canarium'),
         Species=str_replace_all(Species,'Caralia','Carallia'),
         Species=str_replace_all(Species,'caralia','Carallia'),
         Species=str_replace(Species,'Cinammomum culilawane','Cinnamomum cullilawan'),
         Species=str_replace(Species,'Cinamommum culillawane','Cinnamomum cullilawan'),
         Species=str_replace(Species,'Cinamomum culilawan','Cinnamomum cullilawan'),
         Species=str_replace(Species,'Cinnamommum culilawane','Cinnamomum cullilawan'),
         Species=str_replace(Species,'Cleistanhus','Cleistanthus'),
         Species=str_replace(Species,'Cleistantus','Cleistanthus'),
         Species=str_replace(Species,'Cleistantus myriianthus','Cleistanthus myrianthus'),
         Species=str_replace(Species,'Cratoxilon','Cratoxylum'),
         Species=str_replace(Species,'Crypsophyllum','Chrysophyllum'),
         Species=str_replace(Species,'Cryptocaria','Cryptocarya'),
         Species=str_replace(Species,'Crytocarya','Cryptocarya'),
         Species=str_replace(Species,'Crysophyllum','Chrysophyllum'),
         Species=str_replace(Species,'Cyathocaylx','Cyathocalyx'),
         Species=str_replace(Species,'Diopyros','Diospyros'),
         Species=str_replace(Species,'Disoxyllum','Dysoxylum'),
         Species=str_replace(Species,'Dracontomelom','Dracontomelon'),
         Species=str_replace(Species,'Dracontomelum','Dracontomelon'),
         Species=str_replace(Species,'Elmerilia','Magnolia'),
         Species=str_replace(Species,'Endniandra','Endiandra'),
         Species=str_replace(Species,'Fagrarea','Fagraea'),
         Species=str_replace(Species,'fagrarea','Fagraea'),
         Species=str_replace(Species,'Fitosforum','Pittosporum'),
         Species=str_replace(Species,'Flindercia','Flindersia'),
         Species=str_replace(Species,'Garcicinia picrorrhiza','Garcinia picrorrhiza'),
         Species=str_replace(Species,'garcicinia picrorrhiza','Garcinia picrorrhiza'),
         Species=str_replace(Species,'Gironiera','Gironniera'),
         Species=str_replace(Species,'Glaocydion','Glochidion'),
         Species=str_replace(Species,'Glaocylon','Claoxylon'),
         Species=str_replace(Species,'Gomphandara','Gomphandra'),
         Species=str_replace(Species,'Gonocarium','Gonocaryum'),
         Species=str_replace(Species,'Gonocarium','Gonocaryum'),
         Species=str_replace(Species,'Gopandra','Gomphandra'),
         Species=str_replace(Species,'Guio pleuropsis','Guioa pleuropteris'),
         Species=str_replace(Species,'Gymnacanthera','Gymnacranthera'),
         Species=str_replace(Species,'Homaliun','Homalium'),
         Species=str_replace(Species,'Horfieldia','Horsfieldia'),
         Species=str_replace(Species,'Horsfiedia','Horsfieldia'),
         Species=str_replace(Species,'Horsfieldlia','Horsfieldia'),
         Species=str_replace(Species,'Horsfildia','Horsfieldia'),
         Species=str_replace(Species,'Horsfildia','Horsfieldia'),
         Species=str_replace(Species,'Inocapus','Inocarpus'),
         Species=str_replace(Species,'Laplapceae','Laplacea'),
         Species=str_replace(Species,'Mstixiodendron','Mastixiodendron'),
         Species=str_replace(Species,'Myrisstica','Myristica'),
         Species=str_replace(Species,'Myristic$','Myristica'),
         Species=str_replace(Species,'Myristrica','Myristica'),
         Species=str_replace(Species,'Myrristica','Myristica'),
         Species=str_replace(Species,'Myristic agigantea','Myristica gigantea'),
         Species=str_replace(Species,'Osmoxilon','Osmoxylon'),
         Species=str_replace(Species,'Pimelodendon','Pimelodendron'),
         Species=str_replace(Species,'Pittosforum','Pittosporum'),
         Species=str_replace(Species,'Polyalthis','Polyalthia'),
         Species=str_replace(Species,'Pterigota','Pterygota'),
         Species=str_replace(Species,'Reindwartiodendron','Reinwardtiodendron'),
         Species=str_replace(Species,'Rhustaitensis sp','Rhus taitensis'),
         Species=str_replace(Species,'Siphodon','Siphonodon'),
         Species=str_replace(Species,'Sizygium','Syzygium'),
         Species=str_replace(Species,'sizygium','Syzygium'),
         Species=str_replace(Species,'Spaeteostemon javanensis','Spathiostemon javensis'),
         Species=str_replace(Species,'Spateostemon javanensis','Spathiostemon javensis'),
         Species=str_replace(Species,'spateostemon javanensis','Spathiostemon javensis'),
         Species=str_replace(Species,'Spathoitemon','Spathiostemon'),
         Species=str_replace(Species,'Spondia cytherea','Spondias cytherea'),
         Species=str_replace(Species,'Stemunurus','Stemonurus'),
         Species=str_replace(Species,'Sterblus','Streblus'),
         Species=str_replace(Species,'Sysygium','Syzygium'),
         Species=str_replace(Species,'sysygium','Syzygium'),
         Species=str_replace(Species,'Cleistocalyx sp','Syzygium sp'),
         Species=str_replace(Species,'Teijamanniodendron','Teijsmanniodendron'),
         Species=str_replace(Species,'Teijmanniodendron','Teijsmanniodendron'),
         Species=str_replace(Species,'Tejsmaniodendron','Teijsmanniodendron'),
         Species=str_replace(Species,'Tejsmaniodendron bogoriensis','Teijsmanniodendron bogoriense'),
         Species=str_replace(Species,'Termnalia','Terminalia'),
         Species=str_replace(Species,'Weinnmania','Weinmannia'),
         Species=str_replace(Species,'Xantophyllum','Xanthophyllum'),
         Species=str_replace(Species,'Omalanthus novoquineesis','Homalanthus novoguineensis'),
         Species=str_replace(Species,'Linociera macocarpa','Chionanthus macrocarpus'),
         Species=str_replace(Species,'Linociera ceramicus','Chionanthus sp'),
         Species=str_replace(Species,'Linociera macrophyllum','Chionanthus ramiflorus'),
         Species=str_replace(Species,'Podadenia sp','Ptychopyxis sp'),
         Species=str_replace(Species,'Anthocephalus chinensis','Neolamarckia cadamba')) %>%
  mutate(Species=str_to_sentence(Species)) 

wcvp=read.csv(file='wcvp_v6_sep_2021.txt',sep = '|')

names=left_join(plot_data_clean_2 %>% 
                  mutate(Species=str_remove(Species,'\\ sp$')) %>%
                  select(Species),wcvp,by=c('Species'='taxon_name')) %>%
  mutate(accepted_name=case_when(taxonomic_status=='Accepted'~Species,
                                 is.na(accepted_name)~Species,
                                 accepted_name==''~Species,
                                         T~accepted_name)) %>% 
  mutate(sp=case_when(!str_detect(accepted_name,' ')~'sp')) %>% 
  select(original_name=Species,accepted_name,sp) %>%
  unite('original_name',c(original_name,sp),remove = F,na.rm = T,sep=' ') %>%
  unite('accepted_name',c(accepted_name,sp),remove = F,na.rm = T,sep=' ') %>%
  select(original_name,accepted_name) %>% distinct() %>%
  group_by(original_name) %>%
  mutate('n_names'=n()) %>%
  ungroup() %>%
  mutate(accepted_name=case_when(n_names>1~original_name,
                                 T~accepted_name)) %>% distinct() %>%
  select(-n_names)

## remove sp then add sp to all species without space plus numbers for morphospecies
### recalculate abundance for previous synonymous names

clean_plot_comp=left_join(plot_data_clean_2,
                          names, by=c('Species'="original_name")) %>%
  rename(original_name=Species) %>% 
  group_by(accepted_name) %>% 
  mutate(num=row_number()) %>%
  ungroup() %>% 
  mutate('num'=case_when(!str_detect(accepted_name,'\\ sp$')~NA_real_,
                       T~as.numeric(num))) %>%
  unite('accepted_name',c(accepted_name,num),remove = F,na.rm = T,sep='. ') %>%
  select(-num) %>%
  group_by(ID,accepted_name) %>%
  mutate(abundance=sum(abundance)) %>%
  ungroup() %>%
  select(-original_name) %>%
  distinct()

rm(plot_data,plot_data_clean_1,plot_data_clean_2,wcvp)

write_csv(x=clean_plot_comp,'clean_Indoplot_abundance.csv')

####################################################################
####################################################################

library("iNEXT")

iNEXT_interpolated=estimateD(clean_plot_comp %>% select(accepted_name,ID,abundance) %>% 
                               pivot_wider(names_from = ID,values_from = abundance,values_fill = 0) %>%
                               column_to_rownames('accepted_name') %>% 
                               as.data.frame(), datatype = 'abundance',base = 'size',
                             level=60) %>%
  rename('q_value'='Order.q') %>%
  filter(q_value==0)

iNEXT_extrapolated=estimateD(clean_plot_comp %>% select(accepted_name,ID,abundance) %>% 
                               pivot_wider(names_from = ID,values_from = abundance,values_fill = 0) %>%
                               column_to_rownames('accepted_name') %>% 
                               as.data.frame(), datatype = 'abundance',base = 'size',
                             level=c(100,200,300)) %>%
  rename('q_value'='Order.q') %>%
  filter(q_value==0)

write_csv(iNEXT_extrapolated,file='iNEXT_extrapolated.csv')

## bind to env and soil
## then check transforms of env data

alpha_data=rbind(iNEXT_interpolated %>% select(site,'interpolated_alpha'=qD) %>% 
  left_join(clean_plot_meta,by=c('site'='ID')) %>% select(-c(Location,Area,Elevation)),
  read_csv('Cam_Hill numbers.csv') %>% 
  separate(data,into = c('num','site','m','method','order',
                         'SC','qD','qD.LCL','qD.UCL'), sep=' ') %>%
  .[-1,] %>% 
  filter(order==0) %>% select(site,'interpolated_alpha'=qD) %>% 
  left_join(clean_plot_meta,by=c('site'='Location')) %>% select(-c(site,Area,Elevation)) %>%
  select('site'=ID,interpolated_alpha,Island,Lat,Long)
) %>% mutate('interpolated_alpha'=as.numeric(interpolated_alpha))

rm(clean_plot_comp,clean_plot_meta,iNEXT_interpolated,names)

library(raster)
alt_data=getData('alt',country='IDN',mask=T) %>% as.data.frame(xy=T)  %>%
  rename(alt=IDN_msk_alt) %>% drop_na() %>% 
  distinct() %>% 
  mutate(x=round(x,2),y=round(y,2))

library('rgdal')
library('rbioclim')
bioclim=recursive.getData(times=c('pres','lgm'),res=5,var='bio')

library(gdalUtils)
library(sf)

####### New chunk - not evaluated??
####### dont need to run this just import code below

Asia_sf=data.frame(lon=c(90,158), lat=c(-11,20)) %>% st_as_sf(coords = c("lon", "lat"),dim='XY') %>%
  st_set_crs(4326)

igh='+proj=igh +lat_0=0 +lon_0=0 +datum=WGS84 +units=m +no_defs' # proj string for Homolosine projection
Asia_sf_Homolosine=st_transform(Asia_sf,igh)

bb=st_bbox(Asia_sf_Homolosine)

bb=c(bb$xmin,bb$ymax,bb$xmax,bb$ymin)

sg_url="/vsicurl/https://files.isric.org/soilgrids/latest/data/"

gdal_translate(paste0(sg_url,'nitrogen/nitrogen_15-30cm_mean.vrt'),
    "./Malesia_N_a.vrt",
    of="VRT",tr=c(1000,1000),
    projwin=bb,
    projwin_srs=igh,
    verbose=TRUE)
gdalwarp("./Malesia_N_a.vrt",
    "./Malesia_N_b.vrt", 
    s_src=igh, 
    t_srs="EPSG:4326", 
    of="VRT")
gdal_translate(paste0(sg_url,'cec/cec_15-30cm_mean.vrt'),
    "./Malesia_cec_a.vrt",
    of="VRT",tr=c(1000,1000),
    projwin=bb,
    projwin_srs=igh,
    verbose=TRUE)
gdalwarp("./Malesia_cec_a.vrt",
    "./Malesia_cec_b.vrt", 
    s_src=igh, 
    t_srs="EPSG:4326", 
    of="VRT")
gdal_translate(paste0(sg_url,'soc/soc_15-30cm_mean.vrt'),
    "./Malesia_soc_a.vrt",
    of="VRT",tr=c(1000,1000),
    projwin=bb,
    projwin_srs=igh,
    verbose=TRUE)
gdalwarp("./Malesia_soc_a.vrt",
    "./Malesia_soc_b.vrt", 
    s_src=igh, 
    t_srs="EPSG:4326", 
    of="VRT")

############################################################

N_Asia=readGDAL("./Malesia_N_b.vrt") %>% as.data.frame(xy=T)
CEC_Asia=readGDAL("./Malesia_cec_b.vrt") %>% as.data.frame(xy=T)
C_Asia=readGDAL("./Malesia_soc_b.vrt") %>% as.data.frame(xy=T)

alpha_env=alpha_data %>% mutate(x_round=round(Long,2),y_round=round(Lat,2)) %>%
  unite('coord',c(x_round,y_round)) %>%
  left_join(alt_data %>% mutate(x_round=round(x,2),y_round=round(y,2)) %>%
  unite('coord',c(x_round,y_round)) %>% dplyr::select(-c(x,y)),by='coord') %>% 
  group_by(site) %>% mutate(alt=mean(alt)) %>% ungroup() %>%
  distinct() %>% mutate(x_round=round(Long,1),y_round=round(Lat,1)) %>%
  unite('coord',c(x_round,y_round)) %>%
  left_join(bioclim[["pres"]] %>% as.data.frame(xy=T) %>%
  dplyr::select(x,y,bio1,bio7,bio12,bio15) %>%
  drop_na() %>% 
  filter(between(x,90,158) & between(y,-11,20)) %>%
  filter(y<6.5|x>117) %>% 
  dplyr::select(x,y,'MAT'=bio1,'T_range'=bio7,'MAP'=bio12,'P_seasonality'=bio15) %>%
  mutate(x_round=round(x,1),y_round=round(y,1)) %>%
  unite('coord',c(x_round,y_round)) %>% dplyr::select(-c(x,y)),
  by='coord') %>%
  group_by(site) %>%
  mutate(MAT=mean(MAT),T_range=mean(T_range),MAP=mean(MAP),P_seasonality=mean(P_seasonality)) %>%
  ungroup() %>%
  distinct() %>% mutate(x_round=round(Long,2),y_round=round(Lat,2)) %>%
  unite('coord',c(x_round,y_round)) %>%
  left_join(N_Asia %>% rename(soil_N=band1) %>% mutate(x_round=round(x,2),y_round=round(y,2)) %>%
  unite('coord',c(x_round,y_round)) %>% dplyr::select(-c(x,y)), by='coord') %>%
  group_by(site) %>%
  mutate(soil_N=mean(soil_N)) %>%
  ungroup() %>%
  distinct() %>% 
  left_join(C_Asia %>% rename(soil_C=band1) %>% mutate(x_round=round(x,2),y_round=round(y,2)) %>%
  unite('coord',c(x_round,y_round)) %>% dplyr::select(-c(x,y)), by='coord') %>%
  group_by(site) %>%
  mutate(soil_C=mean(soil_C)) %>%
  ungroup() %>%
  distinct() %>% 
  left_join(CEC_Asia %>% rename(soil_CEC=band1) %>% mutate(x_round=round(x,2),y_round=round(y,2)) %>%
  unite('coord',c(x_round,y_round)) %>% dplyr::select(-c(x,y)), by='coord') %>%
  group_by(site) %>%
  mutate(soil_CEC=mean(soil_CEC)) %>%
  ungroup() %>%
  distinct() 

rm(bioclim,alt_data,N_Asia,C_Asia,CEC_Asia)

alpha_env=alpha_env %>% dplyr::select(-coord) %>% 
  mutate(alt=log(alt),
         MAP=log(MAP),
         MAT=MAT^10,
         soil_C=log(soil_C),
         soil_N=log(soil_N)) 

write_csv(alpha_env,'alpha_env.csv')

unloadNamespace('gdalUtils')
unloadNamespace('raster')
unloadNamespace('rgdal')
unloadNamespace('sf')
unloadNamespace('rbioclim')
unloadNamespace('iNEXT')


```

```{r image-fig,message=F,error=F,echo=F}

setwd("/Users/liamtrethowan/Documents/Indo_alpha_diversity")
library(tidyverse)

library(magick)

katingan=image_read('~/Documents/Indo_alpha_diversity/35976721034_6c5baa0c80_k.jpg') %>% 
  image_scale('300')
salak=image_read('~/Documents/Indo_alpha_diversity/35991686011_723aa49766_k.jpg') %>% 
  image_scale('300')
mataiyang=image_rotate(image_read('~/Documents/Indo_alpha_diversity/IMG_0232.JPG'),90) %>%
  image_scale('300')
arfaks=image_read('~/Documents/Indo_alpha_diversity/IMG_0795.HEIC') %>% 
  image_convert(format = 'jpeg') %>%
  image_scale('300')
waigeo=image_read('~/Documents/Indo_alpha_diversity/Weigeo_2.JPG') %>% 
  image_scale('300')
halmahera=image_read('~/Documents/Indo_alpha_diversity/Halmahera.JPG') %>% 
  image_scale('300')

library(cowplot)

fig_pics=ggdraw() + 
  draw_plot(ggplot(tibble(x=c(1,2),y=c(1,2)),
                   aes(x=x,y=y)) +
                theme(plot.background = element_rect(fill='peachpuff2'),
                      panel.background = element_blank(),
                      axis.ticks = element_blank(),
                      axis.text = element_blank(),
                      axis.title = element_blank(),
                      panel.grid = element_blank()),
            x=.66,y=-0.01,width = .35,height = 1.1) +
  draw_plot(ggplot(tibble(x=c(1,2),y=c(1,2)),
                   aes(x=x,y=y)) +
                theme(plot.background = element_rect(fill='skyblue2'),
                      panel.background = element_blank(),
                      axis.ticks = element_blank(),
                      axis.text = element_blank(),
                      axis.title = element_blank(),
                      panel.grid = element_blank()),
            x=.32,y=-0.01,width = .35,height = 1.1) +
    draw_plot(ggplot(tibble(x=c(1,2),y=c(1,2)),
                   aes(x=x,y=y)) +
                theme(plot.background = element_rect(fill='tomato'),
                      panel.background = element_blank(),
                      axis.ticks = element_blank(),
                      axis.text = element_blank(),
                      axis.title = element_blank(),
                      panel.grid = element_blank()),
            x=-.05,y=-0.01,width=.38,height = 1.1) +
  draw_image(mataiyang,width = .33,height=.7,x=.33,y=0) +
  draw_image(halmahera,width = .33,height=.5,x=.33,y=.5) +
  draw_image(arfaks,width = .33,height=.5,x=.67,y=0) +
  draw_image(waigeo,width = .33,height=.5,x=.67,y=.5) +
  draw_image(katingan,width = .33,height=.5,x=0,y=.5) +
  draw_image(salak,width = .33,height=.5,x=0,y=0) +
  draw_plot_label(label = c('Java','Indonesian Borneo','Halmahera','Sumbawa',
                            'Waigeo','Indonesian New Guinea'),
             x=c(.04,-.02,.35,.38,.7,.65),
             y=c(.2,.65,.65,.2,.65,.2),
             colour = c('white','white','white','white','white','white'),size = 9)

#ggsave('fig_pics.jpeg',fig_pics,dpi=300,width = 118,height = 50,units = 'mm')
```

```{r analysis,message=F,error=F,echo=F,warning=F}

library(tidyverse)

alpha_env=read_csv('alpha_env.csv') %>% 
  mutate(Island_size=case_when(Island=='Simeuleu'~1754,
                               Island=='Sumatra'~473481,
                               Island=='Java'~128297,
                               Island=='Kalimantan'~743330,
                               Island=='Sumbawa'~15214,
                               Island=='Flores'~13540,
                               Island=='Sulawesi'~174600,
                               Island=='Buton'~4408,
                               Island=='Wawonii'~715,
                               Island=='Halmahera'~17780,
                               Island=='Seram'~17100,
                               Island=='Waigeo'~3155,
                               Island=='Yamdena'~3100,
                               Island=='New Guinea'~785753,
                               Island=='Weh'~156,
                               Island=='Bangka'~11413),
         Island=str_replace(Island,'New Guinea','West Papua')) %>%
  mutate('BGR'=case_when(Island=='Kalimantan'~'Sunda',
                                       Island=='Sumatra'~'Sunda',
                                       Island=='Weh'~'Sunda',
                                       Island=='Bangka'~'Sunda',
                                       Island=='Buton'~'Wallacea',
                                       Island=='Halmahera'~'Wallacea',
                                       Island=='Java'~'Sunda',
                                       Island=='West Papua'~'Sahul',
                                       Island=='Sulawesi'~'Wallacea',
                                       Island=='Sumbawa'~'Wallacea',
                                       Island=='Wawonii'~'Wallacea',
                                       Island=='Yamdena'~'Wallacea',
                                       Island=='Flores'~'Wallacea',
                                       Island=='Seram'~'Wallacea',
                                       Island=='Waigeo'~'Sahul'))

alpha_env=alpha_env %>% drop_na()

library(geosphere)

volcano_data=rbind(read.table(file = 'volcanoes-PNG.tsv', sep = '\t', header = TRUE) %>% 
  filter(Location=='New Guinea') %>%
  select('Volcano'=Volcano.Name,Location,'Long'=Longitude,'Lat'=Latitude),
  read_csv('Whelley_Volcano_data.csv') %>% 
  select('Volcano'=VOLCANO,'Long'=Longitude,'Lat'=Latitude) %>%
  add_column('Location'=NA) %>% 
  drop_na(Volcano)
) %>%
  add_column('name'='Volcano','number'=1:nrow(.)) %>%
  unite('Volcano',c(number,Volcano),sep = '_') %>%
  unite('Volcano',c(name,Volcano),sep = '_') %>%
  distinct(Long, Lat,.keep_all = T)

quake_data=rbind(
read.table(file = 'earthquakes-pacific.tsv', sep = '\t', header = TRUE) %>% 
  rename('Location'='Location.Name') %>% 
  filter(str_detect(Location, pattern="INDONESIA|PHILIPPINES|NEW GUINEA")) %>%
  select(Location,'Lat'=Latitude,'Long'=Longitude),

read.table(file = 'earthquakes-SE_Asia.tsv', sep = '\t', header = TRUE) %>% 
  rename('Location'='Location.Name')  %>%
  select(Location,'Lat'=Latitude,'Long'=Longitude) %>%
  filter(between(Long,95,140) & between(Lat,-10,10)) 
) %>% 
  add_column('Earthquake'='Earthquake','number'=1:nrow(.)) %>%
  unite('Earthquake',c(Earthquake,number)) %>% distinct(Long,Lat,.keep_all=T)

quake_volc_data=left_join(distm(volcano_data %>% column_to_rownames('Volcano') %>% select(-Location),
                   alpha_env %>% column_to_rownames('site') %>% select(Long,Lat),
                   distHaversine) %>%
  as_tibble() %>% 
  add_column('name_Volcano'=volcano_data$Volcano) %>% 
  pivot_longer(starts_with('V'),names_to = 'site',values_to = 'dist') %>% 
  group_by(site) %>% slice_min(dist) %>% 
  ungroup() %>%
  mutate('site'=as.numeric(str_remove(site,'V'))) %>% arrange(site) %>%
  mutate('site'=alpha_env$site) %>%
  mutate(dist_volcano=sqrt(dist/1000)) %>% 
    mutate(dist_volcano=1/dist_volcano) %>%
    select(-name_Volcano,-dist),
  distm(
  quake_data %>% select(Long,Lat),
  alpha_env %>% select(Long,Lat),
  distHaversine
) %>%
  as_tibble() %>% 
  add_column('Quake'=quake_data$Earthquake) %>% 
  pivot_longer(starts_with('V'),names_to = 'site',values_to = 'dist') %>% 
  group_by(site) %>% slice_min(dist) %>% 
  ungroup() %>%
  mutate('site'=as.numeric(str_remove(site,'V'))) %>% arrange(site) %>%
  mutate('site'=alpha_env$site) %>%
  mutate(dist_quake=log(dist/1000)) %>% 
    mutate(dist_quake=1/dist_quake) %>% select(-Quake,-dist) 
)

rm(quake_data,volcano_data)

envPCA=prcomp(alpha_env[6:13],center = T,scale. = T)
sumenvPCA=summary(envPCA)

alpha_env=alpha_env %>% left_join(quake_volc_data) %>% 
  mutate('biome'=case_when(Island=='Kalimantan'~'Wet',
                                       Island=='Sumatra'~'Wet',
                                       Island=='Weh'~'Wet',
                                       Island=='Bangka'~'Wet',
                                       Island=='Buton'~'Wet',
                                       Island=='Halmahera'~'Wet',
                                       Island=='Java'~'Wet',
                                       Island=='West Papua'~'Wet',
                                       Island=='Sulawesi'~'Wet',
                                       Island=='Sumbawa'~'Dry',
                                       Island=='Wawonii'~'Wet',
                                       Island=='Yamdena'~'Dry',
                                       Island=='Flores'~'Dry',
                                       Island=='Seram'~'Wet',
                                       Island=='Waigeo'~'Wet'),
                               'Elev_z'=c(scale(alt)),
                               'MAT_z'=c(scale(MAT)),
                               'T_range_z'=c(scale(T_range)),
                               'P_seasonality_z'=c(scale(P_seasonality)),
                               'MAP_z'=c(scale(MAP)),
                               'soil_N_z'=c(scale(soil_N)),
                               'soil_C_z'=c(scale(soil_C)),
                               'soil_CEC_z'=c(scale(soil_CEC)),
                            'Island_size_z'=c(scale(Island_size)),
         'dist_quake_z'=c(scale(dist_quake)),
                     'dist_volcano_z'=c(scale(dist_volcano))) %>%
  unite('group',remove = F,c(Lat,Long))

rm(quake_volc_data)

library(car)
library(lme4)

###### These contribute most to first three selected PC axes and this model has low VIF
###### use geol first PC axis/average dist of both quake and volc (geol instability) and see if VIF low?

alpha_lmm_selected=lmer(interpolated_alpha ~ Elev_z + P_seasonality_z + soil_C_z + Island_size_z + (1|BGR),
            data=alpha_env)

VIF_selected=vif(alpha_lmm_selected)

library(DHARMa)
simres_pseas=simulateResiduals(alpha_lmm_selected)
simres_grouped_pseas=recalculateResiduals(simres_pseas,group = alpha_env$group)
MoranI_pseas=testSpatialAutocorrelation(plot=F,simres_grouped_pseas,
                                        x=alpha_env %>% distinct(group,.keep_all = T) %>%. $Long,
                                        y=alpha_env %>% distinct(group,.keep_all = T) %>%. $Lat)

################################
### Quake data

alpha_lmm_geol=lmer(interpolated_alpha ~ Elev_z + soil_C_z + Island_size_z + dist_quake_z + (1|BGR),
            data=alpha_env) 

VIF_geol=vif(alpha_lmm_geol) 
#### ADD TO SUPP

simres_quake=simulateResiduals(alpha_lmm_geol)
simres_grouped_quake=recalculateResiduals(simres_quake,group = alpha_env$group)
MoranI_quake=testSpatialAutocorrelation(plot=F,simres_grouped_quake,
                                        x=alpha_env %>% distinct(group,.keep_all = T) %>%. $Long,
                                        y=alpha_env %>% distinct(group,.keep_all = T) %>%. $Lat)

###### HERE RE-RUN MODELS WITH THREE different diversity levels
###### maybe plot differences in effects sizes for different parameters .... nope

colnames_cam_data=read.table('Cam_Hill numbers_extrapolated.txt',sep=',') %>% 
  mutate(V1=as.character(replace_na(V1,0))) %>% 
  slice(1) %>%
  pivot_longer(everything()) %>% .$value

extrapolated_alpha=left_join(alpha_env, rbind(
  read_csv(file='iNEXT_extrapolated.csv') %>% 
  select('site'='Assemblage',m,'extrapolated_alpha'=qD),
  read.table('Cam_Hill numbers_extrapolated.txt',
                            sep=',',col.names = colnames_cam_data) %>% select(-1) %>% 
  slice_tail(n=-1) %>% 
  filter(Order.q=='0') %>% 
  select('site'='Assemblage',m,'extrapolated_alpha'=qD) 
  %>% left_join(read_csv('clean_plot_meta.csv') %>% 
  select('site'=Location,ID)) %>% select(-site) %>% rename('site'=ID)
)) %>% 
  mutate('extrapolated_alpha'=as.numeric(extrapolated_alpha)) %>%
  pivot_wider(names_from = m,names_prefix = 'extrapolated',values_from = extrapolated_alpha)

rm(colnames_cam_data)

alpha_lmm_selected100=lmer(extrapolated100 ~ Elev_z + P_seasonality_z + soil_C_z + Island_size_z + (1|BGR),
            data=extrapolated_alpha)
alpha_lmm_selected200=lmer(extrapolated200 ~ Elev_z + P_seasonality_z + soil_C_z + Island_size_z + (1|BGR),
            data=extrapolated_alpha)
alpha_lmm_selected300=lmer(extrapolated300 ~ Elev_z + P_seasonality_z + soil_C_z + Island_size_z + (1|BGR),
            data=extrapolated_alpha)
alpha_lmm_geol100=lmer(extrapolated100 ~ Elev_z + soil_C_z + Island_size_z + dist_quake_z + (1|BGR),
            data=extrapolated_alpha)
alpha_lmm_geol200=lmer(extrapolated200 ~ Elev_z + soil_C_z + Island_size_z + dist_quake_z + (1|BGR),
            data=extrapolated_alpha)
alpha_lmm_geol300=lmer(extrapolated300 ~ Elev_z + soil_C_z + Island_size_z + dist_quake_z + (1|BGR),
            data=extrapolated_alpha)

BGR_intercepts=rbind(
  coef(alpha_lmm_selected)$BGR %>% as.data.frame() %>% 
  rownames_to_column('BGR') %>%
  select(BGR,Intercept='(Intercept)') %>% 
  add_column('model'='selected'),
coef(alpha_lmm_geol)$BGR %>% as.data.frame() %>% 
  rownames_to_column('BGR') %>%
  select(BGR,Intercept='(Intercept)') %>% 
  add_column('model'='quake')) %>% 
  left_join(tibble('model'=c('selected','quake'),
                   'AIC'=c(AIC(alpha_lmm_selected),AIC(alpha_lmm_geol))))

plot_BGR_intercepts=BGR_intercepts %>%
  group_by(BGR) %>% mutate('minInt'=min(Intercept),'maxInt'=max(Intercept)) %>%
  ggplot(aes(x=BGR,fill=AIC)) +
  geom_linerange(aes(ymin=minInt,ymax=maxInt,x=BGR,colour=BGR),linewidth=3) +
  geom_point(aes(y=Intercept),shape=21,size=3) +
  theme(axis.text = element_text(size=8),
        axis.title.x = element_blank(),
        axis.line = element_line(),
        axis.title.y = element_text(size=8),
        panel.background = element_rect(colour='white'),
        legend.position = 'none',
        plot.background = element_blank()) +
  scale_colour_manual(values=c('peachpuff2','tomato','skyblue')) +
  scale_x_discrete(limits=c('Sunda','Wallacea','Sahul')) +
  scale_y_continuous(breaks = c(27,30)) +
  ylab('Bioregion random\neffect intercepts') +
  scale_fill_fermenter(palette='PuOr',breaks=c(1397))

predict_plot=tibble('Predicted_diversity'=fitted(alpha_lmm_selected),alpha_env) %>% 
  ggplot(aes(x=P_seasonality_z,y=Predicted_diversity,colour=BGR,size=Island_size_z)) +
  geom_point(alpha=.4) +
  scale_colour_manual(values=c('peachpuff2','tomato','skyblue2')) +
  theme(panel.background = element_blank(),
        axis.line = element_line(),
        legend.title = element_text(size=9),
        legend.position = c(.8,.8),
        legend.key = element_blank()) +
  guides(colour='none',size=guide_legend('Island area',reverse = T)) +
  scale_size_continuous(breaks = c(-0.8,1.4),labels = c('Flores','New Guinea')) +
  xlab('Precipitation seasonality') +
  ylab('Model predictions of\nlocal tree diversity')
  
### Figure map with sites 
library(mapdata)

Indo_map_data=map_data("world2Hires") %>% filter(region=='Indonesia') %>%
  rename('LONG'=long,'LAT'='lat') %>% 
  mutate('BGR'=case_when(LONG > 131.8 ~'Sahul',
                         region=='Australia'~'Sahul',
                         subregion %in% c('Waigeo','Salawati')~'Sahul',
                         between(LONG,130.38,130.938) & between(LAT,-0.921,-0.73)~'Sahul',
                         between(LONG,130.43,130.7) & between(LAT,-0.542,-0.383)~'Sahul',
                         subregion=='Bali'~'Sunda',
                         LONG < 115.3 ~ 'Sunda',
                         between(LONG,111.43,119.5) & between(LAT,-4.323,7.7)~'Sunda',
                         T~'Wallacea'))

BGR_labs=tibble('BGR'=c('Sunda','Wallacea','Sahul'),
       x=c(108,124,138),
       y=c(5.5,5.7,0.9))


plots_map=ggplot() + 
 geom_polygon(data=Indo_map_data, aes(x=LONG, y=LAT, group=group,fill=BGR)) +
  geom_point(data = alpha_env,position=position_jitter(width=.1, height=.1),
             aes(x=Long,y=Lat,colour=interpolated_alpha),
              shape=1,size=2,stroke=.7,fill=NA) +
  geom_label(data = BGR_labs,aes(x=x,y=y,label=BGR,fill=BGR),size=3,colour='black',
             show.legend=F) +
  geom_text(data = alpha_env %>% distinct(Island) %>% 
  filter(!Island %in% c('Bangka','Buton','Weh')) %>%
  mutate('Latitude'=case_when(Island=='Kalimantan'~3.7,
                              Island=='Sumatra'~3.1,
                              Island=='Java'~-9,
                              Island=='Sulawesi'~2.4,
                              Island=='Yamdena'~-9,
                              Island=='West Papua'~-4.2,
                              Island=='Halmahera'~3,
                              Island=='Wawonii'~-3.1,
                              Island=='Sumbawa'~-10,
                              Island=='Flores'~-7.6,
                              Island=='Seram'~-4.5,
                              Island=='Waigeo'~0.65),
         'Longitude'=case_when(Island=='Kalimantan'~112.7,
                               Island=='Sumatra'~103,
                               Island=='Java'~109,
                               Island=='Sulawesi'~122.3,
                               Island=='Yamdena'~132.5,
                               Island=='West Papua'~138,
                               Island=='Halmahera'~126.8,
                               Island=='Wawonii'~124,
                               Island=='Sumbawa'~117.1,
                               Island=='Flores'~120.6,
                               Island=='Seram'~129.6,
                               Island=='Waigeo'~131.8)) %>%
    mutate('Island'=str_replace(Island,'West Papua','Indonesian\nNew Guinea'),
           'Island'=str_replace(Island,'Kalimantan','Indonesian\nBorneo')),
  aes(x=Longitude,y=Latitude,label=Island),size=3) +
  theme(panel.background = element_rect(fill='grey80'),
        panel.grid = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank(),
        legend.position = c(0.07,.3)) +
  scale_colour_distiller(palette = 'PRGn',
                       direction = 1,
                       name='Tree\ndiversity',breaks=c(10,30,50))  +
  scale_fill_manual(values=c('peachpuff2','tomato','skyblue2')) +
  guides(colour=guide_colourbar(ticks = T,frame.colour = 'black',ticks.colour = 'black',
                                barwidth = .8,barheight = 2.9),
         fill='none')

##ggsave(plots_map,filename = 'plots_map.jpeg',dpi = 300,width = 180,height = 75,units = 'mm')

alpha_islands=alpha_env %>% filter(!Island %in% c('Bangka','Buton','Weh')) %>%
     mutate('Island'=str_replace(Island,'West Papua','Indonesian\nNew Guinea'),
           'Island'=str_replace(Island,'Kalimantan','Indonesian\nBorneo')) %>%
  ggplot(aes(x=Island,y=interpolated_alpha,fill=BGR)) +
    stat_summary(geom = 'crossbar',size=.5,
               fun.data = 'mean_sdl',fun.args = list(mult = 1),width=.4) +
  theme(panel.background = element_blank(),
        panel.grid = element_blank(),
        legend.position = 'none',
        legend.text = element_blank(),
        axis.line = element_line()) +
  scale_fill_manual(values=c('peachpuff2','tomato','skyblue2')) +
  xlab(NULL) +
  ylab('Tree diversity') +
  scale_x_discrete(limits=c(alpha_env %>% filter(!Island %in% c('Bangka','Buton','Weh')) %>%
                                  mutate('Island'=str_replace(Island,'West Papua','Indonesian\nNew Guinea'),
                                         'Island'=str_replace(Island,'Kalimantan','Indonesian\nBorneo'))
                            %>%
  group_by(Island) %>% mutate(mean_long=mean(Long)) %>% arrange(mean_long) %>% distinct(Island) %>%.$Island))

sumlmm=summary(alpha_lmm_selected) 
sumlmmgeol=summary(alpha_lmm_geol)

effects_plot=rbind(sumlmm$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% add_column('model'='selected'),
  sumlmmgeol$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% add_column('model'='quake')
  ) %>% 
  left_join(tibble('model'=c('selected','quake'),
                   'AIC'=c(AIC(alpha_lmm_selected),AIC(alpha_lmm_geol)))) %>%
  filter(predVars!='(Intercept)') %>% 
  mutate('predVars'=str_replace(predVars,'Elev_z','Elevation'),
         'predVars'=str_replace(predVars,'P_seasonality_z','Precipitation\nseasonality'),
         'predVars'=str_replace(predVars,'soil_C_z','Soil carbon'),
         'predVars'=str_replace(predVars,'Island_size_z','Island area'),
         'predVars'=str_replace(predVars,'dist_quake_z','Earthquake\nproximity')) %>%
  ggplot(aes(x=Effect,y=predVars)) +
  geom_pointrange(aes(xmin=Effect-error,xmax=Effect+error,colour=AIC),
                  fatten=.5,size=2,position = position_dodge2(padding=.2,width = .3)) +
  geom_segment(x=0,xend=0,y=0,yend=Inf,linetype='dashed',colour='grey40') +
  theme(panel.background = element_rect(fill='grey80'),
        panel.grid = element_blank(),
        axis.line = element_line(),
        axis.text.y = element_text(size=10),
        legend.justification = c("right", "bottom"),
        legend.background = element_blank(),
        legend.position = c(.96,.08),
        legend.title = element_blank()) +
  ylab(NULL) +
  xlab('Effect upon tree diversity') +
  scale_x_continuous(breaks=c(-2.5,0,2.5,5)) +
  scale_color_fermenter(palette='PuOr',breaks=c(1398),labels=c('High AIC\n\nLow AIC')) +
  guides(colour=guide_colorsteps(barheight=2,barwidth=.5,frame.colour='black'))

### Do extrapolated data figure here .... try combine all lmm output together ....
### add column for model ie. geol or not and then another for diversity individuals ie 60-300 ....

fig_extrap=rbind(summary(alpha_lmm_selected100)$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% 
    add_column('model'='Environment model','individuals'='100'),
  summary(alpha_lmm_selected200)$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% 
    add_column('model'='Environment model','individuals'='200'),
  summary(alpha_lmm_selected300)$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% 
    add_column('model'='Environment model','individuals'='300'),
  summary(alpha_lmm_geol100)$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% 
    add_column('model'='Earthquake model','individuals'='100'),
  summary(alpha_lmm_geol200)$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% 
    add_column('model'='Earthquake model','individuals'='200'),
  summary(alpha_lmm_geol300)$coefficients %>% as.data.frame() %>% rownames_to_column('predVars') %>%
  select(predVars,'Effect'=Estimate,'error'='Std. Error') %>% 
    add_column('model'='Earthquake model','individuals'='300')
  ) %>% filter(predVars!='(Intercept)') %>% 
  mutate('predVars'=str_replace(predVars,'Elev_z','Elevation'),
         'predVars'=str_replace(predVars,'P_seasonality_z','Precipitation\nseasonality'),
         'predVars'=str_replace(predVars,'soil_C_z','Soil carbon'),
         'predVars'=str_replace(predVars,'Island_size_z','Island area'),
         'predVars'=str_replace(predVars,'dist_quake_z','Earthquake\nproximity')) %>%
  ggplot(aes(x=Effect,y=predVars)) +
  geom_pointrange(aes(xmin=Effect-error,xmax=Effect+error,colour=as.numeric(individuals)),
                  fatten=.5,size=2,position = position_dodge2(padding=.2,width = .5)) +
  geom_segment(x=0,xend=0,y=0,yend=Inf,linetype='dashed',colour='grey40') +
  theme(panel.background = element_blank(),
        panel.grid.major.y = element_line(colour='grey90'),
        panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        axis.line = element_line(),
        axis.text.y = element_text(size=10),
        legend.justification = c("right", "bottom"),
        legend.background = element_blank(),
        legend.position = c(.99,.02),
        legend.title = element_text(size=7)) +
  ylab(NULL) +
  xlab('Effect upon tree diversity') +
  facet_grid(cols = vars(model)) +
  scale_color_fermenter(palette='Set2',breaks=c(100,199,299,399),limits=c(100,399),
                        labels=c('100','200','300','')) +
  guides(colour=guide_colorsteps(title='No. individuals used\nto calculate diversity',barheight=2,barwidth=.5,frame.colour='black',
                                 show.limits = T))

##ggsave(fig_extrap,filename='FigS4.pdf',height = 6,width=16,units='cm')

library(sf)
library(rnaturalearth)
library(rnaturalearthdata)

world = ne_countries(scale = "medium", returnclass = "sf")

Malesia_polygon=tibble(x=c(92,158,158,92),y=c(-15,-15,19,19))

map_world=ggplot(data = world) +
  geom_sf(colour='grey90',size=.01) +
  theme(panel.background = element_rect(colour=NA,fill=NA),
        panel.grid = element_blank(),
        axis.title = element_blank()) +
  geom_polygon(data = Malesia_polygon, aes(x=x,y=y),fill=NA,colour='grey40') 

unloadNamespace('mapdata')
unloadNamespace('rnaturalearth')
unloadNamespace('rnaturalearthdata')
unloadNamespace('sf')

library(cowplot)

fig_1=ggdraw() +
  draw_plot(fig_pics,x=0,y=.78,width = 1,height = .22) +
  draw_plot(plots_map,x=-0.025,y=.475,width = 1.05,height=.3) +
  draw_plot(map_world,x=.83,y=.64,width = .18,height = .19) +
  draw_plot(alpha_islands,x=0,y=.27,width = 1,height = .22) +
  draw_plot(effects_plot,x=0,y=0,width = .53,height = .24) +
  draw_plot(plot_BGR_intercepts,x=.28,y = .14,width = .25,height = .14) +
  draw_plot(predict_plot,x=.57,y=0,width = .43,height=.28) +
  draw_plot_label(label=c('(a)','(b)','(c)','(d)','(e)'),x=c(-0.01,-0.01,-0.01,-0.01,.55),y=c(1,.77,.48,.26,.26),
                  fontface = 'plain',colour = c('black','black','black','black','black'),size = 11)


fig_1save=ggdraw() +
  draw_plot(fig_pics,x=0,y=.78,width = 1,height = .22) +
  draw_plot(plots_map,x=-0.025,y=.475,width = 1.05,height=.3) +
  draw_plot(map_world,x=.83,y=.64,width = .18,height = .19) +
  draw_plot(alpha_islands,x=0,y=.28,width = 1.12,height = .22) +
  draw_plot(effects_plot,x=0,y=0,width = .53,height = .24) +
  draw_plot(plot_BGR_intercepts,x=.26,y = .14,width = .26,height = .165) +
  draw_plot(predict_plot,x=.57,y=0,width = .43,height=.28) +
  draw_plot_label(label=c('(a)','(b)','(c)','(d)','(e)'),x=c(-0.01,-0.01,-0.01,-0.01,.55),y=c(1,.77,.48,.24,.24),
                  fontface = 'plain',colour = c('black','black','black','black','black'),size = 11)

##ggsave(fig_1save, filename = 'fig_1.2.pdf', dpi = 350, width = 200,height = 290, units = 'mm')

```

__Materials and Methods__  

Species/morphospecies abundance lists were compiled for trees $\geq$ 10 cm diameter, from `r nrow(alpha_env)` georeferenced plots (Fig. 1b), ranging in size from 0.2 ha to 10.5 ha (plot metadata and reference list in supplementary material) across Weh (1 plot), Sumatra (8), Bangka (1), Java (10), Indonesian Borneo (42), Sumbawa (14), Flores (4), Sulawesi (22), Buton (1), Wawonii (6), Halmahera (2), Seram (5), Yamdena (64), Waigeo (4) and Indonesian New Guinea (11) [@brearley_opportunities_2019]. Accepted species names followed the World Checklist of Vascular Plants [@govaerts_world_2021; @walker_kewr_2021]. Our diversity metric was rarefied Hill diversity akin to species richness [@chao_rarefaction_2014]. The rarefied metric was equivalent to the diversity we would expect if plots had the same number of individuals as the plot with the fewest, in this case 60. Rarefaction allowed us to account for differences in numbers of individuals per plot and therefore compare plots of different sizes [@hsieh_inext:_2016]. This rarefied diversity metric is henceforth termed “diversity”. To determine if rarefaction impacted our results we also calculated diversity indices equivalent to that found for 100, 200 and 300 individuals across all plots and repeated analyses below using these data as response variables [@hsieh_inext:_2016].  

We examined the drivers of local tree diversity in Indonesia with a Gaussian mixed effects model and an identity link function. Tree diversity was modelled as a function of island area (total island area used for Borneo and New Guinea as these differ from the Indonesian border) and environmental variables (elevation, precipitation seasonality, and soil carbon). These environmental variables were chosen because they have been shown to influence tropical tree diversity [@brambach_diversity_2017; @baltzer_role_2008; @draper_peatland_2018] and were the largest independent contributors (Fig. S1) to the three principal component axes that represented `r sumenvPCA$importance %>% as.data.frame() %>% rownames_to_column('data') %>% filter(data=='Cumulative Proportion') %>% mutate(PC3=PC3*100) %>% .$PC3 %>% round(0)` % variability in mean annual temperature, temperature range, elevation, mean annual precipitation, precipitation seasonality, soil nitrogen, soil carbon and soil cation exchange capacity taken from SRTM, WorldClim and SoilGrids databases [@hengl_soilgrids250m_2017; @exposito-alonso_rbioclim_2017; @farr_shuttle_2007]. When the three selected variables, elevation, precipitation seasonality and soil carbon were included in the model, alongside island area, all predictor Variance Inflation Factors (VIFs) were below 1.7 (Fig. S2) indicating a lack of covariation amongst predictors. Given that we also wanted to test how geological activity affected diversity, we also built a model where precipitation seasonality was replaced with earthquake proximity, as parameters for this model had VIFs below 1.7 (Fig. S2). We used proximity to earthquakes rather than volcanoes, as VIFs for the model parameterised with volcano proximity exceeded 1.7. All predictors were scaled, as z-scores, prior to analysis to allow effect score comparison. Proximity to earthquakes (> 7.5 Richter magnitude since 2150 BC) and volcanoes was calculated from the NGDC/WDS databases [@national_geophysical_data_centerworld_data_service_global_2023-1; @national_geophysical_data_centerworld_data_service_global_2023]. Volcano data was expanded with data from @whelley_frequency_2015. We also included a random intercept for bioregions (Sunda, Wallacea or Sahul). Bioregions follow the concept first outlined by Heilprin and Darlington [Fig. 1b, @ali_wallaces_2021]. This reflected the different climatic and geological histories found between bioregions (Fig. S3). Model residuals did not show spatial dependence [Moran's I test both *p* > 0.5, @hartig_dharma_2021]. Finally, prediction error, using the Akaike Information Criterion, was compared between models parameterised either by precipitation seasonality and earthquake proximity.  

__Results__  

Mean diversity per island was lowest in the seasonally dry forests of `r alpha_env %>% group_by(Island) %>% summarise(mean_alph=mean(interpolated_alpha)) %>% slice(which.min(mean_alph)) %>% .$Island` (diversity = `r alpha_env %>% group_by(Island) %>% summarise(mean_alph=mean(interpolated_alpha)) %>% slice(which.min(mean_alph)) %>% .$mean_alph %>% round(2)` and standard error (SE) = `r alpha_env %>% group_by(Island) %>% summarise(se_alph=sd(interpolated_alpha)/sqrt(length(interpolated_alpha))) %>% slice(which.min(se_alph)) %>% .$se_alph %>% round(2)`) and highest in the wet forests of `r alpha_env %>% group_by(Island) %>% summarise(mean_alph=mean(interpolated_alpha)) %>% slice(which.max(mean_alph)) %>% .$Island` (diversity = `r alpha_env %>% group_by(Island) %>% summarise(mean_alph=mean(interpolated_alpha)) %>% slice(which.max(mean_alph)) %>% .$mean_alph %>% round(2)` and SE = `r alpha_env %>% group_by(Island) %>% summarise(se_alph=sd(interpolated_alpha)/sqrt(length(interpolated_alpha))) %>% slice(which.max(se_alph)) %>% .$se_alph %>% round(2)`.00) (Fig. 1c). The model parameterised by precipitation seasonality found a negative effect of precipitation seasonality and soil carbon and a positive effect of island area on local tree diversity (precipitation seasonality effect = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='P_seasonality_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='P_seasonality_z') %>% .$Std..Error %>% round(2)`, soil carbon effect = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='soil_C_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='soil_C_z') %>% .$Std..Error %>% round(2)`, island area effect = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Island_size_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Island_size_z') %>% .$Std..Error %>% round(2)`, Fig. 1d). There was no effect of elevation (effect = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Elev_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmm$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Elev_z') %>% .$Std..Error %>% round(2)`). The model parameterised by earthquake proximity showed a small negative effect of soil carbon and a positive effect of island area upon local tree diversity (soil carbon effect = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='soil_C_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='soil_C_z') %>% .$Std..Error %>% round(2)`, island area effect = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Island_size_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Island_size_z') %>% .$Std..Error %>% round(2)`, Fig. 1d). Elevation had a small positive effect on local tree diversity, whereas earthquake proximity had a small negative effect (elevation effect = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Elev_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='Elev_z') %>% .$Std..Error %>% round(2)`, earthquake proximity effect = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='dist_quake_z') %>% .$Estimate %>% round(2)` and SE = `r sumlmmgeol$coefficients %>% data.frame() %>% rownames_to_column('predictor') %>% filter(predictor=='dist_quake_z') %>% .$Std..Error %>% round(2)`).  

Random effect intercepts for the precipitation seasonality model suggested that bioregion was strongly associated with tree diversity. The highest effects were in Sunda (intercept = `r BGR_intercepts %>% filter(model=='selected' & BGR=='Sunda') %>% .$Intercept %>% round(2)`) followed by Wallacea (`r BGR_intercepts %>% filter(model=='selected' & BGR=='Wallacea') %>% .$Intercept %>% round(2)`) and then Sahul (`r BGR_intercepts %>% filter(model=='selected' & BGR=='Sahul') %>% .$Intercept %>% round(2)`, Fig. 1d inset). This suggests that in Sahul diversity is lower than would be predicted by environmental variables and island area alone (Fig. 1e). Likewise, for a given value of island area and environmental variable, Wallacea has lower diversity than Sunda (but higher than Sahul). The bioregion random effect explained approx. `r round(sumlmm$varcor$BGR %>% as.data.frame() %>% .$'(Intercept)'/max(alpha_env$interpolated_alpha)*100,0)` % of variation in tree diversity. However, when earthquake proximity was included in the model differences amongst bioregions were reduced (`r round(sumlmmgeol$varcor$BGR %>% as.data.frame() %>% .$'(Intercept)'/max(alpha_env$interpolated_alpha)*100,0)` % variation in diversity explained, Fig. 1d inset).

The model parameterised by precipitation seasonality that also had larger differences between bioregions according to random effect intercepts was more precise than the model that showed smaller differences between bioregions and was parameterised by earthquake proximity (precipitation seasonality model AIC `r round(AIC(alpha_lmm_geol))-round(AIC(alpha_lmm_selected))` less than earthquake proximity model, Fig. 1d).  

Results repeated with diversity metrics equivalent to 100, 200 and 300 did not show large differences from that calculated from 60 individuals (Fig. S4). 

```{r fig-1,message=F,error=F,echo=F,fig.height=10.4,fig.width=7.5,dpi=300,dev='jpeg',fig.cap='(a) Forests across Indonesia\'s three bioregions. Top left wet lowland Central Kalimantan. Top middle wet lowland Halmahera. Top right wet lowland Waigeo. Bottom left Mount Salak, Java. Bottom middle seasonally dry forest West Sumbawa. Bottom right Arfak mountains, Indonesian New Guinea. (b) Map of Indonesian rarefied forest plot tree diversity and their global position (inset). (c) Rarefied tree diversity per island. Islands with single plots not shown. Boxplots represent island mean and standard deviation diversity. (d) +/- 1 standard error (horizontal lines) for effects (points) of environmental variables, earthquake proximity and island area on local tree diversity in Indonesia. Both models either with precipitation seasonality or earthquake proximity parameters are shown, hence single effects shown for these two parameters. Inset shows the random effect intercepts for bioregion across our two models. Point colour shows model prediction error as measured by the Aikake Information Criterion (AIC). (e) Mixed effect model predictions for local tree diversity in plots along the precipitation seasonality gradient, on islands of varying area, across three bioregions. Point opaqueness shows overlapping points. Photographers for (a): Top left Nanang Sujana, CIFOR; Top middle JS; Top right JS; Bottom left Mokhamad Edliadi, CIFOR; Bottom middle LAT; Bottom right LAT.'}

### https://www.flickr.com/photos/cifor/35976721034/in/album-72157677975003023/
### https://www.flickr.com/photos/cifor/35991686011/in/album-72157632697450461/

fig_1
```

__Discussion__

Here, we have analysed 215 forest plots across fifteen major islands of the Indonesian archipelago and shown that local tree diversity appears to be influenced by fine-scale local environment and proximity to earthquakes, and by large-scale drivers of island area and bioregion.

The physiological limits imposed by drought should be detrimental to the number of tropical trees able to co-exist locally [@baltzer_role_2008; @baltzer_rainfall_2012]. Our results showing declining diversity with precipitation seasonality indicate that drought effects are relevant across large scales.

We did not find a clear relationship between elevation and diversity, perhaps caused by our plots not spanning sufficiently high elevations to detect diversity tail-off. Alternatively, it may be due to differing mountain topography, where dependent upon how/if mountains taper, large-scale diversity-elevation relationships can differ from monotonic decline in richness to an increase [@elsen_global_2015]. For instance, the central New Guinea highlands have a 'diamond' shaped topography where area is greatest at mid-elevations [@elsen_global_2015]. Similarly, mountain species pools may not necessarily decline linearly with elevation [@bachman_elevational_2004; @whitman_edaphic_2021]. Our results suggest that mountain species pools, rather than elevation per se, could be a major driver of local diversity [@rosenzweig_species_1995]. This could also be reflected across different habitats. For instance, in the Amazon low soil nutrient habitats are locally rich if that habitat is widely distributed and vice versa high nutrient habitat with a small species pool can show low diversity [ter @ter_steege_mapping_2023]. 

We have shown how important island area and linked species pool size variation [@zobel_relative_1997] are for local tropical tree diversity. These patterns are therefore key to understanding drivers of diversity of the tropical ecosystems where most global diversity exists. Larger islands have more species and can therefore support more species at local scales [@rosenzweig_echo_1999; @roos_species_2004]. To examine this further we require more baseline floristic data from Indonesia and neighbouring countries. First, we need to accelerate the production of  expert-led species checklists and taxonomic revisions across the region [@camara-leret_new_2020; @rustiami_checklist_2020; @joyce_checklist_2020]. Despite taxonomic information being critical to identify tree individuals from forest plots, many big tropical genera still remain taxonomically neglected [@frodin_history_2004]. Second, better interdisciplinary collaboration among ecologists and taxonomists is needed. This will be important for ecologists who want to have high-grade vouchers [@baker_maximising_2017], and for systematists who seek to understand what drives trait variation across the archipelago. The growth of dual expert-verified data would allow examination of island species-area relationships and their dependence upon environmental variation between and within islands.

Here we have assumed that larger islands have larger species pools. However, equally species-rich pools may differ in the diversity of traits that they support [@spasojevic_integrating_2018]. Traits determine species ability to persist in an environment so the trait pool should better reflect the number of species that can occur at small-scales [@spasojevic_integrating_2018; @schrader_roadmap_2021]. Likewise, the overall dispersal capacity of pools should shape how many species can disperse into and occur at sites [@xie_can_2023]. Exploration of these potential patterns would require the collation and analysis of trait data linked to dispersal and adaptation to environment, such as height, leaf and fruit size [@olson_plant_2018; @wright_global_2017; @brodie_fruit_2022; @trethowan_environment-dependent_2023; @trethowan_environmental_2022].

Our results suggest an influence of biogeographic history upon local tropical tree diversity. We find a decrease with longitude from Sunda to Sahul rather than clear differences between the ancient geological region of Sunda and younger Wallacea and Sahul. This could reflect increasing distance from the wet tropical source pool of mainland Southeast Asia, as opposed to Australia where Neogene aridification drove widespread extinction of rainforest taxa [@kooyman_origins_2019; @byrne_decline_2011]. Heightened diversity with closer proximity to the western source pool suggests that dispersal distances have been crucial for the formation of modern diversity in Indonesia [@macarthur_equilibrium_1963]. Greater chance of tropical lineage dispersal, from the western source pool, also promotes their opportunities for diversification [@crayn_sahulsunda_2015; @atkins_molecular_2019; @kooyman_origins_2019; @morley_assembly_2018]. In the western bioregions, this presumably increased the proportion of species adapted to tropical conditions. Here, these species that are pre-adapted to modern conditions are less likely to be outcompeted, and potentially a greater number of species can coexist [@harrison_toward_2008; @swenson_biogeographic_2023]. However, our model incorporating geological activity showed reduced differences in local diversity explained by bioregion. Regional geology causing non-climatic differences between bioregions, e.g., via earthquake frequency, is therefore likely important for local diversity. 

We have shown, for the first time, how local tree diversity varies across Indonesia. With this new Indonesian plot-based data, future global studies of local tree diversity will have an opportunity to better cover the entirety of the tropics [@sullivan_diversity_2017; @cazzolla_gatti_number_2022; @parmentier_odd_2007; ter @ter_steege_mapping_2023]. Local and indigenous groups in Indonesia have interacted with plants for millennia and still use thousands of species [@camara-leret_information_2019; @sheil_diversity_2012; @sheil_anthropogenic_2012], so further studies of human’s ecological legacies on the archipelago’s forests are warranted [@hamilton_non-uniform_2021]. However, more forest plot-based data are still needed. Sampling of the large, forested areas in Southeast Sulawesi, Flores, Sumba and Indonesian New Guinea should remain a priority, including coverage of high elevations and extreme ultramafic and karstic soils [@galey_ultramafic_2017; @geekiyanage_plant_2019; @brambach_predominant_2020].

Diversity is key for the functioning of ecosystems [@jucker_stabilizing_2014; van der @van_der_plas_continental_2018]. We have highlighted here how for a megadiverse tree flora the parameters of diversity vary from the fine-scale and modern to the large-scale and historic. Therefore, studies that forecast diversity, including those that use the results to predict alteration of ecosystem function, should integrate relevant multi-scale parameters across space and time.

__Data availability__  
Plot diversity metrics, coordinates and an Rmarkdown to recreate the manuscript and analysis are available at [OA data repository link removed for double blind peer review].

__Supplementary__

```{r figS1,message=F,error=F,echo=F,fig.height=3.8,dpi=300,dev='jpeg',fig.cap='Correlations between all environmental, non-geological, variables and the three environmental principal component (PC) axes used to select the variables used in the two models of Indonesian tree diversity.'}

pc_loadings_plot=envPCA$rotation %>% as.data.frame() %>% rownames_to_column('envVar') %>%
  select(1:4) %>% pivot_longer(starts_with('PC'), names_to = 'axis') %>% 
  mutate('selected'=case_when(envVar %in% c('alt','soil_C')~'Parameters in both models',
                              envVar %in% c('P_seasonality')~'Parameter in precipitation\nseasonality model')) %>%
  mutate('envVar'=str_replace(envVar,'alt','Elevation'),
         'envVar'=str_replace(envVar,'MAP','Mean annual\nprecipitation'),
         'envVar'=str_replace(envVar,'MAT','Mean annual\ntemperature'),
         'envVar'=str_replace(envVar,'P_seasonality','Precipitaition\nseasonality'),
         'envVar'=str_replace(envVar,'soil_CEC','Soil cation\nexchange capacity'),
                  'envVar'=str_replace(envVar,'soil_C','Soil carbon'),
         'envVar'=str_replace(envVar,'soil_N','Soil nitrogen'),
         'envVar'=str_replace(envVar,'T_range','Temperature\nrange'),
         'envVar'=str_replace(envVar,'dist_quake','Earthquake\nproximity'),
         'envVar'=str_replace(envVar,'dist_volcano','Volcano\nproximity')) %>%
  ggplot(aes(x=envVar,y=value,fill=selected)) +
  geom_bar(stat = 'identity') +
  facet_grid(rows = vars(axis)) +
  xlab('Relationship between environmental variables and PC axes') +
  ylab(NULL) +
  theme(panel.background = element_blank(),
        panel.grid = element_blank(),
        axis.line = element_line(),
        strip.background = element_blank(),
        axis.text.x = element_text(size = 6),
        legend.title = element_blank(),
        legend.position = 'top') +
  scale_fill_discrete(limits=c('Parameters in both models','Parameter in precipitation\nseasonality model'))

### check colours okay
pc_loadings_plot

```

```{r figS2, message=F,error=F,echo=F,fig.height=1.7,out.width="80%",dpi=300,dev='jpeg',fig.cap='Variance inflation factors (VIFs) for the fixed predictors in our models of tree diversity. VIF values beyond five indicate covariation amongst predictors beyond which it is difficult to estimate coefficients.'}

figVIF=rbind(enframe(VIF_selected,name = 'predVars', value = 'VIF') %>%
  mutate('predVars'=str_replace(predVars,'Elev_z','Elevation'),
         'predVars'=str_replace(predVars,'P_seasonality_z','Precipitation\nseasonality'),
         'predVars'=str_replace(predVars,'soil_C_z','Soil carbon'),
         'predVars'=str_replace(predVars,'Island_size_z','Island area'),
         'predVars'=str_replace(predVars,'dist_quake_z','Earthquake\nproximity')) %>% 
  add_column('model'='Model 1'),
  enframe(VIF_geol,name = 'predVars', value = 'VIF') %>%
  mutate('predVars'=str_replace(predVars,'Elev_z','Elevation'),
         'predVars'=str_replace(predVars,'P_seasonality_z','Precipitation\nseasonality'),
         'predVars'=str_replace(predVars,'soil_C_z','Soil carbon'),
         'predVars'=str_replace(predVars,'Island_size_z','Island area'),
         'predVars'=str_replace(predVars,'dist_quake_z','Earthquake\nproximity')) %>% 
  add_column('model'='Model 2')
) %>%
  ggplot(aes(y=VIF,x=predVars)) +
  geom_bar(stat = 'identity') +
  xlab(NULL) +
  theme(axis.title.y = element_text(angle = 0,vjust = .5),
        axis.line = element_line(),
        panel.background = element_blank(),
        panel.grid = element_blank(),
        axis.text = element_text(size=6),
        axis.title = element_text(size=6)) +
  facet_grid(cols = vars(model),scales = 'free_x')

figVIF 
```

```{r figS3, message=F,error=F,echo=F,fig.height=3,dpi=500,dev='jpeg',fig.cap='Brief description of island uplift dynamics and timing for islands with least uncertainty.'}

timings=tibble('Island'='Sumatra','text'='After early Miocene\nsubmergence, began\nto emerge\nwith uplift of Barisan\nMountains in\nmiddle Miocene', LAT=-3,LONG=94) %>%
  add_row('Island'='Borneo','text'='Southwest Borneo emergent\nthroughout Cenozoic, but remainder of\n Borneo emergent from early Miocene\nonward with uplift of Central\nRanges and Meratus Mountains', LAT=9.5,LONG=101) %>%
  add_row('Island'='Sulawesi','text'='Locally emergent in\nEocene and Miocene, but\nisland assembled\n in Pliocene,\ntaking  present shape\nin Pleistocene', LAT=9,LONG=117) %>%
  add_row('Island'='Java','text'='West Java emergent in Pliocene,\nbut East Java\nemerged in Pleistocene', LAT=-11,LONG=105) %>%
  add_row('Island'='LSI','text'='Island arc formed\nin Pliocene',LAT=-13,LONG=118) %>%
  add_row('Island'='Timor','text'='Uplifted above sea level in\nlate Plio-Pleistocene',
          LAT=-12,LONG=133) %>%
  add_row('Island'='Seram','text'='Emergent in late Plio-Pleist.',
          LAT=-5,LONG=130) %>%
  add_row('Island'='Halmahera','text'='Volc. arcs present\nin west during Miocene,\n current configuration\nassembled in\nLate Plio-Pleist.',
          LAT=6,LONG=130) %>%
  add_row('Island'='Papua','text'='Uplift began in\nmid-Miocene,\nprobably 12 Myr,\nregion expanded\nin Pliocene and further\nin Pleistocene, when\ncurrent altitudes\nwere reached',
          LAT=6,LONG=142) 
  

geolmap=Indo_map_data %>%
  mutate('Island'=case_when(subregion=='Borneo'~'Borneo',
                         subregion=='Sumatra'~'Sumatra',
                         subregion=='Java'~'Java',
                         subregion=='Irian Jaya'~'Papua',
                         subregion %in% c('Sulawesi','Buton','Wawoni')~'Sulawesi',
                         subregion =='Halmahera'~'Halmahera',
                         subregion %in% c('Sumbawa','Bali','Lombok',
                                          'Flores','Sumba')~'LSI',
                         subregion %in% c('Timor',
                                          'Yamdena')~'Timor',
                         subregion =='Ceram'~'Seram')) %>% 
  filter(!is.na(Island)) %>% 
  ggplot() + 
 geom_polygon(aes(x=LONG, y=LAT, group=group,fill=Island),colour='grey40',linewidth=.2) +
  theme(axis.line = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank(),
        axis.ticks = element_blank(),
        panel.background = element_blank(),
        panel.grid = element_blank(),
        legend.title = element_blank(),
        legend.text = element_text(vjust=1.25),
        legend.position = 'none') +
  geom_label(data = timings,aes(x=LONG,y=LAT,fill=Island,label=text),colour='grey40',label.size=.2,size=2) +
  scale_fill_brewer(palette = 'Set3') +
  guides(fill=guide_coloursteps(barheight=3,barwidth=.7)) +
  xlim(90.6,147) + ylim(-15,12) 
  
##ggsave(geolmap,filename='FigS3.pdf',width=14,height=7,units='cm')

geolmap
```

```{r figS4, message=F,error=F,echo=F,warning=FALSE,fig.height=3.8,dpi=500,dev='jpeg',fig.cap='+/- 1 standard error (horizontal lines) for effects (points) of environmental variables, eathquake proximity and island area on local tree diversity in Indonesia. Here tree diversity was equivalent to that expected in each plot for 100, 200 and 300 individuals respectively.'}

fig_extrap

```


Supplementary Table 1 uploaded separately.

__References__  