for (species in ambiguous_species_ids){
counter = counter+1
if(counter %% 50==0){
# Print on the screen some message
print(paste0("iteration: ", counter))
}
species_name = gsub(".tif", "", species)
presence_absence_vector = c(species,as.numeric(count_table_no_amb[count_table_no_amb['species']==species,][2:9]))
# ----------This outcommented part below is the workflow that double-checks species distributions based on their current IUCN range. it takes very long though and is not necessary.------------
# create a new row for the dataframe
# presence_absence_vector = c(species,0,0,0,0,0,0,0,0)
# species_range = iucn_ranges[iucn_ranges@data$binomial==gsub("_", " ", species_name),]
# # only proceed if there is rnage information in the iucn file
# if (dim(species_range@data)[1]>0){
#   print(species_name)
#   # the orca always causes problems because the polygon file is too big, so handle it manually
#   if (species_name == 'Orcinus_orca'){
#     presence_absence_vector[2:9] = 1
#   } else if (species_name == 'Mus_musculus'){
#     presence_absence_vector[4] = 1
#   } else if (species_name == 'Balaenoptera_physalus'){
#     presence_absence_vector[2:9] = 1
#     presence_absence_vector[7] = 0
#   } else {
#     row = count_table_original[count_table_original$species == species,]
#     # get the column indeces where species is present
#     columns_of_interest = which(row > 0)
#     ambiguous_continents = list()
#     for (column in columns_of_interest){
#       area = names(row)[column]
#       # if the column is not the ambiguous one
#       if (!area%in%list('contains_ambiguous')){
#         cell_count = row[column]
#         # if the cells for the continent could all be ambiguous, do the test
#         if (cell_count>0 & cell_count<=row$contains_ambiguous){
#           ambiguous_continents = append(toString(area),ambiguous_continents)
#         } else if (cell_count>0){
#           # else if there are any cell counts, it is a real occurrence and we want to append it to the final vector
#           presence_absence_vector[column] = 1
#         }
#       }
#     }
#     for (continent in unlist(ambiguous_continents)){
#       presence_absence_vector = get_pa_vector_intersect(continent,species_range,presence_absence_vector)
#     }
#   }
#   new_pa_df[nrow(new_pa_df) + 1,] = presence_absence_vector
# }
new_pa_df[nrow(new_pa_df) + 1,] = presence_absence_vector
}
# sort df by species name
#new_pa_df$species = sub('.tif','',new_pa_df$species,fixed = TRUE)
new_pa_df = new_pa_df[order(new_pa_df['species']),]
write.table(new_pa_df,'../../processed/spatial_data/pa_file_cleaning_steps/step2_pa_file_all_taxa.txt',sep="\t",quote = FALSE,row.names=FALSE)
library(raster)
library(maptools)
library(maps)
library(rgeos)
setwd('/Users/tobias/GitHub/mammal_extinction/data/processed/spatial_data/')
#___________________functions_____________________________
cell_count_vector_ambiguous <- function(cells_species,cells_area,ambiguous_cells,cc_vector) {
cells_match = cells_species[cells_species%in%cells_area]
# if all matching cells are ambiguous, don't return any (we apply this function only to the big landmasses, not to small islands)
if (all(cells_match%in%ambiguous_cells)){
cells_match = c()
}
count = length(cells_match)
cc_vector = c(cc_vector,count)
return(cc_vector)
}
get_range_map_for_species_list <- function(species_list) {
# take care of some naming issues
clean_region_endemic_species_list = sub(' ','_',species_list)
clean_region_endemic_species_list = paste0(clean_region_endemic_species_list,'.tif')
clean_region_endemic_species_list = sub('Geocapromys_SP_A.tif','Geocapromys_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Nesophontes_SP_A.tif','Nesophontes_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Caprini_indet.tif','CapriniGen_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Dicroceros_sp.tif','Dicroceros_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('HexolobodontinaeGen_NOW_Sp_NOW.tif','HexolobodontinaeGen_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Homo_denisovans.tif','Homo_spDenisova.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Megaoryzomys_Sp_Now.tif','Megaoryzomys_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Nesoryzomys_Sp_B.tif','Nesoryzomys_SpB.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Nesoryzomys_Sp_C.tif','Nesoryzomys_SpC.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Nesoryzomys_Sp_D.tif','Nesoryzomys_SpD.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Peroryctes_SP_NOW.tif','Peroryctes_SpA.tif',clean_region_endemic_species_list)
clean_region_endemic_species_list = sub('Peroryctinae_GEN_NOW.tif','PeroryctinaeGen_SpA.tif',clean_region_endemic_species_list)
# read and add all species ranges
all_endemic_species_ranges = raster(paste0('../../raw/spatial_data/Present_Natural/',clean_region_endemic_species_list[1]))
for (species in clean_region_endemic_species_list[2:length(clean_region_endemic_species_list)]){
species_range = raster(paste0('../../raw/spatial_data/Present_Natural/',species))
all_endemic_species_ranges = all_endemic_species_ranges+species_range
}
return(all_endemic_species_ranges)
}
#___________________________________________
count_table_original = read.csv('pa_file_cleaning_steps/cell_count_ambiguous_filter_raw.txt',sep='\t')
count_table = count_table_original
count_table[count_table>0]=1
new_pa_df = read.table('pa_file_cleaning_steps/step2_pa_file_all_taxa.txt',header = TRUE)
all_combined = raster('../../raw/spatial_data/continent_shapes/raster_sum_all_regions.tif')
oceanic = raster('../../raw/spatial_data/continent_shapes/raster_oceanic_main.tif')
carribean = raster('../../raw/spatial_data/continent_shapes/raster_carribean.tif')
north_america = raster('../../raw/spatial_data/continent_shapes/raster_northamerica.tif')
south_america = raster('../../raw/spatial_data/continent_shapes/raster_southamerica.tif')
eurasia = raster('../../raw/spatial_data/continent_shapes/raster_eurasia.tif')
africa = raster('../../raw/spatial_data/continent_shapes/raster_africa.tif')
australia = raster('../../raw/spatial_data/continent_shapes/raster_australia.tif')
madagascar = raster('../../raw/spatial_data/continent_shapes/raster_madagascar.tif')
species_ranges=list.files('../../raw/spatial_data/Present_Natural/')
island_endemic_info = read.csv('../../raw/spatial_data/Trait_data.csv',header=TRUE)
island_endemic_info$Island.Endemicity
#_______________deal with island endemics______________________
# which species are still not in our final df?
#remaining_species = count_table[!count_table$species%in%new_pa_df$species,]
# which of those are island endemics?
island_endemics_df = island_endemic_info[island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
island_endemics_df
list_island_endemics = paste0(island_endemics_df$Genus, '_', island_endemics_df$Species,'.tif')
# set the mainland columns to 0, since all species in this list are known to be endemic to small islands
count_table[count_table$species%in%list_island_endemics,][, c(2,3,4,5,6)] = 0
# remove last column since we don't need it
isl_end_clean_pa_df = count_table[, -10]
write.table(isl_end_clean_pa_df,'../../processed/spatial_data/pa_file_cleaning_steps/step3_pa_file_fixed_island_endemics.txt',sep="\t",quote = FALSE,row.names=FALSE)
isl_end_clean_pa_df
list_island_endemics
# get all non-island endemics and set oceanic and caribbean to 0
island_endemics_df = island_endemic_info[!island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
island_endemics_df
# get all non-island endemics and set oceanic and caribbean to 0
non_island_endemics_df = island_endemic_info[!island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
list_non_island_endemics = paste0(non_island_endemics_df$Genus, '_', non_island_endemics_df$Species,'.tif')
list_non_island_endemics
isl_end_clean_pa_df
island_endemics_df = island_endemic_info[island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
list_island_endemics = paste0(island_endemics_df$Genus, '_', island_endemics_df$Species,'.tif')
# set the mainland columns to 0, since all species in this list are known to be endemic to small islands
count_table[count_table$species%in%list_island_endemics,][, c(2,3,4,5,6)] = 0
# remove last column since we don't need it
isl_end_clean_pa_df = count_table[, -10]
# get all non-island endemics and set oceanic and caribbean to 0
non_island_endemics_df = island_endemic_info[!island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
list_non_island_endemics = paste0(non_island_endemics_df$Genus, '_', non_island_endemics_df$Species,'.tif')
isl_end_clean_pa_df[isl_end_clean_pa_df$species%in%list_non_island_endemics,][, c(7,9)] = 0
isl_end_clean_pa_df
#_______________deal with island endemics______________________
# which species are still not in our final df?
#remaining_species = count_table[!count_table$species%in%new_pa_df$species,]
# which of those are island endemics?
island_endemics_df = island_endemic_info[island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
list_island_endemics = paste0(island_endemics_df$Genus, '_', island_endemics_df$Species,'.tif')
# set the mainland columns to 0, since all species in this list are known to be endemic to small islands
count_table[count_table$species%in%list_island_endemics,][, c(2,3,4,5,6)] = 0
# remove last column since we don't need it
isl_end_clean_pa_df = count_table[, -10]
# get all non-island endemics and set oceanic and caribbean to 0
non_island_endemics_df = island_endemic_info[!island_endemic_info$Island.Endemicity=='Occurs only on isolated islands',]
list_non_island_endemics = paste0(non_island_endemics_df$Genus, '_', non_island_endemics_df$Species,'.tif')
isl_end_clean_pa_df[isl_end_clean_pa_df$species%in%list_non_island_endemics,][, c(7,9)] = 0
# write final df to file
write.table(isl_end_clean_pa_df,'../../processed/spatial_data/pa_file_cleaning_steps/step3_pa_file_fixed_island_endemics.txt',sep="\t",quote = FALSE,row.names=FALSE)
#________________________________________________________
#________________adding some taxa, which are present in the more recent verion of the iucn-2016-3 database (inconsistent within iucn-2016-3)_______________________________
final_pa_df = read.table('../../processed/spatial_data/pa_file_cleaning_steps/step3_pa_file_fixed_island_endemics.txt',header = TRUE,stringsAsFactors=FALSE)
# order of columns: north_america south_america eurasia africa australia carribean madagascar oceanic
# Eudorcas_tilonura is from Eritrea; Ethiopia; Sudan
row = c('Eudorcas_tilonura.tif',0,0,0,1,0,0,0,0)
final_pa_df[nrow(final_pa_df) + 1,] = row
# remove '.tif' from species names
final_pa_df$species = sub('.tif','',final_pa_df$species,fixed = TRUE)
final_pa_df$species = sub('_',' ',final_pa_df$species,fixed = TRUE)
# sort by species name
final_pa_df = final_pa_df[order(final_pa_df['species']),]
write.table(final_pa_df,'../../processed/spatial_data/pa_file_cleaning_steps/step4_pa_file_added_missing_taxa.txt',sep="\t",quote = FALSE,row.names=FALSE)
# remove pre-quaternary occs
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt'')
#quaternary_tbl = subtbl[which(subtbl$age<2580000),]
quaternary_tbl = subtbl[which(subtbl$age<781000),]
#quaternary_tbl = quaternary_tbl[which(quaternary_tbl$age>500),]
# remove low precision records
quaternary_tbl = quaternary_tbl[which(abs(quaternary_tbl$delta_age)<10000),]
dim(quaternary_tbl)
# lo_file = "/Users/danielesilvestro/Desktop/Tobi/data20180117/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils.txt"
lo_file = "/Users/tobias/GitHub/mammal_extinction/data/processed/preservation_rates/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils_fixed_typos.txt"
lo_tbl = read.csv(lo_file,h=F,stringsAsFactors=F,sep="\t")
colnames(lo_tbl) = c("species","max_age","min_age")
# REMOVE NAs = CHECK IF IT's OK!!
lo_tbl$min_age[which(is.na(lo_tbl$min_age))] = lo_tbl$max_age[which(is.na(lo_tbl$min_age))]
# remove pre-quaternary occs
subtbl= read.table('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt'')
#quaternary_tbl = subtbl[which(subtbl$age<2580000),]
quaternary_tbl = subtbl[which(subtbl$age<781000),]
#quaternary_tbl = quaternary_tbl[which(quaternary_tbl$age>500),]
# remove low precision records
quaternary_tbl = quaternary_tbl[which(abs(quaternary_tbl$delta_age)<10000),]
dim(quaternary_tbl)
# lo_file = "/Users/danielesilvestro/Desktop/Tobi/data20180117/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils.txt"
lo_file = "/Users/tobias/GitHub/mammal_extinction/data/processed/preservation_rates/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils_fixed_typos.txt"
lo_tbl = read.csv(lo_file,h=F,stringsAsFactors=F,sep="\t")
colnames(lo_tbl) = c("species","max_age","min_age")
# REMOVE NAs = CHECK IF IT's OK!!
lo_tbl$min_age[which(is.na(lo_tbl$min_age))] = lo_tbl$max_age[which(is.na(lo_tbl$min_age))]
# remove pre-quaternary occs
subtbl= read.table('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt')
# remove pre-quaternary occs
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt')
# remove pre-quaternary occs
subtbl= read.table('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
head(subtbl)
# remove pre-quaternary occs
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
head(subtbl)
subtbl$age
(subtbl$max_age+subtbl$min_age)/2
subtbl$age = (subtbl$max_age+subtbl$min_age)/2
subtbl$max_age-subtbl$min_age
subtbl$age
# remove pre-quaternary occs
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
subtbl$age = (subtbl$max_age+subtbl$min_age)/2
subtbl$delta_age = subtbl$max_age-subtbl$min_age
subtbl$max_age = subtbl$max_age*1000000
# remove pre-quaternary occs
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
subtbl$max_age = subtbl$max_age*1000000
subtbl$min_age = subtbl$min_age*1000000
subtbl$age = (subtbl$max_age+subtbl$min_age)/2
subtbl$delta_age = subtbl$max_age-subtbl$min_age
#quaternary_tbl = subtbl[which(subtbl$age<2580000),]
quaternary_tbl = subtbl[which(subtbl$age<781000),]
quaternary_tbl
#quaternary_tbl = quaternary_tbl[which(quaternary_tbl$age>500),]
# remove low precision records
quaternary_tbl = quaternary_tbl[which(abs(quaternary_tbl$delta_age)<10000),]
dim(quaternary_tbl)
head(subtbl)
# lo_file = "/Users/danielesilvestro/Desktop/Tobi/data20180117/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils.txt"
lo_file = "/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils_fixed_typos.txt"
lo_tbl = read.csv(lo_file,h=F,stringsAsFactors=F,sep="\t")
colnames(lo_tbl) = c("species","max_age","min_age")
# REMOVE NAs = CHECK IF IT's OK!!
lo_tbl$min_age[which(is.na(lo_tbl$min_age))] = lo_tbl$max_age[which(is.na(lo_tbl$min_age))]
lo_tbl$max_age[which(is.na(lo_tbl$max_age))] = lo_tbl$min_age[which(is.na(lo_tbl$max_age))]
lo_tbl = cbind(lo_tbl,(lo_tbl$max_age+lo_tbl$min_age)/2)
colnames(lo_tbl) = c("species","max_age","min_age","age")
occs_data = NULL
occs_count = c()
time_span = c()
time_until_known_extinction = c()
species_with_time_until_known_extinction = c()
j=1
for (taxon in lo_tbl$species){
tax = gsub("_"," ",taxon)
G = grep(tax, quaternary_tbl$species,fixed=T)
count = length(G)
#print( c(tax, ))
occs_pbdb = quaternary_tbl$age[G]
comb_ages = sort(as.numeric(c(lo_tbl$age[j],occs_pbdb)))
ages = list(comb_ages)
occs_data[j] = ages
if (count>1){
print(comb_ages)
occs_count = c(occs_count,length(comb_ages))
time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
}
#if (min(comb_ages)<=500 & count>=1){
#	occs_count = c(occs_count,length(comb_ages))
#	time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
#	time_until_known_extinction = c(time_until_known_extinction, min(occs_pbdb)-lo_tbl$age[j] )
#	species_with_time_until_known_extinction = c(species_with_time_until_known_extinction, tax )
#}
j = j+1
}
par(mfrow=c(1,2))
plot(log(occs_count/time_span)~log(occs_count),xlab="log n. occurrences",ylab = "log preservation rate")
abline(lm(log(occs_count/time_span)~log(occs_count)),col="red")
regression = lm(log(occs_count/time_span)~log(occs_count))
get_log_rate <- function(n_occs=1){
a = regression$coefficients[2]
b = regression$coefficients[1]
y = a*log(n_occs) + b
return(y)
}
plot(exp(get_log_rate(1:100)),type="l",xlab = "n. occurrences",ylab = "preservation rate")
plot(log(occs_count/time_span)~log(occs_count),xlab="log n. occurrences",ylab = "log preservation rate")
occs_count
time_span
lo_tbl$species
quaternary_tbl
quaternary_tbl$species
quaternary_tbl$name
lo_tbl$species
quaternary_tbl
quaternary_tbl$name
replace(quaternary_tbl$name,' ','_')
replace(quaternary_tbl$name,' ','_')
gsub(' ','_',quaternary_tbl$name)
# remove pre-quaternary occs
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
subtbl$max_age = subtbl$max_age*1000000
subtbl$min_age = subtbl$min_age*1000000
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
subtbl$max_age = subtbl$max_age*1000000
subtbl$min_age = subtbl$min_age*1000000
subtbl$age = (subtbl$max_age+subtbl$min_age)/2
subtbl$delta_age = subtbl$max_age-subtbl$min_age
#quaternary_tbl = subtbl[which(subtbl$age<2580000),]
quaternary_tbl = subtbl[which(subtbl$age<781000),]
#quaternary_tbl = quaternary_tbl[which(quaternary_tbl$age>500),]
# remove low precision records
quaternary_tbl = quaternary_tbl[which(abs(quaternary_tbl$delta_age)<10000),]
quaternary_tbl$name = gsub(' ','_',quaternary_tbl$name)
dim(quaternary_tbl)
quaternary_tbl$name
# lo_file = "/Users/danielesilvestro/Desktop/Tobi/data20180117/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils.txt"
lo_file = "/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils_fixed_typos.txt"
lo_tbl = read.csv(lo_file,h=F,stringsAsFactors=F,sep="\t")
colnames(lo_tbl) = c("species","max_age","min_age")
# REMOVE NAs = CHECK IF IT's OK!!
lo_tbl$min_age[which(is.na(lo_tbl$min_age))] = lo_tbl$max_age[which(is.na(lo_tbl$min_age))]
lo_tbl$max_age[which(is.na(lo_tbl$max_age))] = lo_tbl$min_age[which(is.na(lo_tbl$max_age))]
lo_tbl = cbind(lo_tbl,(lo_tbl$max_age+lo_tbl$min_age)/2)
colnames(lo_tbl) = c("species","max_age","min_age","age")
occs_data = NULL
occs_count = c()
time_span = c()
time_until_known_extinction = c()
species_with_time_until_known_extinction = c()
j=1
for (taxon in lo_tbl$species){
tax = gsub("_"," ",taxon)
G = grep(tax, quaternary_tbl$name,fixed=T)
count = length(G)
#print( c(tax, ))
occs_pbdb = quaternary_tbl$age[G]
comb_ages = sort(as.numeric(c(lo_tbl$age[j],occs_pbdb)))
ages = list(comb_ages)
occs_data[j] = ages
if (count>1){
print(comb_ages)
occs_count = c(occs_count,length(comb_ages))
time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
}
#if (min(comb_ages)<=500 & count>=1){
#	occs_count = c(occs_count,length(comb_ages))
#	time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
#	time_until_known_extinction = c(time_until_known_extinction, min(occs_pbdb)-lo_tbl$age[j] )
#	species_with_time_until_known_extinction = c(species_with_time_until_known_extinction, tax )
#}
j = j+1
}
occs_count
taxon
occs_count
tax = gsub("_"," ",taxon)
G = grep(tax, quaternary_tbl$name,fixed=T)
G
quaternary_tbl
quaternary_tbl$name
lo_tbl$species
quaternary_tbl$name
taxon
lo_tbl$species
taxon = 'Mammut_americanum'
subtbl= read.csv('/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/joined_databases_update_sahul.txt',sep = '\t')
subtbl$max_age = subtbl$max_age*1000000
subtbl$min_age = subtbl$min_age*1000000
subtbl$age = (subtbl$max_age+subtbl$min_age)/2
subtbl$delta_age = subtbl$max_age-subtbl$min_age
#quaternary_tbl = subtbl[which(subtbl$age<2580000),]
quaternary_tbl = subtbl[which(subtbl$age<781000),]
#quaternary_tbl = quaternary_tbl[which(quaternary_tbl$age>500),]
# remove low precision records
quaternary_tbl = quaternary_tbl[which(abs(quaternary_tbl$delta_age)<10000),]
#quaternary_tbl$name = gsub(' ','_',quaternary_tbl$name)
dim(quaternary_tbl)
# lo_file = "/Users/danielesilvestro/Desktop/Tobi/data20180117/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils.txt"
lo_file = "/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils_fixed_typos.txt"
lo_tbl = read.csv(lo_file,h=F,stringsAsFactors=F,sep="\t")
colnames(lo_tbl) = c("species","max_age","min_age")
# REMOVE NAs = CHECK IF IT's OK!!
lo_tbl$min_age[which(is.na(lo_tbl$min_age))] = lo_tbl$max_age[which(is.na(lo_tbl$min_age))]
lo_tbl$max_age[which(is.na(lo_tbl$max_age))] = lo_tbl$min_age[which(is.na(lo_tbl$max_age))]
lo_tbl = cbind(lo_tbl,(lo_tbl$max_age+lo_tbl$min_age)/2)
colnames(lo_tbl) = c("species","max_age","min_age","age")
occs_data = NULL
occs_count = c()
time_span = c()
time_until_known_extinction = c()
species_with_time_until_known_extinction = c()
j=1
for (taxon in lo_tbl$species){
tax = gsub("_"," ",taxon)
G = grep(tax, quaternary_tbl$name,fixed=T)
count = length(G)
#print( c(tax, ))
occs_pbdb = quaternary_tbl$age[G]
comb_ages = sort(as.numeric(c(lo_tbl$age[j],occs_pbdb)))
ages = list(comb_ages)
occs_data[j] = ages
if (count>1){
print(comb_ages)
occs_count = c(occs_count,length(comb_ages))
time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
}
#if (min(comb_ages)<=500 & count>=1){
#	occs_count = c(occs_count,length(comb_ages))
#	time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
#	time_until_known_extinction = c(time_until_known_extinction, min(occs_pbdb)-lo_tbl$age[j] )
#	species_with_time_until_known_extinction = c(species_with_time_until_known_extinction, tax )
#}
j = j+1
}
par(mfrow=c(1,2))
plot(log(occs_count/time_span)~log(occs_count),xlab="log n. occurrences",ylab = "log preservation rate")
abline(lm(log(occs_count/time_span)~log(occs_count)),col="red")
regression = lm(log(occs_count/time_span)~log(occs_count))
get_log_rate <- function(n_occs=1){
a = regression$coefficients[2]
b = regression$coefficients[1]
y = a*log(n_occs) + b
return(y)
}
plot(exp(get_log_rate(1:100)),type="l",xlab = "n. occurrences",ylab = "preservation rate")
occs_count
occs_data = NULL
occs_count = c()
time_span = c()
time_until_known_extinction = c()
species_with_data = c()
occs_per_species = c()
j=1
for (taxon in lo_tbl$species){
tax = gsub("_"," ",taxon)
G = grep(tax, quaternary_tbl$name,fixed=T)
count = length(G)
#print( c(tax, ))
occs_pbdb = quaternary_tbl$age[G]
comb_ages = sort(as.numeric(c(lo_tbl$age[j],occs_pbdb)))
ages = list(comb_ages)
occs_data[j] = ages
if (count>1){
print(comb_ages)
occs_count = c(occs_count,length(comb_ages))
time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
}
if (count >0){
species_with_data = c(species_with_data,tax)
occs_per_species = c(occs_per_species,count)
}
species_with_data
j = j+1
}
occs_data = NULL
occs_count = c()
time_span = c()
time_until_known_extinction = c()
species_with_data = c()
occs_per_species = c()
j=1
for (taxon in lo_tbl$species){
tax = gsub("_"," ",taxon)
G = grep(tax, quaternary_tbl$name,fixed=T)
count = length(G)
#print( c(tax, ))
occs_pbdb = quaternary_tbl$age[G]
comb_ages = sort(as.numeric(c(lo_tbl$age[j],occs_pbdb)))
ages = list(comb_ages)
occs_data[j] = ages
if (count>1){
print(comb_ages)
occs_count = c(occs_count,length(comb_ages))
time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
}
if (count >0){
species_with_data = c(species_with_data,tax)
occs_per_species = c(occs_per_species,count)
}
#if (min(comb_ages)<=500 & count>=1){
#	occs_count = c(occs_count,length(comb_ages))
#	time_span  = c(time_span ,max(comb_ages)-min(comb_ages))
#	time_until_known_extinction = c(time_until_known_extinction, min(occs_pbdb)-lo_tbl$age[j] )
#	species_with_time_until_known_extinction = c(species_with_time_until_known_extinction, tax )
#}
j = j+1
}
species_with_data
rbindlist(list(species_with_data, occs_per_species), use.names = TRUE, fill=TRUE)
library(data.table)
rbindlist(list(species_with_data, occs_per_species), use.names = TRUE, fill=TRUE)
occs_per_species
rbindlist(list(list(species_with_data), list(occs_per_species)), use.names = TRUE, fill=TRUE)
rbindlist(list(list(species_with_data), list(occs_per_species)), use.names = TRUE)
rbindlist(list(list(species_with_data), list(occs_per_species)))
DT = data.table(
species = species_with_data,
counts = occs_per_species
)
DT
species_with_presence_in_fossil_db = data.table(species = species_with_data,counts = occs_per_species)
species_with_presence_in_fossil_db = species_with_presence_in_fossil_db[order(species),]
species_with_presence_in_fossil_db
write.table(species_with_presence_in_fossil_db,file="/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/taxa_with_fossil_db_occurrences.txt",quote=F,sep="\t",row.names=F)
# replace 4th col with preservation rates (use old table without fixed typos to leave taxa names unchanged)
lo_file = "/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/extinct_taxa_with_lo_dates_from_fossils.txt"
occs_count
time_span
presrate_table = data.table(occs_count = occs_count,time_span = time_span)
presrate_table
presrate_info_table = data.table(occs_count = occs_count,time_span = time_span)
presrate_info_table = data.table(occs_count = occs_count,time_span = time_span)
write.table(presrate_info_table,file="/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/presrate_info_table",quote=F,sep="\t",row.names=F)
write.table(presrate_info_table,file="/Users/tobias/GitHub/mammal_extinction_old/data/processed/preservation_rates/estimate_preservation_rate/presrate_info_table.txt",quote=F,sep="\t",row.names=F)
