comparison GeoNN.R @ 2:24a81631a8b5 draft

planemo upload for repository https://github.com/galaxyecology/tools-ecology/tree/master/tools/Ecoregionalization_workflow commit 5d48df67919fbc9d77b98a8243d438c397f61a0e
author ecology
date Thu, 21 Mar 2024 14:04:36 +0000
parents
children
comparison
equal deleted inserted replaced
1:edb8d19735a6 2:24a81631a8b5
1 #Date : 09/02/2024
2 #Author : Seguineau Pauline
3
4 #Load libraries
5 library(tidyr)
6 library(dplyr)
7 library(sf)
8
9 #load arguments
10 args = commandArgs(trailingOnly=TRUE)
11 if (length(args)==0)
12 {
13 stop("This tool needs at least one argument")
14 }else{
15 enviro <- args[1]
16 envlong <- as.numeric(args[2])
17 envlat <- as.numeric(args[3])
18 occu <- args[4]
19 occulat <- as.numeric(args[5])
20 occulong <- as.numeric(args[6])
21 }
22
23 env = read.table(enviro, header = TRUE, sep="\t")
24 occ = read.table(occu, header = TRUE, sep = "\t")
25
26 cols_env = c(names(env[envlong]),names(env[envlat]))
27 cols_occ = c(names(occ[occulong]),names(occ[occulat]))
28
29 ###calculate distances###
30 #transform tables into sf object
31
32 env_sf <- st_as_sf(env, coords = cols_env, crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
33 occ_sf <- st_as_sf(occ, coords = cols_occ, crs = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
34
35 #Find the indices of env_sf entities closest to each point in occ_sf.
36
37 nearest_indices <- st_nearest_feature(occ_sf, env_sf)
38
39 nearest_points <- env[nearest_indices, ]
40
41 # Calculate distances between env_sf and occ_sf points
42 distances <- st_distance(env_sf, occ_sf)
43
44 #Extract the corresponding distances between occ and env
45
46 nearest_distances <- numeric(length(nearest_indices))
47
48 for (i in 1:length(nearest_indices)) {
49 nearest_distances[i] <- st_distance(env_sf[nearest_indices[i],], occ_sf[i,])
50 }
51
52 #assemble occurrences and environmental parameters in the same file
53
54 nearest_points <- nearest_points[, !names(nearest_points) %in% cols_env] #remove lat and long from env to clean data
55 new_occ = cbind(occ, nearest_points)
56
57 #Save the file
58
59 write.table(new_occ, file = "occurrence_env.tsv",sep ="\t",quote = F, row.names = F,col.names = T)
60
61 #create an information file with the distances between the points of the two files
62
63 distance_info <- data.frame(
64 occ_geometry = occ_sf$geometry,
65 env_geometry = env_sf$geometry[nearest_indices],
66 distance = nearest_distances
67 )
68
69 colnames(distance_info)[1] <- "occ_geometry"
70 colnames(distance_info)[2] <- "env_geometry"
71 colnames(distance_info)[3] <- "Distances (meters)"
72 #save the information file
73
74 write.table(distance_info, file = "infos_file.tsv",sep ="\t",quote = F, row.names = F,col.names = T)
75
76
77