-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinterface.R
1630 lines (1415 loc) Β· 62 KB
/
interface.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Define a population
#'
#' Defines the parameters of a population (non-spatial and spatial).
#'
#' There are four ways to specify a spatial boundary: i) circular range
#' specified using a center coordinate and a radius, ii) polygon specified as a
#' list of two-dimensional vector coordinates, iii) polygon as in ii), but
#' defined (and named) using the \code{region} function, iv) with just a world
#' map specified (circular or polygon range parameters set to the default
#' \code{NULL} value), the population will be allowed to occupy the entire
#' landscape.
#'
#' Note that because slendr models have to accomodate both SLiM and msprime
#' back ends, population sizes and split times are rounded to the nearest
#' integer value.
#'
#' @param name Name of the population
#' @param time Time of the population's first appearance
#' @param N Number of individuals at the time of first appearance
#' @param parent Parent population object or \code{NULL} (which indicates that
#' the population does not have an ancestor, as it is the first population
#' in its "lineage")
#' @param map Object of the type \code{slendr_map} which defines the world
#' context (created using the \code{world} function). If the value
#' \code{FALSE} is provided, a non-spatial model will be run.
#' @param center Two-dimensional vector specifying the center of the circular
#' range
#' @param radius Radius of the circular range
#' @param polygon List of vector pairs, defining corners of the polygon range or
#' a geographic region of the class \code{slendr_region} from which the
#' polygon coordinates will be extracted (see the \code{region() function})
#' @param remove Time at which the population should be removed
#' @param intersect Intersect the population's boundaries with landscape
#' features?
#' @param competition,mating Maximum spatial competition and mating
#' choice distance
#' @param dispersal Standard deviation of the normal distribution of the
#' distance that offspring disperses from its parent
#' @param dispersal_fun Distribution function governing the dispersal of
#' offspring. One of "normal", "uniform", "cauchy", "exponential", or
#' "brownian" (in which vertical and horizontal displacements are drawn from a
#' normal distribution independently).
#' @param aquatic Is the species aquatic (\code{FALSE} by default, i.e.
#' terrestrial species)?
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
population <- function(name, time, N, parent = NULL, map = FALSE,
center = NULL, radius = NULL, polygon = NULL,
remove = NULL, intersect = TRUE,
competition = NA, mating = NA, dispersal = NA,
dispersal_fun = NULL, aquatic = FALSE) {
if (!is.character(name) ||
length(name) != 1 ||
!grepl("^(?:[_\\p{L}\\p{Nl}])(?:[_\\p{L}\\p{Nl}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Pc}])*$",
name, perl = TRUE))
stop("A population name must be a character scalar value which must also be\n",
"valid Python identifiers (a restriction of the msprime simulation engine)", call. = FALSE)
N <- as.integer(round(N))
time <- as.integer(round(time))
if (time < 1) stop("Split time must be a non-negative number", call. = FALSE)
if (N < 1) stop("Population size must be a non-negative number", call. = FALSE)
# if this population splits from a parental population, check that the parent
# really exists and that the split time make sense given the time of appearance
# of the parental population
if (!is.null(parent)) {
if (!inherits(parent, "slendr_pop"))
stop("Only slendr_pop objects can represent parental populations", call. = FALSE)
else
check_split_time(time, parent)
}
parent_remove <- attr(parent, "remove")
if (!is.null(parent) && parent_remove != -1) {
direction <- if (time > parent$time[1]) "forward" else "backward"
if (direction == "forward" && parent_remove <= time)
stop("Parent population will be removed before the split event", call. = FALSE)
else if (direction == "backward" && parent_remove >= time)
stop("Parent population will be removed before the split event", call. = FALSE)
}
if (!is.logical(map) && !inherits(map, "slendr_map"))
stop("A simulation landscape must be an object of the class slendr_map", call. = FALSE)
if (!is.null(parent) && is.logical(map) && map == FALSE)
map <- attr(parent, "map")
if (inherits(map, "slendr_map")) {
check_spatial_pkgs()
# define the population range as a simple geometry object
# and bind it with the annotation info into an sf object
if (is.null(polygon) && is.null(center) && is.null(radius)) {
geometry <- sf::st_geometry(map)
} else if (!is.null(polygon) & inherits(polygon, "slendr_region"))
geometry <- sf::st_geometry(polygon)
else
geometry <- define_boundary(map, center, radius, polygon)
pop <- sf::st_sf(
data.frame(pop = name, time = time, stringsAsFactors = FALSE),
geometry = geometry
)
sf::st_agr(pop) <- "constant"
attr(pop, "intersect") <- intersect
attr(pop, "aquatic") <- aquatic
} else
pop <- list(pop = name, time = time)
# when to clean up the population?
attr(pop, "remove") <- if (!is.null(remove)) remove else -1
# keep a record of the parent population
if (inherits(parent, "slendr_pop"))
attr(pop, "parent") <- parent
else if (is.null(parent))
attr(pop, "parent") <- "__pop_is_ancestor"
else
stop("Suspicious parent population", call. = FALSE)
attr(pop, "map") <- map
dispersal_fun <- kernel_fun(dispersal_fun)
# create the first population history event - population split
attr(pop, "history") <- list(data.frame(
pop = name,
event = "split",
time = time,
N = N,
competition = competition,
mating = mating,
dispersal = dispersal,
dispersal_fun = dispersal_fun
))
class(pop) <- set_class(pop, "pop")
if (!is.logical(map) && intersect && (nrow(intersect_features(pop)) == 0))
stop("The specified population boundary has no overlap with liveable landscape surface",
call. = FALSE)
pop
}
#' Move the population to a new location in a given amount of time
#'
#' This function defines a displacement of a population along a given trajectory
#' in a given time frame
#'
#' @param pop Object of the class \code{slendr_pop}
#' @param trajectory List of two-dimensional vectors (longitude, latitude)
#' specifying the migration trajectory
#' @param start,end Start/end points of the population migration
#' @param overlap Minimum overlap between subsequent spatial boundaries
#' @param snapshots The number of intermediate snapshots (overrides the
#' \code{overlap} parameter)
#' @param verbose Show the progress of searching through the number of
#' sufficient snapshots?
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
move <- function(pop, trajectory, end, start, overlap = 0.8, snapshots = NULL,
verbose = TRUE) {
if (!has_map(pop)) stop("This operation is only allowed for spatial models", call. = FALSE)
check_spatial_pkgs()
check_event_time(c(start, end), pop)
check_removal_time(start, pop)
check_removal_time(end, pop)
if (!is.null(snapshots))
if (snapshots <= 0)
stop("The number of snapshots must be a non-negative integer", call. = FALSE)
if (!(overlap > 0 & overlap < 1))
stop("The required overlap between subsequent spatial maps must be a number between 0 and 1",
call. = FALSE)
map <- attr(pop, "map")
# take care of just a single destination point being specified
if (!is.list(trajectory) & length(trajectory) == 2)
trajectory <- list(trajectory)
# get the last available population boundary
region_start <- pop[nrow(pop), ]
region_start$time <- start
sf::st_agr(region_start) <- "constant"
# prepend the coordinates of the first region to the list of "checkpoints"
# along the way of the movement
start_coords <- sf::st_centroid(region_start)
if (has_crs(map)) {
source_crs <- "EPSG:4326"
target_crs <- sf::st_crs(pop)
start_coords <- sf::st_transform(start_coords, crs = source_crs)
}
start_coords <- sf::st_coordinates(start_coords)
checkpoints <- c(list(as.vector(start_coords)), trajectory)
traj <- sf::st_linestring(do.call(rbind, checkpoints)) %>% sf::st_sfc()
if (has_crs(map)) {
traj <- sf::st_sf(traj, crs = source_crs) %>%
sf::st_transform(crs = target_crs)
} else {
traj <- sf::st_sf(traj)
}
if (is.null(snapshots)) {
n <- 1
message("Iterative search for the minimum sufficient number of intermediate ",
"spatial snapshots, starting at ", n, ". This should only take a couple of ",
"seconds, but if you don't want to wait, you can set `snapshots = N` manually.")
} else
n <- snapshots
# iterate through the number of intermediate spatial boundaries to reach
# the required overlap between subsequent spatial maps
repeat {
traj_segments <- sf::st_segmentize(traj, sf::st_length(traj) / n)
traj_points <- sf::st_cast(traj_segments, "POINT")
traj_points_coords <- sf::st_coordinates(traj_points)
traj_diffs <- diff(traj_points_coords)
time_slices <- seq(start, end, length.out = nrow(traj_points))[-1]
traj_diffs <- cbind(traj_diffs, time = time_slices)
inter_regions <- list()
inter_regions[[1]] <- region_start
for (i in seq_len(nrow(traj_diffs))) {
shifted_region <- sf::st_geometry(inter_regions[[i]]) + traj_diffs[i, c("X", "Y")]
inter_regions[[i + 1]] <- sf::st_sf(
data.frame(
pop = region_start$pop,
time = traj_diffs[i, "time"],
stringsAsFactors = FALSE
),
geometry = shifted_region,
crs = sf::st_crs(inter_regions[[i]])
)
sf::st_agr(inter_regions[[i + 1]]) <- "constant"
}
if (!is.null(snapshots)) break
# calculate the overlap between subsequent spatial snapshots
overlaps <- compute_overlaps(do.call(rbind, inter_regions))
if (all(overlaps >= overlap)) {
message("The required ", sprintf("%.1f%%", 100 * overlap),
" overlap between subsequent spatial maps has been met")
break
} else {
n <- n + 1
if (verbose)
message("- testing ", n, " snapshots")
}
}
inter_regions <- rbind(pop, do.call(rbind, inter_regions))
sf::st_agr(inter_regions) <- "constant"
result <- copy_attributes(
inter_regions, pop,
c("map", "parent", "remove", "intersect", "aquatic", "history")
)
attr(result, "history") <- append(attr(result, "history"), list(data.frame(
pop = unique(region_start$pop),
event = "move",
tstart = start,
tend = end
)))
result
}
#' Expand the population range
#'
#' Expands the spatial population range by a specified distance in a given
#' time-window
#'
#' Note that because slendr models have to accomodate both SLiM and msprime
#' back ends, population sizes and times of events are rounded to the nearest
#' integer value.
#'
#' @param pop Object of the class \code{slendr_pop}
#' @param by How many units of distance to expand by?
#' @param start,end When does the expansion start/end?
#' @param overlap Minimum overlap between subsequent spatial boundaries
#' @param snapshots The number of intermediate snapshots (overrides the
#' \code{overlap} parameter)
#' @param polygon Geographic region to restrict the expansion to
#' @param lock Maintain the same density of individuals. If
#' \code{FALSE} (the default), the number of individuals in the
#' population will not change. If \code{TRUE}, the number of
#' individuals simulated will be changed (increased or decreased)
#' appropriately, to match the new population range area.
#' @param verbose Report on the progress of generating intermediate spatial
#' boundaries?
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
expand_range <- function(pop, by, end, start, overlap = 0.8, snapshots = NULL,
polygon = NULL, lock = FALSE, verbose = TRUE) {
if (!has_map(pop)) stop("This operation is only allowed for spatial models", call. = FALSE)
check_spatial_pkgs()
start <- as.integer(round(start))
end <- as.integer(round(end))
shrink_or_expand(pop, by, end, start, overlap, snapshots, polygon, lock, verbose)
}
#' Shrink the population range
#'
#' Shrinks the spatial population range by a specified distance in a given
#' time-window
#'
#' Note that because slendr models have to accomodate both SLiM and msprime
#' back ends, population sizes and split times are rounded to the nearest
#' integer value.
#'
#' @param pop Object of the class \code{slendr_pop}
#' @param by How many units of distance to shrink by?
#' @param start,end When does the boundary shrinking start/end?
#' @param overlap Minimum overlap between subsequent spatial boundaries
#' @param snapshots The number of intermediate snapshots (overrides the
#' \code{overlap} parameter)
#' @param lock Maintain the same density of individuals. If
#' \code{FALSE} (the default), the number of individuals in the
#' population will not change. If \code{TRUE}, the number of
#' individuals simulated will be changed (increased or decreased)
#' appropriately, to match the new population range area.
#' @param verbose Report on the progress of generating intermediate spatial
#' boundaries?
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
shrink_range <- function(pop, by, end, start, overlap = 0.8, snapshots = NULL,
lock = FALSE, verbose = TRUE) {
if (!has_map(pop)) stop("This operation is only allowed for spatial models", call. = FALSE)
check_spatial_pkgs()
shrink_or_expand(pop, -by, end, start, overlap, snapshots, polygon = NULL, lock, verbose)
}
#' Update the population range
#'
#' This function allows a more manual control of spatial map changes
#' in addition to the \code{expand} and \code{move} functions
#'
#' @param pop Object of the class \code{slendr_pop}
#' @param time Time of the change
#' @param center Two-dimensional vector specifying the center of the
#' circular range
#' @param radius Radius of the circular range
#' @param polygon List of vector pairs, defining corners of the
#' polygon range (see also the \code{region} argument) or a
#' geographic region of the class \code{slendr_region} from which
#' the polygon coordinates will be extracted
#' @param lock Maintain the same density of individuals. If
#' \code{FALSE} (the default), the number of individuals in the
#' population will not change. If \code{TRUE}, the number of
#' individuals simulated will be changed (increased or decreased)
#' appropriately, to match the new population range area.
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
set_range <- function(pop, time, center = NULL, radius = NULL,
polygon = NULL, lock = FALSE) {
if (!has_map(pop)) stop("This operation is only allowed for spatial models", call. = FALSE)
check_spatial_pkgs()
check_event_time(time, pop)
check_removal_time(time, pop)
map <- attr(pop, "map")
# define the population range as a simple geometry object
# and bind it with the annotation info into an sf object
if (!is.null(polygon) & inherits(polygon, "slendr_region"))
geometry <- sf::st_geometry(polygon)
else
geometry <- define_boundary(map, center, radius, polygon)
updated <- sf::st_sf(
data.frame(pop = unique(pop$pop), time = time, stringsAsFactors = FALSE),
geometry = geometry
)
# Let's not enforce this given that the point of this function is to allow
# full manual control over the boundary dynamics:
# if (compute_overlaps(rbind(updated, pop[nrow(pop), ])) < overlap)
# stop("Insufficient overlap with the last active spatial boundary (",
# "please adjust the new spatial boundary or adjust the `overlap = `",
# "parameter for less stringent checking)", call. = FALSE)
combined <- rbind(pop, updated)
sf::st_agr(combined) <- "constant"
result <- copy_attributes(
combined, pop,
c("map", "parent", "remove", "intersect", "aquatic", "history")
)
attr(result, "history") <- append(attr(result, "history"), list(data.frame(
event = "range",
time = time
)))
if (lock) {
areas <- slendr::area(result)$area
area_change <- areas[length(areas)] / areas[length(areas) - 1]
prev_N <- utils::tail(sapply(attributes(pop)$history, function(event) event$N), 1)
new_N <- round(area_change * prev_N)
result <- resize(result, N = new_N, time = time, how = "step")
}
result
}
#' Change the population size
#'
#' Resizes the population starting from the current value of \code{N}
#' individuals to the specified value
#'
#' In the case of exponential size change, if the final \code{N} is larger than
#' the current size, the population will be exponentially growing over the
#' specified time period until it reaches \code{N} individuals. If \code{N} is
#' smaller, the population will shrink exponentially.
#'
#' Note that because slendr models have to accomodate both SLiM and msprime
#' back ends, population sizes and split times are rounded to the nearest
#' integer value.
#'
#' @param pop Object of the class \code{slendr_pop}
#' @param N Population size after the change
#' @param how How to change the population size (options are \code{"step"} or
#' \code{"exponential"})
#' @param time Time of the population size change
#' @param end End of the population size change period (used for exponential
#' change events)
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
resize <- function(pop, N, how, time, end = NULL) {
if (N < 1) stop("resize(): Only positive, non-zero population sizes are allowed", call. = FALSE)
N <- as.integer(round(N))
time <- as.integer(round(time))
if (!is.null(end)) end <- as.integer(round(end))
if (time == attr(pop, "history")[[1]]$time)
stop("Population resize cannot happen at the time the population is created", call. = FALSE)
if (!how %in% c("step", "exponential"))
stop("resize(): Only 'step' or 'exponential' are allowed as arguments for the 'how' parameter", call. = FALSE)
if (how == "exponential" & is.null(end))
stop("resize(): Start-end period of the exponential growth must be specified", call. = FALSE)
# get the last active population size
prev_N <- sapply(attr(pop, "history"), function(event) event$N) %>%
Filter(Negate(is.null), .) %>%
unlist %>%
utils::tail(1)
change <- data.frame(
pop = unique(pop$pop),
event = "resize",
how = how,
N = N,
prev_N = prev_N,
tresize = time
)
if (how == "step") {
check_event_time(time, pop)
check_removal_time(time, pop)
change$tend <- NA
} else {
check_event_time(c(time, end), pop)
check_removal_time(time, pop)
check_removal_time(end, pop)
change$tend <- end
}
attr(pop, "history") <- append(attr(pop, "history"), list(change))
pop
}
#' Change dispersal parameters
#'
#' Changes either the competition interactive distance, mating choice distance,
#' or the dispersal of offspring from its parent
#'
#' @param pop Object of the class \code{slendr_pop}
#' @param time Time of the population size change
#' @param competition,mating Maximum spatial competition and mating
#' choice distance
#' @param dispersal Standard deviation of the normal distribution of the
#' distance that offspring disperses from its parent
#' @param dispersal_fun Distribution function governing the dispersal of
#' offspring. One of "normal", "uniform", "cauchy", "exponential", or
#' "brownian" (in which vertical and horizontal displacements are drawn from a
#' normal distribution independently).
#'
#' @return Object of the class \code{slendr_pop}, which contains population
#' parameters such as name, time of appearance in the simulation, parent
#' population (if any), and its spatial parameters such as map and spatial
#' boundary.
#'
#' @export
#'
#' @example man/examples/model_definition.R
set_dispersal <- function(pop, time, competition = NA, mating = NA, dispersal = NA,
dispersal_fun = NULL) {
if (!has_map(pop)) stop("This operation is only allowed for spatial models", call. = FALSE)
check_spatial_pkgs()
if (is.na(competition) && is.na(mating) && is.na(dispersal) &&
is.null(dispersal_fun))
stop("At least one spatial interaction parameter must be specified", call. = FALSE)
if (any(c(competition, mating, dispersal) < 0, na.rm = TRUE))
stop("Spatial interaction parameters can only have positive, non-zero values", call. = FALSE)
dispersal_fun <- kernel_fun(dispersal_fun)
map <- attr(pop, "map")
if (!is.na(competition)) check_resolution(map, competition)
if (!is.na(mating)) check_resolution(map, mating)
if (!is.na(dispersal)) check_resolution(map, dispersal)
check_event_time(time, pop)
check_removal_time(time, pop)
change <- data.frame(
pop = unique(pop$pop),
event = "dispersal",
time = time,
competition = competition,
mating = mating,
dispersal = dispersal,
dispersal_fun = dispersal_fun
)
attr(pop, "history") <- append(attr(pop, "history"), list(change))
pop
}
#' Define a gene-flow event between two populations
#'
#' @param from,to Objects of the class \code{slendr_pop}
#' @param rate Scalar value in the range (0, 1] specifying the
#' proportion of migration over given time period
#' @param start,end Start and end of the gene-flow event
#' @param overlap Require spatial overlap between admixing
#' populations? (default \code{TRUE})
#'
#' @return Object of the class data.frame containing parameters of the specified
#' gene-flow event.
#'
#' @export
#'
#' @example man/examples/model_definition.R
gene_flow <- function(from, to, rate, start, end, overlap = TRUE) {
if (!inherits(from, "slendr_pop") || !inherits(to, "slendr_pop"))
stop("Both 'from' and 'to' arguments must be slendr population objects",
call. = FALSE)
# TODO: this needs some serious restructuring -- this function originated when slendr
# could only do spatial simulations and some consistency checks relied on spatial
# attributes; as a result, some checks are overlapping and/or redundant
if ((has_map(from) && !has_map(to)) || (!has_map(from) && has_map(to)))
stop("Both or neither populations must be spatial", call. = FALSE)
# make sure that gene flow has a sensible value between 0 and 1
if (rate < 0 || rate > 1)
stop("Gene-flow rate must be a numeric value between 0 and 1", call. = FALSE)
from_name <- unique(from$pop)
to_name <- unique(to$pop)
if (start == end)
stop(sprintf("Start and end time for the %s -> %s gene flow is the same (%s)",
from_name, to_name, start), call. = FALSE)
gf_dir <- if (start < end) "forward" else "backward"
from_dir <- time_direction(from)
to_dir <- time_direction(to)
direction <- unique(setdiff(c(gf_dir, from_dir, to_dir), "unknown"))
if (length(direction) > 1)
stop("Inconsistent time direction implied by populations and the gene flow event", call. = FALSE)
# make sure both participating populations are present at the start of the
# gene flow event (`check_present_time()` is reused from the sampling functionality)
tryCatch(
{
check_present_time(start, from, offset = 0, direction = direction)
check_present_time(end, from, offset = 0, direction = direction)
check_present_time(start, to, offset = 0, direction = direction)
check_present_time(end, to, offset = 0, direction = direction)
check_removal_time(start, from)
check_removal_time(end, from)
check_removal_time(start, to)
check_removal_time(end, to)
},
error = function(e) {
stop(sprintf("Both %s and %s must be already present within the gene-flow window %s-%s",
from_name, to_name, start, end), call. = FALSE)
}
)
if (has_map(from) && has_map(to)) {
comp <- if (direction == "forward") `<=` else `>=`
# get the last specified spatial maps before the geneflow time
region_from <- intersect_features(from[comp(from$time, start), ] %>% .[nrow(.), ])
region_to <- intersect_features(to[comp(to$time, start), ] %>% .[nrow(.), ])
if (nrow(region_from) == 0)
stop(sprintf("No spatial map defined for %s at/before the time %d",
from_name, start),
call. = FALSE)
if (nrow(region_to) == 0)
stop(sprintf("No spatial map defined for %s at/before the time %d",
to_name, start),
call. = FALSE)
# calculate the overlap of spatial ranges between source and target
region_overlap <- sf::st_intersection(region_from, region_to)
area_overlap <- as.numeric(sum(sf::st_area(region_overlap)))
if (overlap && area_overlap == 0) {
stop(sprintf("No overlap between population ranges of %s and %s at time %d.
Please check the spatial maps of both populations by running
`plot_map(%s, %s)` and adjust them accordingly. Alternatively, in case
this makes sense for your model, you can add `overlap = F` which
will instruct slendr to simulate gene flow without spatial overlap
between populations.",
from_name, to_name, start, deparse(base::substitute(from)),
deparse(base::substitute(to))), call. = FALSE)
}
} else
overlap <- FALSE
data.frame(
from_name = from_name,
to_name = to_name,
tstart = start,
tend = end,
rate = rate,
overlap = overlap,
stringsAsFactors = FALSE
)
}
#' Define a world map for all spatial operations
#'
#' Defines either an abstract geographic landscape (blank or containing
#' user-defined landscape) or using a real Earth cartographic data from the
#' Natural Earth project (<https://www.naturalearthdata.com>).
#'
#' @param xrange Two-dimensional vector specifying minimum and maximum
#' horizontal range ("longitude" if using real Earth cartographic data)
#' @param yrange Two-dimensional vector specifying minimum and maximum vertical
#' range ("latitude" if using real Earth cartographic data)
#' @param landscape Either "blank" (for blank abstract geography),
#' "naturalearth" (for real Earth geography) or an object of the class
#' \code{sf} defining abstract geographic features of the world
#' @param crs EPSG code of a coordinate reference system to use for spatial
#' operations. No CRS is assumed by default (\code{NULL}), implying an
#' abstract landscape not tied to any real-world geographic region (when
#' \code{landscape = "blank"} or when \code{landscape} is a custom-defined
#' geographic landscape), or implying WGS-84 (EPSG 4326) coordinate system
#' when a real Earth landscape was defined (\code{landscape =
#' "naturalearth"}).
#' @param scale If Natural Earth geographic data is used (i.e. \code{landscape =
#' "naturalearth"}), this parameter determines the resolution of the data
#' used. The value "small" corresponds to 1:110m data and is provided with the
#' package, values "medium" and "large" correspond to 1:50m and 1:10m
#' respectively and will be downloaded from the internet. Default value is
#' "small".
#'
#' @return Object of the class \code{slendr_map}, which encodes a standard
#' spatial object of the class \code{sf} with additional slendr-specific
#' attributes such as requested x-range and y-range.
#'
#' @export
#'
#' @example man/examples/spatial_functions.R
world <- function(xrange, yrange, landscape = "naturalearth", crs = NULL,
scale = c("small", "medium", "large")) {
check_spatial_pkgs()
if (length(xrange) != 2 || length(yrange) != 2)
stop("Horizontal (i.e. longitude) and vertical (i.e. latitude) must be\n",
"specified as two-dimensional vectors such as:\n",
" `xrange = c(x1, x2), yrange = c(y1, y2)`",
call. = FALSE)
if (is.character(landscape) && landscape == "naturalearth" && is.null(crs)) {
warning("No explicit coordinate reference system (CRS) was specified.\n",
"A default geographic CRS (EPSG:4326) will be used but please make\n",
"sure this is appropriate for your geographic region of interest.",
call. = FALSE)
crs <- 4326
}
if (inherits(landscape, "sf")) { # a landscape defined by the user
cropped_landscape <- sf::st_crop(
landscape,
xmin = xrange[1], xmax = xrange[2],
ymin = yrange[1], ymax = yrange[2]
)
map <- sf::st_sf(landscape = sf::st_geometry(cropped_landscape)) %>%
set_bbox(xmin = xrange[1], xmax = xrange[2], ymin = yrange[1], ymax = yrange[2])
} else if (landscape == "blank") { # an empty abstract landscape
map <- sf::st_sf(geometry = sf::st_sfc()) %>%
set_bbox(xmin = xrange[1], xmax = xrange[2], ymin = yrange[1], ymax = yrange[2])
} else if (landscape == "naturalearth") { # Natural Earth data vector landscape
scale <- match.arg(scale)
# the small scale Natural Earth data is bundled with slendr
ne_dir <- file.path(tempdir(), "naturalearth")
if (scale == "small") {
utils::unzip(system.file("naturalearth/ne_110m_land.zip", package = "slendr"),
exdir = ne_dir)
} else {
size <- ifelse(scale == "large", 10, 50)
file <- sprintf("ne_%sm_land.zip", size)
if (!dir.exists(ne_dir)) dir.create(ne_dir)
path <- file.path(ne_dir, file)
utils::download.file(
url = sprintf("https://naturalearth.s3.amazonaws.com/%sm_physical/%s", size, file),
destfile = path, quiet = TRUE
)
utils::unzip(path, exdir = ne_dir)
}
# TODO: this function uses internally rgdal, which is to be retired by 2023
# silence the deprecation warning for now, as it would only confuse the user
# and figure out a way to deal with this (either by providing a PR to the devs
# or hacking our own alternative)
suppressWarnings(
map_raw <- rnaturalearth::ne_load(
scale = scale, type = "land", category = "physical",
returnclass = "sf", destdir = ne_dir
)
)
sf::st_agr(map_raw) <- "constant"
# define boundary coordinates in the target CRS
crop_bounds <- define_zoom(xrange, yrange, "EPSG:4326")
# crop the map to the boundary coordinates
map_cropped <- tryCatch({
sf::st_crop(sf::st_make_valid(map_raw), crop_bounds)
}, error = function(cond) {
sf::st_crop(map_raw, crop_bounds)
})
# transform the map into the target CRS if needed
map <- sf::st_transform(map_cropped, crs)
} else {
stop("Landscape has to be either 'blank', 'naturalearth' or an object of the class 'sf'",
call. = FALSE)
}
sf::st_agr(map) <- "constant"
class(map) <- set_class(map, "map")
attr(map, "xrange") <- xrange
attr(map, "yrange") <- yrange
map
}
#' Define a geographic region
#'
#' Creates a geographic region (a polygon) on a given map and gives it
#' a name. This can be used to define objects which can be reused in
#' multiple places in a slendr script (such as \code{region} arguments
#' of \code{population}) without having to repeatedly define polygon
#' coordinates.
#'
#' @param name Name of the geographic region
#' @param map Object of the type \code{sf} which defines the map
#' @param center Two-dimensional vector specifying the center of the
#' circular range
#' @param radius Radius of the circular range
#' @param polygon List of vector pairs, defining corners of the
#' polygon range or a geographic region of the class
#' \code{slendr_region} from which the polygon coordinates will be
#' extracted (see the \code{region() function})
#'
#' @return Object of the class \code{slendr_region} which encodes a standard
#' spatial object of the class \code{sf} with several additional attributes
#' (most importantly a corresponding \code{slendr_map} object, if applicable).
#'
#' @export
#'
#' @example man/examples/spatial_functions.R
region <- function(name = NULL, map = NULL, center = NULL, radius = NULL, polygon = NULL) {
check_spatial_pkgs()
# for accurate circular areas see: https://stackoverflow.com/a/65280376
if (is.null(name)) name <- "unnamed region"
region <- sf::st_sf(
region = name,
geometry = define_boundary(map, center, radius, polygon)
) %>% sf::st_make_valid()
sf::st_agr(region) <- "constant"
# keep the map as an internal attribute
attr(region, "map") <- map
class(region) <- set_class(region, "region")
region
}
#' Reproject coordinates between coordinate systems
#'
#' Converts between coordinates on a compiled raster map (i.e. pixel
#' units) and different Geographic Coordinate Systems (CRS).
#'
#' @param x,y Coordinates in two dimensions (if missing, coordinates
#' are expected to be in the \code{data.frame} specified in the
#' \code{coords} parameter as columns "x" and "y")
#' @param from,to Either a CRS code accepted by GDAL, a valid integer
#' EPSG value, an object of class \code{crs}, the value "raster"
#' (converting from/to pixel coordinates), or "world" (converting
#' from/to whatever CRS is set for the underlying map)
#' @param coords data.frame-like object with coordinates in columns
#' "x" and "y"
#' @param model Object of the class \code{slendr_model}
#' @param add Add column coordinates to the input data.frame
#' \code{coords} (coordinates otherwise returned as a separate
#' object)?
#' @param input_prefix,output_prefix Input and output prefixes of data
#' frame columns with spatial coordinates
#'
#' @return Data.frame with converted two-dimensional coordinates given as input
#'
#' @examples
#' lon_lat_df <- data.frame(x = c(30, 0, 15), y = c(60, 40, 10))
#'
#' reproject(
#' from = "epsg:4326",
#' to = "epsg:3035",
#' coords = lon_lat_df,
#' add = TRUE # add converted [lon,lat] coordinates as a new column
#' )
#' @export
reproject <- function(from, to, x = NULL, y = NULL, coords = NULL, model = NULL,
add = FALSE, input_prefix = "", output_prefix = "new") {
check_spatial_pkgs()
if ((is.null(x) | is.null(y)) & is.null(coords))
stop("Coordinates for conversion are missing", call. = FALSE)
from_slendr <- !is.null(model)
if ((from == "raster" | to == "raster") & !from_slendr)
stop("Model object needs to be specified for conversion of raster coordinates", call. = FALSE)
if (add && is.null(coords))
stop("Converted coordinates can only be added to a provided data.frame", call. = FALSE)
inx <- paste0(input_prefix, "x"); iny <- paste0(input_prefix, "y")
outx <- paste0(output_prefix, "x"); outy <- paste0(output_prefix, "y")
if (!is.null(coords) & !all(c(inx, iny) %in% colnames(coords)))
stop("Columns '", inx, "' and '", iny, "' must be present in the input data.frame", call. = FALSE)
if (from_slendr) {
# dimension of the map in the projected CRS units
bbox <- sf::st_bbox(model$world)
map_dim <- c(bbox["xmax"] - bbox["xmin"], bbox["ymax"] - bbox["ymin"])
# dimension of the rasterized map in pixel units
# (x/y dimensions of PNGs are reversed)
raster_dim <- dim(png::readPNG(file.path(model$path, model$maps$path[1])))[2:1]
}
if (to == "world") to <- sf::st_crs(model$world)
if (from == "world" && has_crs(model$world)) from <- sf::st_crs(model$world)
if (is.null(coords)) {
df <- data.frame(x = x, y = y)
colnames(df) <- c(inx, iny)
} else
df <- coords[, c(inx, iny)]
if (from == "raster") {
# convert pixel coordinates to na sf object in world-based coordinates
df[[inx]] <- bbox["xmin"] + map_dim[1] * df[[inx]] / raster_dim[1]
df[[iny]] <- bbox["ymin"] + map_dim[2] * df[[iny]] / raster_dim[2]
point <- sf::st_as_sf(df, coords = c(inx, iny), crs = sf::st_crs(model$world))
} else {
# ... otherwise create a formal sf point object from the
# coordinates already given
point <- sf::st_as_sf(df, coords = c(inx, iny), crs = from)
}
if (to == "raster") {
if (has_crs(model$world))
point<- sf::st_transform(point, crs = sf::st_crs(model$world))
point_coords <- sf::st_coordinates(point)
newx <- abs((point_coords[, "X"] - bbox["xmin"])) / map_dim[1] * raster_dim[1]
newy <- abs((point_coords[, "Y"] - bbox["ymin"])) / map_dim[2] * raster_dim[2]
new_point <- data.frame(newx = round(as.vector(newx)), newy = round(as.vector(newy)))
colnames(new_point) <- c(outx, outy)
} else if (!is.na(to)) {
new_point <- sf::st_transform(point, crs = to) %>% sf::st_coordinates()
colnames(new_point) <- c(outx, outy)
} else {
new_point <- point %>% sf::st_coordinates()
colnames(new_point) <- c(outx, outy)
}
# if (nrow(new_point) == 1)
# return(as.vector(unlist(new_point)))
if (add) new_point <- cbind(coords, new_point) %>% dplyr::as_tibble()
new_point
}
#' Merge two spatial \code{slendr} objects into one
#'
#' @param x Object of the class \code{slendr}
#' @param y Object of the class \code{slendr}
#' @param name Optional name of the resulting geographic region. If missing,