-
Notifications
You must be signed in to change notification settings - Fork 4
/
internal-make_ipm.R
1675 lines (1108 loc) · 44.1 KB
/
internal-make_ipm.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
# make_ipm internal helpers
#' @noRd
.make_sub_kernel_general <- function(proto, env_list, return_envs = FALSE) {
out <- list()
main_env <- env_list$main_env
for(i in seq_len(dim(proto)[1])) {
if(proto$evict[i]) {
proto[i, ] <- .correct_eviction(proto[i, ])
}
param_tree <- proto$params[[i]]
kern_env <- .make_kernel_env(param_tree$params,
main_env,
proto[i, ])
kern_text <- param_tree$formula
kern_form <- .parse_vr_formulae(kern_text,
kern_env,
proto[i, ],
main_env)
names(kern_form) <- proto$kernel_id[i]
rlang::env_bind_lazy(kern_env,
!!! kern_form,
.eval_env = kern_env)
temp <- .extract_kernel_from_eval_env(kern_env,
proto$kernel_id[i],
out,
proto$params[[i]]$family,
pos = i)
out[[i]] <- .fun_to_iteration_mat(temp[[i]],
state_var_start = names(proto$domain[[i]])[1],
state_var_end = names(proto$domain[[i]])[2],
main_env = main_env,
kern_name = proto$kernel_id[i])
names(out)[i] <- proto$kernel_id[i]
if(return_envs) {
env_list <- c(env_list, list(kern_env))
names(env_list)[(i + 1)] <- proto$kernel_id[i]
}
} # end sub-kernel construction
res <- list(sub_kernels = out, env_list = env_list)
return(res)
}
.make_sub_kernel_general_lazy <- function(proto, main_env, return_envs = FALSE) {
env_state_funs <- lapply(
proto$env_state,
function(x, main_env) {
temp <- x$env_quos
if(rlang::is_quosure(temp[[1]]) || rlang::is_quosures(temp[[1]])) {
out <- lapply(temp,
function(x, main_env) {
rlang::quo_set_env(x,
main_env)
},
main_env = main_env)
} else {
out <- NULL
}
return(out)
},
main_env = main_env) %>%
.flatten_to_depth(1L)
nms <- names(env_state_funs)
ind <- duplicated(nms)
env_state_funs <- env_state_funs[!ind]
main_env <- .bind_env_exprs(main_env, env_state_funs)
env_list <- list(main_env = main_env)
sys <- .make_sub_kernel_general(proto,
env_list,
return_envs = return_envs)
out <- list(ipm_system = sys,
main_env = main_env)
return(out)
}
#' @noRd
.make_sub_kernel_simple <- function(proto, env_list, return_envs = FALSE) {
out <- list()
main_env <- env_list$main_env
for(i in seq_len(dim(proto)[1])) {
if(proto$evict[i]) {
proto[i, ] <- .correct_eviction(proto[i, ])
}
param_tree <- proto$params[[i]]
integrate <- param_tree$integrate
kern_env <- .make_kernel_env(param_tree$params,
main_env,
proto[i, ])
kern_text <- .append_dz_to_kern_form(param_tree$formula,
proto,
i,
integrate)
kern_form <- .parse_vr_formulae(kern_text,
kern_env,
proto[i, ],
main_env)
names(kern_form) <- proto$kernel_id[i]
rlang::env_bind_lazy(kern_env,
!!! kern_form,
.eval_env = kern_env)
temp <- .extract_kernel_from_eval_env(kern_env,
proto$kernel_id[i],
out,
proto$params[[i]]$family,
pos = i)
out[[i]] <- .fun_to_iteration_mat(temp[[i]],
state_var_start = names(proto$domain[[i]])[1],
state_var_end = names(proto$domain[[i]])[2],
main_env = main_env,
kern_name = proto$kernel_id[i])
names(out)[i] <- proto$kernel_id[i]
if(return_envs) {
env_list <- c(env_list, list(kern_env))
names(env_list)[(i + 1)] <- proto$kernel_id[i]
}
} # end sub-kernel construction
res <- list(sub_kernels = out, env_list = env_list)
return(res)
}
#' @noRd
.append_dz_to_kern_form <- function(kern_text, proto, id,
integrate) {
# If the user has specified not to integrate, then this step is not
# necessary
if(!integrate) return(kern_text)
# If discrete_extrema is used, then the d_z has already been appended
# somewhere on that kernel. Thus, just return the kernel text
if(proto$evict[id]) {
quo_l <- .flatten_to_depth(proto$evict_fun[[id]], 1L)
if(rlang::call_name(quo_l[[1]]) == "discrete_extrema") {
return(kern_text)
}
}
sv <- names(proto$domain[[id]])
sv <- gsub('_[0-9]', "", sv)
out <- paste(kern_text, ' * d_', unique(sv), sep = "")
return(out)
}
#' @noRd
# makes sub-kernels, but ensures that stochastic parameters are sampled from
# their respective distributions one time for each iteration. One of many reasons
# kernel resampling is preferred when a viable alternative (at least within
# the context of ipmr).
.make_sub_kernel_simple_lazy <- function(proto, main_env, return_envs = FALSE,
dd = 'n') {
out <- switch(dd,
'n' = .make_sub_kernel_simple_lazy_di(proto,
main_env,
return_envs),
'y' = .make_sub_kernel_simple_lazy_dd(proto,
main_env,
return_envs))
return(out)
}
.make_sub_kernel_simple_lazy_dd <- function(proto,
main_env,
return_envs) {
out <- .make_sub_kernel_simple(proto,
list(main_env = main_env),
return_envs = return_envs)
return(out)
}
.make_sub_kernel_simple_lazy_di <- function(proto, main_env, return_envs = FALSE) {
env_state_funs <- lapply(
proto$env_state,
function(x, main_env) {
temp <- x$env_quos
if(rlang::is_quosure(temp[[1]]) || rlang::is_quosures(temp[[1]])) {
out <- lapply(temp,
function(x, main_env) {
rlang::quo_set_env(x,
main_env)
},
main_env = main_env)
} else {
out <- NULL
}
return(out)
},
main_env = main_env) %>%
.flatten_to_depth(1L)
nms <- names(env_state_funs)
ind <- duplicated(nms)
env_state_funs <- env_state_funs[!ind]
main_env <- .bind_env_exprs(main_env, env_state_funs)
env_list <- list(main_env = main_env)
sys <- .make_sub_kernel_simple(proto,
env_list,
return_envs = return_envs)
out <- list(ipm_system = sys,
main_env = main_env)
return(out)
}
#' @noRd
# makes sure the expressions for each stochastic parameter are evaluated
# only one time per iteration of the whole model. Creates data in 2 formats:
#
# 1. Individual values of each parameter that are bound to a correspoding symbol
# in the main environment. This means that users can reference each variable
# by NAME without using left hand side of the env_state expression. For example
# in a vital rate expression, env_params$g_r_yr becomes g_r_yr, no env_params$.
#
# 2. a list named by the left hand side of the env_state expression that contains
# all of the values it creates, also named. This is so that .update_env_output
# can grab that list, unlist it, and stick it into a matrix. Matching all of those
# things by names provided by the user would probably get a bit more convoluted
# and be error prone.
.bind_env_exprs <- function(main_env, env_funs) {
nms <- names(env_funs)
rlang::env_bind_lazy(main_env, !!! env_funs, .eval_env = main_env)
for(i in seq_along(nms)) {
# This does the binding so that values are accessible by the names
# the user gives them.
# temp <- rlang::eval_tidy(env_funs[[i]])
temp <- rlang::env_get(main_env, nms[i])
if(!rlang::is_list(temp)) {
temp <- rlang::list2(!!nms[i] := temp)
}
rlang::env_bind(main_env, !!! temp)
# This creates a list containing the same values so that .update_env_output
# can find them to store the env_seq data to return to the user.
ass_nm <- nms[i]
env_param_list <- rlang::list2(!! ass_nm := temp) %>%
.flatten_to_depth(1L)
# This handles binding values when expressions are supplied rather
# than functions. This is always the case in PADRINO, and may be the case
# for interactive use as well.
if(all(names(env_funs)[i] %in% names(env_param_list))){
rlang::env_bind(main_env, !!! env_param_list)
} else {
assign(ass_nm, env_param_list, envir = main_env)
}
}
return(main_env)
}
#' @noRd
.prep_di_output <- function(others, k_row, proto_ipm, iterations, normal) {
# all placeholders.
out <- list(iterators = list(),
sub_kernels = list(),
env_list = list(),
env_seq = NA_real_,
pop_state = NA_real_,
proto_ipm = proto_ipm)
out$pop_state <- .init_pop_state_list(others, iterations, normal)
return(out)
}
#' @noRd
.init_pop_state_list <- function(others,
iterations,
normal) {
# Flatten and drop duplicates. Duplication is likely to occur in simple_*
# ipms because every kernel will have the same population state associated
# with it. General IPMs with parameter sets, on the other hand, will need
# different population states for almost every kernel row.
pop_state <- .flatten_to_depth(others$pop_state, 1L)
pop_state <- pop_state[!duplicated(names(pop_state))]
out <- list()
# If pop_vec is specified, then initialize an array to hold the output
if(!rlang::is_empty(pop_state)){
if(rlang::is_list(pop_state)) {
# multiple states
for(i in seq_along(pop_state)) {
if(rlang::is_quosure(pop_state[[i]])) {
pop_state[[i]] <- rlang::eval_tidy(pop_state[[i]])
}
dim_pop_out <- ifelse(is.matrix(pop_state[[i]]),
dim(pop_state[[i]]),
length(pop_state[[i]]))
# Need to work out exactly how to know the indexing procedure here -
# higher dimensional kernels will have time as the 3rd, 4th, or 5th
# dimension (so trippy!) and normal bracket notation won't necessarily
# work without some awful if{...}else{} sequence. Right now, this will
# only work for distinct continuous state vars
pop_out <- array(NA_real_, dim = c(dim_pop_out,
iterations + 1))
pop_out[ , 1] <- pop_state[[i]]
out[[i]] <- pop_out
}
names(out) <- gsub("_t", "", names(pop_state))
}
}
# Rescale population vector to 1 if requested.
if(normal) {
out <- .norm_pop_size(out, time_step = 1L)
}
out$lambda <- matrix(NA_real_, nrow = 1, ncol = iterations + 1)
return(out)
}
.pop_size <- function(pop, time_step) {
# Remove lambda slot - this shouldn't be counted or scaled!
pop <- pop[!grepl("lambda", names(pop))]
temp <- vapply(pop,
function(x, time_step) sum(x[ , time_step]),
numeric(1L),
time_step = time_step)
out <- Reduce('+', temp, init = 0)
return(out)
}
#' @noRd
.norm_pop_size <- function(pop_list, time_step) {
# compute total population size and re-scale population vectors
# by that. Do not re-scale lambda. .pop_size knows to remove this
# column, so no need to worry about that in step 1.
tot_size <- .pop_size(pop_list, time_step)
lams <- pop_list[grepl("lambda", names(pop_list))]
pop <- pop_list[! grepl("lambda", names(pop_list))]
out <- lapply(
pop,
function(x, pop_size, time_step) {
x[ , time_step] <- x[ , time_step] / pop_size
return(x)
},
pop_size = tot_size,
time_step = time_step
)
# instert lambdas back into the pop_state object
out <- c(out, lams)
return(out)
}
#' @noRd
.update_param_output <- function(sub_kernels,
pop_state,
data_envs = NA_character_,
main_env,
output,
tot_iterations,
current_iteration,
return_sub_kernels) {
# Updates env_seq and data_environments part of output. env, perhaps confusingly,
# refers to environment in both the programming and the biological sense
output <- .update_env_output(output,
main_env = main_env,
data_envs = data_envs,
tot_iterations = tot_iterations,
current_iteration = current_iteration)
if(return_sub_kernels){
names(sub_kernels) <- paste(names(sub_kernels),
"it",
current_iteration,
sep = "_")
output$sub_kernels <- c(output$sub_kernels, sub_kernels)
} else {
output$sub_kernels <- NA_real_
}
output$pop_state <- pop_state
return(output)
}
# Modifies output in place - updates environmental parameter sequence
# AND the data_envs list slot. "env" refers to both programming environments
# and to biological environments - might need to improve terminology for long
# term maintenance.
.update_env_output <- function(output,
main_env,
data_envs,
tot_iterations,
current_iteration) {
# First, figure out if this is a stoch_param model. If so, then
# determine if env_state is comprised of functions. If so, get whatever
# they returned for that iteration. If not, grab the constants (I think this
# is more useful for troubleshooting than anyone actually using it - if the
# environment isn't varying, then they shouldn't be using this method anyway).
if(any(grepl("stoch_param", class(output$proto_ipm)))){
if(!rlang::is_empty(names(output$proto_ipm$env_state[[1]]$env_quos))) {
env_vars <- names(output$proto_ipm$env_state[[1]]$env_quos)
} else {
env_vars <- names(output$proto_ipm$env_state[[1]]$constants)
}
env_temp <- rlang::env_get_list(main_env,
env_vars,
default = NA_real_,
inherit = FALSE) %>%
unlist()
if(current_iteration == 1) {
env_var_nms <- names(env_temp) %>%
strsplit('\\.') %>%
vapply(function(x) x[length(x)], character(1L))
output$env_seq <- matrix(NA_real_,
nrow = tot_iterations,
ncol = length(env_temp),
byrow = TRUE,
dimnames = list(c(NULL),
c(env_var_nms)))
}
output$env_seq[current_iteration, ] <- env_temp
}
# On to the rest of the output
if(!all(is.na(data_envs))) {
output$sub_kernel_envs <- c(output$sub_kernel_envs, data_envs)
}
return(output)
}
#' @noRd
# Generates evaluation environment for a sub-kernel. Assumes that all parameters
# name/value pairs have been generated. Inherits from main_env so that it can
# access domains, stochastic parameters, and population states.
.make_kernel_env <- function(parameters,
main_env,
proto) {
param_tree <- proto$params
kernel_env <- rlang::child_env(.parent = main_env)
rlang::env_bind(kernel_env,
!!! parameters)
kern_quos <- .parse_vr_formulae(param_tree[[1]]$vr_text,
kernel_env,
proto,
main_env)
# Bind the vital rate expressions so the initial discretization can take
# place
rlang::env_bind_lazy(kernel_env,
!!! kern_quos,
.eval_env = kernel_env)
invisible(kernel_env)
}
#' @noRd
.parse_vr_formulae <- function(text,
kernel_env,
proto,
main_env) {
# Check for calls to sum() in text. These need to be modified to
# divide by the number of meshpoints over the domain of the function IF there
# is only one domain for the function (which is what the user will want, not
# the sum of the entire result of expand.grid(z, z1)).
test <- vapply(text, .check_sum_calls, logical(1L))
if(any(test)) {
text[test] <- lapply(text[test],
function(x, proto_ipm, main_env) {
.prep_sum_calls(x,
proto_ipm = proto_ipm,
main_env = main_env)
},
proto_ipm = proto,
main_env = main_env)
}
# parse the text expressions and then convert to list of depth 1.
# This is critical as otherwise, env_bind_lazy bind a list containing the
# expression rather than the expression itself!
vr_forms <- lapply(text, function(x) rlang::parse_exprs(x)) %>%
.flatten_to_depth(1L)
# convert to quosures and set the environment for evaluation
out <- lapply(vr_forms, function(x, to_set) {
temp <- rlang::enquo(x)
rlang::quo_set_env(temp, to_set)
},
to_set = kernel_env)
return(out)
}
.parse_k_formulae <- function(text, kernel_env, proto, main_env) {
# Modify forms to make sense w/ n->pop_state renaming
text <- lapply(text, function(x) {
gsub(' n_', ' pop_state_', x, perl = TRUE)
}
)
names(text) <- gsub('^n_', 'pop_state_', names(text))
out <- .parse_vr_formulae(text, kernel_env, proto, main_env)
return(out)
}
#' @noRd
#' @importFrom purrr flatten map_dbl
#'
# Rename to main_env or something like that - this doesn't strictly hold
# domain information anymore
.make_main_env <- function(domain_list, usr_funs, age_size) {
# Parent is whatever is 2nd on search path. all loaded functions/packges
# should still be findable, but objects in the global environment should not
# be to prevent overscoping!
main_env <- new.env(parent = as.environment(search()[2]))
domain_list <- .flatten_to_depth(domain_list, 1L)
domain_list <- domain_list[!duplicated(names(domain_list))]
# Filter out some common troubles w/ age X size models
if(age_size) {
names(domain_list) <- gsub("_(age)|_(max)", "", names(domain_list))
names(domain_list) <- gsub("_[0-9]", "", names(domain_list))
domain_list <- domain_list[!duplicated(names(domain_list))] %>%
c(., .) %>%
setNames(paste(names(.), c(1:2), sep = "_"))
}
rm_ind <- vapply(domain_list,
function(x) any(is.na(x)),
logical(1L))
domain_list <- domain_list[ ! rm_ind ]
# This next bit guarantees that d_1 comes before d_2 every time.
# testing partially par_setarchical models produced a bug where d_2
# can occur before d_1 in the names of this list in one very specific, but
# potentially not-uncommon case where the first non-NA domain name in domain_list
# d_2
nm_order <- sort(names(domain_list))
domain_list <- domain_list[nm_order]
domain_list <- domain_list[!is.na(names(domain_list))]
# Resume as before
bounds <- purrr::map(domain_list, function(x) .make_domain_seqs(x))
# Create helper vars for user-facing formula writing
Ls <- purrr::map_dbl(domain_list, ~.x[1])
Us <- purrr::map_dbl(domain_list, ~.x[2])
n_mesh_p <- purrr::map_dbl(domain_list, ~.x[3])
# Generate unique names
names(Ls) <- paste('L_', names(domain_list), sep = "")
names(Us) <- paste('U_', names(domain_list), sep = "")
names(n_mesh_p) <- paste('n_', names(domain_list), sep = "")
rlang::env_bind(main_env,
!!! Ls,
!!! Us,
!!! n_mesh_p)
# Generate midpoints for integration mesh
mids <- purrr::map(bounds, .f = function(x) {
l <- length(x) - 1
out_domain <- 0.5 * (x[1:l] + x[2:(l + 1)])
return(out_domain)
})
# For general IPMs, we also need indices to extract the correct vectors
# from the evaluated kernels. For CC and DD, these are just empty vectors because
# we want the complete result. However, DC and CD will still generate vectors the
# same length as CC, even though we only want the first row for CD and first column
# for DC. CD is easy, it's just a sequence 1:n_mesh_p. DC is (0:n_mesh_p * n_mesh_p) + 1
# to get the first value in each row (e.g. the first column of the iteration matrix).
# Append names of the state variable to each so that we can access them later.
# We do not want to do this for continuous states that don't exist - e.g. n_mesh_p = NA
# This throws an error, so reduce the list to !is.na() entries.
dc_cd_nms <- names(domain_list)[!grepl('_not_applicable', names(domain_list))]
n_mesh_p_cont <- n_mesh_p[!is.na(n_mesh_p)]
for(i in seq_along(dc_cd_nms)) {
cd_nm <- paste('cd_ind_', dc_cd_nms[i], sep = "")
dc_nm <- paste('dc_ind_', dc_cd_nms[i], sep = "")
to_bind <- rlang::list2(!! cd_nm := seq(1,
n_mesh_p_cont[[i]],
by = 1),
!! dc_nm := (seq(0,
n_mesh_p_cont[[i]] - 1,
by = 1) * n_mesh_p_cont[[i]]) + 1)
rlang::env_bind(main_env,
!!! to_bind)
}
# Loop over the different domains. Each continuous variable will have two,
# hence the "by = 2". This only applies for midpoint rule IPMs, others will need
# different weights, etc.
cont_svs <- strsplit(names(domain_list), '_[0-9]') %>% unlist()
cont_svs <- cont_svs[!grepl('not_applicable', cont_svs)] %>%
unique()
for(i in cont_svs) {
mid_ind <- grepl(i, names(mids))
domain_grid <- expand.grid(mids[mid_ind])
names(domain_grid) <- c(names(mids)[mid_ind])
rlang::env_bind(main_env,
!!! domain_grid)
nm <- paste0('d_', i, sep = "")
h <- domain_grid[2, 1] - domain_grid[1, 1]
assign(nm, h, envir = main_env)
}
# Add in user specified functions. These need to be in the main_env
# so all kernels can access them during evaluation
if(rlang::is_named(usr_funs)){
rlang::env_bind(main_env,
!!! usr_funs)
}
invisible(main_env)
}
#' @noRd
# Generates sequences for the domain of midpoint rule integration (and midpoint
# rule only!!!!!!!!!). This must be generalized for handling bin to bin, cdf, etc.
.make_domain_seqs <- function(dom_vec) {
if(all(!is.na(dom_vec))) {
out <- seq(dom_vec[1], dom_vec[2], length.out = dom_vec[3] + 1)
return(out)
} else {
return(NULL)
}
}
#' @noRd
# Pulls out the evaluated sub-kernels from their evaluation environment
# and splices them into a list to hold them.
.extract_kernel_from_eval_env <- function(kernel_env,
kernel_id,
sub_kernel_list,
family,
pos) {
out <- rlang::env_get(kernel_env, kernel_id)
# Checks for negative/NA entries
out <- .valid_it_mat(out, kernel_id)
sub_kernel_list[[pos]] <- out
names(sub_kernel_list)[pos] <- kernel_id
class(sub_kernel_list[[pos]]) <- family
return(sub_kernel_list)
}
#' @noRd
# Generates a sequence of indices to sample kernels during stochastic
# kernel resampling procedures.
.make_kern_seq <- function(proto, iterations, kernel_seq) {
if(is.null(kernel_seq) || all(is.na(kernel_seq))) {
seq_type <- 'NA'
} else {
test <- is.matrix(kernel_seq)
if(test) {
seq_type <- 'markov_chain_mat'
} else if(all(kernel_seq == 'internal')) {
seq_type <- "internal"
} else {
seq_type <- 'usr_specified'
}
}
out <- switch(seq_type,
'NA' = NULL,
'markov_chain_mat' = .make_markov_seq(proto,
kernel_seq,
iterations),
'usr_specified' = .make_usr_seq(proto,
kernel_seq,
iterations),
'internal' = .make_internal_seq(proto, iterations))
return(out)
}
# Generates a random sequence from a uniform distribution. This only gets called
# if the user doesn't specify one on their own in _stoch_kern methods
.make_internal_seq <- function(proto, iterations) {
par_sets <- proto$par_set_indices[proto$uses_par_sets]
par_sets <- par_sets[!duplicated(par_sets)]
opts <- .make_par_set_indices(par_sets)
out <- sample(opts, size = iterations, replace = TRUE)
return(out)
}
.make_markov_seq <- function(proto,
kernel_seq,
iterations) {
stop('markov chain environmental sequences not yet supported',
call. = FALSE)
}
#' @noRd
.make_usr_seq <- function(proto, kernel_seq, iterations) {
if(is.integer(kernel_seq)) {
kernel_seq <- as.character(kernel_seq)
}
# Make sure everything in kernel_seq appears is actually an option
nms_test <- logical(length(unique(kernel_seq)))
pos_ids <- proto[proto$uses_par_sets, ]
for(i in seq_along(unique(kernel_seq))) {
nms_test[i] <- any(grepl(kernel_seq[i], pos_ids))
}
if(! all(nms_test)) {
stop("Not all values of 'kern_seq' are present in kernel names. Please ",
"check the model definition.")
}
if(length(kernel_seq) > iterations) {
warning("'length(kernel_seq)' is greater than requested 'iterations'.",
" Simulation will only run for as many 'iterations'.")
}
return(kernel_seq)
}
#' @noRd
.check_ipm_definition <- function(proto_ipm, iterate) {
.check_pop_state(proto_ipm, iterate)
.check_env_state(proto_ipm)
ipm_type <- class(proto_ipm)[1]
if(grepl('_param|dd', ipm_type) & !iterate) {
stop("Stochastic, parameter resampled and density dependent models must be\n",
"iterated! Set 'iterate' to 'TRUE' and re-run.")
}
invisible(TRUE)
}
#' @noRd
.check_pop_state <- function(proto_ipm, iterate) {
# ipm type is always first in class(proto)
ipm_type <- class(proto_ipm)[1]
pop_state <- unlist(proto_ipm$pop_state) %>%
unique()
if(any(is.na(pop_state)) && iterate) {
stop("'iterate = TRUE' but 'pop_state' is not defined!",
call. = FALSE)
}
state_vars <- unlist(proto_ipm$state_var) %>%
unique()
if(!all(names(pop_state) %in% names(state_vars))) {
stop("Names of state variables do not match names of 'pop_state'!")
}
# density dependent IPMs must have pop_state defined!
if(grepl('_dd_', ipm_type)) {
if(all(is.na(pop_state))) {
stop("Density dependent IPMs must have 'pop_state' defined!\n",
"See '?define_pop_state()' for more details.")
}
}