-
Notifications
You must be signed in to change notification settings - Fork 4
/
crew_controller.R
1413 lines (1412 loc) · 57.9 KB
/
crew_controller.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
#' @title Create a controller object from a client and launcher.
#' @export
#' @family controller
#' @description This function is for developers of `crew` launcher plugins.
#' Users should use a specific controller helper such as
#' [crew_controller_local()].
#' @param client An `R6` client object created by [crew_client()].
#' @param launcher An `R6` launcher object created by one of the
#' `crew_launcher_*()` functions such as [crew_launcher_local()].
#' @param auto_scale Deprecated. Use the `scale` argument of `push()`,
#' `pop()`, and `wait()` instead.
#' @examples
#' if (identical(Sys.getenv("CREW_EXAMPLES"), "true")) {
#' client <- crew_client()
#' launcher <- crew_launcher_local()
#' controller <- crew_controller(client = client, launcher = launcher)
#' controller$start()
#' controller$push(name = "task", command = sqrt(4))
#' controller$wait()
#' controller$pop()
#' controller$terminate()
#' }
crew_controller <- function(
client,
launcher,
auto_scale = NULL
) {
crew_deprecate(
name = "auto_scale",
date = "2023-05-18",
version = "0.2.0",
alternative = "use the scale argument of push(), pop(), and wait()",
value = auto_scale,
frequency = "once"
)
controller <- crew_class_controller$new(client = client, launcher = launcher)
controller$launcher$set_name(controller$client$name)
controller$validate()
controller
}
#' @title Controller class
#' @export
#' @family controller
#' @description `R6` class for controllers.
#' @details See [crew_controller()].
#' @examples
#' if (identical(Sys.getenv("CREW_EXAMPLES"), "true")) {
#' client <- crew_client()
#' launcher <- crew_launcher_local()
#' controller <- crew_controller(client = client, launcher = launcher)
#' controller$start()
#' controller$push(name = "task", command = sqrt(4))
#' controller$wait()
#' controller$pop()
#' controller$terminate()
#' }
crew_class_controller <- R6::R6Class(
classname = "crew_class_controller",
cloneable = FALSE,
private = list(
.client = NULL,
.launcher = NULL,
.tasks = NULL,
.pushed = NULL,
.popped = NULL,
.summary = NULL,
.error = NULL,
.backlog = NULL,
.autoscaling = NULL,
.shove = function(
command,
data = list(),
globals = list(),
seed = NULL,
algorithm = NULL,
packages = character(0),
library = NULL,
.timeout = NULL,
name = NA_character_,
string = NA_character_
) {
task <- mirai::mirai(
.expr = expr_crew_eval,
.args = list(
name = name,
command = command,
string = string,
data = data,
globals = globals,
seed = seed,
algorithm = algorithm,
packages = packages,
library = library
),
.timeout = .timeout,
.compute = private$.client$name
)
on.exit({
private$.tasks[[length(.subset2(self, "tasks")) + 1L]] <- task
private$.pushed <- .subset2(self, "pushed") + 1L
})
invisible(task)
},
.wait_all_once = function(seconds_interval) {
if (.subset2(self, "unresolved")() > 0L) {
private$.client$relay$wait(seconds_timeout = seconds_interval)
}
.subset2(self, "unresolved")() < 1L
},
.wait_one_once = function(seconds_interval) {
if (.subset2(self, "unpopped")() < 1L) {
private$.client$relay$wait(seconds_timeout = seconds_interval)
}
.subset2(self, "unpopped")() > 0L
}
),
active = list(
#' @field client Router object.
client = function() {
.subset2(private, ".client")
},
#' @field launcher Launcher object.
launcher = function() {
.subset2(private, ".launcher")
},
#' @field tasks A list of `mirai::mirai()` task objects.
tasks = function() {
.subset2(private, ".tasks")
},
#' @field pushed Number of tasks pushed since the controller was started.
pushed = function() {
.subset2(private, ".pushed")
},
#' @field popped Number of tasks popped
#' since the controller was started.
popped = function() {
.subset2(private, ".popped")
},
#' @field error Tibble of task results (with one result per row)
#' from the last call to `map(error = "stop)`.
error = function() {
.subset2(private, ".error")
},
#' @field backlog Character vector of explicitly backlogged tasks.
backlog = function() {
.subset2(private, ".backlog")
},
#' @field autoscaling `TRUE` or `FALSE`, whether async `later`-based
#' auto-scaling is currently running
autoscaling = function() {
.subset2(private, ".autoscaling")
}
),
public = list(
#' @description `mirai` controller constructor.
#' @return An `R6` controller object.
#' @param client Router object. See [crew_controller()].
#' @param launcher Launcher object. See [crew_controller()].
#' @examples
#' if (identical(Sys.getenv("CREW_EXAMPLES"), "true")) {
#' client <- crew_client()
#' launcher <- crew_launcher_local()
#' controller <- crew_controller(client = client, launcher = launcher)
#' controller$start()
#' controller$push(name = "task", command = sqrt(4))
#' controller$wait()
#' controller$pop()
#' controller$terminate()
#' }
initialize = function(
client = NULL,
launcher = NULL
) {
private$.client <- client
private$.launcher <- launcher
invisible()
},
#' @description Validate the client.
#' @return `NULL` (invisibly).
validate = function() {
crew_assert(inherits(private$.client, "crew_class_client"))
crew_assert(inherits(private$.launcher, "crew_class_launcher"))
private$.client$validate()
private$.launcher$validate()
crew_assert(private$.tasks, is.null(.) || is.list(.))
crew_assert(
identical(private$.client$name, private$.launcher$name),
message = "client and launcher must have the same name"
)
crew_assert(private$.summary, is.null(.) || is.list(.))
crew_assert(private$.backlog, is.null(.) || is.character(.))
crew_assert(private$.autoscaling, is.null(.) || isTRUE(.) || isFALSE(.))
invisible()
},
#' @description Check if the controller is empty.
#' @details A controller is empty if it has no running tasks
#' or completed tasks waiting to be retrieved with `push()`.
#' @return `TRUE` if the controller is empty, `FALSE` otherwise.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
empty = function(controllers = NULL) {
length(.subset2(self, "tasks")) < 1L
},
#' @description Check if the controller is nonempty.
#' @details A controller is empty if it has no running tasks
#' or completed tasks waiting to be retrieved with `push()`.
#' @return `TRUE` if the controller is empty, `FALSE` otherwise.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
nonempty = function(controllers = NULL) {
length(.subset2(self, "tasks")) > 0L
},
#' @description Number of resolved `mirai()` tasks.
#' @details `resolved()` is cumulative: it counts all the resolved
#' tasks over the entire lifetime of the controller session.
#' @return Non-negative integer of length 1,
#' number of resolved `mirai()` tasks.
#' The return value is 0 if the condition variable does not exist
#' (i.e. if the client is not running).
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
resolved = function(controllers = NULL) {
.subset2(.subset2(self, "client"), "resolved")()
},
#' @description Number of unresolved `mirai()` tasks.
#' @return Non-negative integer of length 1,
#' number of unresolved `mirai()` tasks.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
unresolved = function(controllers = NULL) {
.subset2(self, "pushed") - .subset2(self, "resolved")()
},
#' @description Number of resolved `mirai()` tasks available via `pop()`.
#' @return Non-negative integer of length 1,
#' number of resolved `mirai()` tasks available via `pop()`.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
unpopped = function(controllers = NULL) {
.subset2(self, "resolved")() - .subset2(self, "popped")
},
#' @description Check if the controller is saturated.
#' @details A controller is saturated if the number of unresolved tasks
#' is greater than or equal to the maximum number of workers.
#' In other words, in a saturated controller, every available worker
#' has a task.
#' You can still push tasks to a saturated controller, but
#' tools that use `crew` such as `targets` may choose not to.
#' @return `TRUE` if the controller is saturated, `FALSE` otherwise.
#' @param collect Deprecated in version 0.5.0.9003 (2023-10-02). Not used.
#' @param throttle Deprecated in version 0.5.0.9003 (2023-10-02). Not used.
#' @param controller Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
saturated = function(collect = NULL, throttle = NULL, controller = NULL) {
crew_deprecate(
name = "collect",
date = "2023-10-02",
version = "0.5.0.9003",
alternative = "none (no longer necessary)",
condition = "message",
value = collect,
skip_cran = TRUE,
frequency = "once"
)
crew_deprecate(
name = "throttle",
date = "2023-10-02",
version = "0.5.0.9003",
alternative = "none (no longer necessary)",
condition = "message",
value = throttle,
skip_cran = TRUE,
frequency = "once"
)
.subset2(self, "unresolved")() >=
.subset2(.subset2(self, "client"), "workers")
},
#' @description Start the controller if it is not already started.
#' @details Register the mirai client and register worker websockets
#' with the launcher.
#' @return `NULL` (invisibly).
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
start = function(controllers = NULL) {
if (!isTRUE(.subset2(.subset2(self, "client"), "started"))) {
private$.client$start()
workers <- private$.client$workers
private$.launcher$start()
private$.tasks <- list()
private$.pushed <- 0L
private$.popped <- 0L
private$.summary <- list(
controller = rep(private$.client$name, workers),
worker = seq_len(workers),
tasks = rep(0L, workers),
seconds = rep(0, workers),
errors = rep(0L, workers),
warnings = rep(0L, workers)
)
private$.backlog <- character(0L)
}
invisible()
},
#' @description Check whether the controller is started.
#' @details Actually checks whether the client is started.
#' @return `TRUE` if the controller is started, `FALSE` otherwise.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
started = function(controllers = NULL) {
isTRUE(.subset2(.subset2(self, "client"), "started"))
},
#' @description Launch one or more workers.
#' @return `NULL` (invisibly).
#' @param n Number of workers to try to launch. The actual
#' number launched is capped so that no more than "`workers`"
#' workers running at a given time, where "`workers`"
#' is an argument of [crew_controller()]. The
#' actual cap is the "`workers`" argument minus the number of connected
#' workers minus the number of starting workers. A "connected"
#' worker has an active websocket connection to the `mirai` client,
#' and "starting" means that the worker was launched at most
#' `seconds_start` seconds ago, where `seconds_start` is
#' also an argument of [crew_controller()].
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
launch = function(n = 1L, controllers = NULL) {
.subset2(self, "start")()
private$.launcher$tally()
private$.launcher$rotate()
walk(
x = private$.launcher$unlaunched(n = n),
f = private$.launcher$launch
)
invisible()
},
#' @description Auto-scale workers out to meet the demand of tasks.
#' @details The `scale()` method re-launches all inactive backlogged
#' workers, then any additional inactive workers needed to
#' accommodate the demand of unresolved tasks. A worker is
#' "backlogged" if it was assigned more tasks than it has completed
#' so far.
#'
#' Methods `push()`, `pop()`, and `wait()` already invoke
#' `scale()` if the `scale` argument is `TRUE`.
#' For finer control of the number of workers launched,
#' call `launch()` on the controller with the exact desired
#' number of workers.
#' @return `NULL` (invisibly).
#' @param throttle `TRUE` to skip auto-scaling if it already happened
#' within the last `seconds_interval` seconds. `FALSE` to auto-scale
#' every time `scale()` is called. Throttling avoids
#' overburdening the `mirai` dispatcher and other resources.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
scale = function(throttle = TRUE, controllers = NULL) {
private$.launcher$scale(demand = self$unresolved(), throttle = throttle)
invisible()
},
#' @description Run worker auto-scaling in a private `later` loop
#' every `controller$client$seconds_interval` seconds.
#' @details Call `controller$descale()` to terminate the
#' auto-scaling loop.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
#' @return `NULL` (invisibly).
autoscale = function(controllers = NULL) {
# Tested in tests/interactive/test-promises.R
# nocov start
if (isTRUE(private$.autoscaling)) {
return(invisible())
}
poll <- function() {
if (isTRUE(self$client$started) && isTRUE(private$.autoscaling)) {
self$scale(throttle = FALSE)
later::later(func = poll, delay = self$client$seconds_interval)
}
}
self$start()
private$.autoscaling <- TRUE
poll()
invisible()
# nocov end
},
#' @description Terminate the auto-scaling loop started by
#' `controller$autoscale()`.
#' @param controllers Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
#' @return `NULL` (invisibly).
descale = function(controllers = NULL) {
private$.autoscaling <- FALSE
invisible()
},
#' @description Push a task to the head of the task list.
#' @return Invisibly return the `mirai` object of the pushed task.
#' This allows you to interact with the task directly, e.g.
#' to create a promise object with `promises::as.promise()`.
#' @param command Language object with R code to run.
#' @param data Named list of local data objects in the
#' evaluation environment.
#' @param globals Named list of objects to temporarily assign to the
#' global environment for the task.
#' This list should
#' include any functions you previously defined in the global
#' environment which are required to run tasks.
#' See the `reset_globals` argument
#' of [crew_controller_local()].
#' @param substitute Logical of length 1, whether to call
#' `base::substitute()` on the supplied value of the
#' `command` argument. If `TRUE` (default) then `command` is quoted
#' literally as you write it, e.g.
#' `push(command = your_function_call())`. If `FALSE`, then `crew`
#' assumes `command` is a language object and you are passing its
#' value, e.g. `push(command = quote(your_function_call()))`.
#' `substitute = TRUE` is appropriate for interactive use,
#' whereas `substitute = FALSE` is meant for automated R programs
#' that invoke `crew` controllers.
#' @param seed Integer of length 1 with the pseudo-random number generator
#' seed to set for the evaluation of the task. Passed to the
#' `seed` argument of `set.seed()` if not `NULL`.
#' If `algorithm` and `seed` are both `NULL`,
#' then the random number generator defaults to the
#' widely spaced worker-specific
#' L'Ecuyer streams as supported by `mirai::nextstream()`.
#' See `vignette("parallel", package = "parallel")` for details.
#' @param algorithm Integer of length 1 with the pseudo-random number
#' generator algorithm to set for the evaluation of the task.
#' Passed to the `kind` argument of `RNGkind()` if not `NULL`.
#' If `algorithm` and `seed` are both `NULL`,
#' then the random number generator defaults to the
#' recommended widely spaced worker-specific
#' L'Ecuyer streams as supported by `mirai::nextstream()`.
#' See `vignette("parallel", package = "parallel")` for details.
#' @param packages Character vector of packages to load for the task.
#' @param library Library path to load the packages. See the `lib.loc`
#' argument of `require()`.
#' @param seconds_timeout Optional task timeout passed to the `.timeout`
#' argument of `mirai::mirai()` (after converting to milliseconds).
#' @param scale Logical, whether to automatically call `scale()`
#' to auto-scale workers to meet the demand of the task load. Also
#' see the `throttle` argument.
#' @param throttle `TRUE` to skip auto-scaling if it already happened
#' within the last `seconds_interval` seconds. `FALSE` to auto-scale
#' every time `scale()` is called. Throttling avoids
#' overburdening the `mirai` dispatcher and other resources.
#' @param name Optional name of the task. Must be a character string
#' or `NA`.
#' @param save_command Logical of length 1. If `TRUE`, the controller
#' deparses the command and returns it with the output on `pop()`.
#' If `FALSE` (default), the controller skips this step to
#' increase speed.
#' @param controller Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
push = function(
command,
data = list(),
globals = list(),
substitute = TRUE,
seed = NULL,
algorithm = NULL,
packages = character(0),
library = NULL,
seconds_timeout = NULL,
scale = TRUE,
throttle = TRUE,
name = NA_character_,
save_command = FALSE,
controller = NULL
) {
.subset2(self, "start")()
if (substitute) {
command <- substitute(command)
}
if (save_command) {
string <- deparse_safe(command)
} else {
string <- NA_character_
}
if (is.null(seconds_timeout)) {
.timeout <- NULL
} else {
.timeout <- seconds_timeout * 1000
}
task <- mirai::mirai(
.expr = expr_crew_eval,
.args = list(
name = name,
command = command,
string = string,
data = data,
globals = globals,
seed = seed,
algorithm = algorithm,
packages = packages,
library = library
),
.timeout = .timeout,
.compute = private$.client$name
)
on.exit({
n <- length(.subset2(self, "tasks")) + 1L
private$.tasks[[n]] <- task
names(private$.tasks)[n] <- name
private$.pushed <- .subset2(self, "pushed") + 1L
})
if (scale) {
.subset2(self, "scale")(throttle = throttle)
}
invisible(task)
},
#' @description Apply a single command to multiple inputs,
#' and return control to the user without
#' waiting for any task to complete.
#' @details In contrast to `walk()`, `map()` blocks the local R session
#' and waits for all tasks to complete.
#' @return Invisibly returns a list of `mirai` task objects for the
#' newly created tasks. The order of tasks in the list matches the
#' order of data in the `iterate` argument.
#' @param command Language object with R code to run.
#' @param iterate Named list of vectors or lists to iterate over.
#' For example, to run function calls
#' `f(x = 1, y = "a")` and `f(x = 2, y = "b")`,
#' set `command` to `f(x, y)`, and set `iterate` to
#' `list(x = c(1, 2), y = c("a", "b"))`. The individual
#' function calls are evaluated as
#' `f(x = iterate$x[[1]], y = iterate$y[[1]])` and
#' `f(x = iterate$x[[2]], y = iterate$y[[2]])`.
#' All the elements of `iterate` must have the same length.
#' If there are any name conflicts between `iterate` and `data`,
#' `iterate` takes precedence.
#' @param data Named list of constant local data objects in the
#' evaluation environment. Objects in this list are treated as single
#' values and are held constant for each iteration of the map.
#' @param globals Named list of constant objects to temporarily
#' assign to the global environment for each task. This list should
#' include any functions you previously defined in the global
#' environment which are required to run tasks.
#' See the `reset_globals` argument of [crew_controller_local()].
#' Objects in this list are treated as single
#' values and are held constant for each iteration of the map.
#' @param substitute Logical of length 1, whether to call
#' `base::substitute()` on the supplied value of the
#' `command` argument. If `TRUE` (default) then `command` is quoted
#' literally as you write it, e.g.
#' `push(command = your_function_call())`. If `FALSE`, then `crew`
#' assumes `command` is a language object and you are passing its
#' value, e.g. `push(command = quote(your_function_call()))`.
#' `substitute = TRUE` is appropriate for interactive use,
#' whereas `substitute = FALSE` is meant for automated R programs
#' that invoke `crew` controllers.
#' @param seed Integer of length 1 with the pseudo-random number generator
#' seed to set for the evaluation of the task. Passed to the
#' `seed` argument of `set.seed()` if not `NULL`.
#' If `algorithm` and `seed` are both `NULL`,
#' then the random number generator defaults to the
#' recommended widely spaced worker-specific
#' L'Ecuyer streams as supported by `mirai::nextstream()`.
#' See `vignette("parallel", package = "parallel")` for details.
#' @param algorithm Integer of length 1 with the pseudo-random number
#' generator algorithm to set for the evaluation of the task.
#' Passed to the `kind` argument of `RNGkind()` if not `NULL`.
#' If `algorithm` and `seed` are both `NULL`,
#' then the random number generator defaults to the
#' recommended widely spaced worker-specific
#' L'Ecuyer streams as supported by `mirai::nextstream()`.
#' See `vignette("parallel", package = "parallel")` for details.
#' @param packages Character vector of packages to load for the task.
#' @param library Library path to load the packages. See the `lib.loc`
#' argument of `require()`.
#' @param seconds_timeout Optional task timeout passed to the `.timeout`
#' argument of `mirai::mirai()` (after converting to milliseconds).
#' @param names Optional character of length 1, name of the element of
#' `iterate` with names for the tasks. If `names` is supplied,
#' then `iterate[[names]]` must be a character vector.
#' @param save_command Logical of length 1, whether to store
#' a text string version of the R command in the output.
#' @param scale Logical, whether to automatically scale workers to meet
#' demand. See also the `throttle` argument.
#' @param throttle `TRUE` to skip auto-scaling if it already happened
#' within the last `seconds_interval` seconds. `FALSE` to auto-scale
#' every time `scale()` is called. Throttling avoids
#' overburdening the `mirai` dispatcher and other resources.
#' @param controller Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
walk = function(
command,
iterate,
data = list(),
globals = list(),
substitute = TRUE,
seed = NULL,
algorithm = NULL,
packages = character(0),
library = NULL,
seconds_timeout = NULL,
names = NULL,
save_command = FALSE,
scale = TRUE,
throttle = TRUE,
controller = NULL
) {
.subset2(self, "start")()
crew_assert(substitute, isTRUE(.) || isFALSE(.))
if (substitute) {
command <- substitute(command)
}
crew_assert(save_command, isTRUE(.) || isFALSE(.))
crew_assert(
iterate,
is.list(.),
rlang::is_named(.),
message = "the 'iterate' arg of map() must be a nonempty named list"
)
crew_assert(
length(iterate) > 0L,
message = "the \"iterate\" arg of map() must be a nonempty named list"
)
crew_assert(
length(unique(map_dbl(iterate, length))) == 1L,
message = "all elements of \"iterate\" must have the same length"
)
crew_assert(
length(iterate[[1L]]) > 0L,
message = "all elements of \"iterate\" must be nonempty"
)
crew_assert(
data,
is.list(.),
rlang::is_named(.) || length(.) < 1L,
message = "the \"data\" argument of map() must be a named list"
)
crew_assert(
globals,
is.list(.),
rlang::is_named(.) || length(.) < 1L,
message = "the \"globals\" argument of map() must be a named list"
)
crew_assert(
seed %|||% 1L,
is.integer(.),
length(.) == 1L,
!anyNA(seed),
message = "seed must be an integer of length 1"
)
crew_assert(
algorithm %|||% "Mersenne-Twister",
is.character(.),
length(.) == 1L,
!anyNA(.),
nzchar(.),
message = "algorithm must be a valid RNG algorithm name"
)
crew_assert(
packages,
is.character(.),
!anyNA(.),
message = "packages must be a character vector with no element missing"
)
crew_assert(
library %|||% "local",
is.character(.),
!anyNA(.),
message = "library must be a NULL or a non-missing character vector"
)
crew_assert(
names %|||% names(iterate)[[1L]],
is.character(.),
length(.) == 1L,
!anyNA(.),
nzchar(.),
. %in% names(iterate),
message = "names argument must be NULL or an element of names(iterate)"
)
crew_assert(scale, isTRUE(.) || isFALSE(.))
crew_assert(throttle, isTRUE(.) || isFALSE(.))
string <- if_any(save_command, deparse_safe(command), NA_character_)
.timeout <- if_any(
is.null(seconds_timeout),
NULL,
seconds_timeout * 1000
)
names <- if_any(
is.null(names),
as.character(seq_along(iterate[[1L]])),
iterate[[names]]
)
crew_assert(
anyDuplicated(names) < 1L,
message = "task names in map() must not have duplicates"
)
names_iterate <- names(iterate)
self$start()
sign <- if_any(!is.null(seed) && seed > 0L, 1L, -1L)
if (!is.null(seed)) {
seed <- 1L
}
tasks <- list()
for (index in seq_along(names)) {
for (name in names_iterate) {
data[[name]] <- .subset2(.subset2(iterate, name), index)
}
if (is.null(seed)) {
task_seed <- NULL
} else {
task_seed <- seed - (sign * index)
}
tasks[[index]] <- .subset2(private, ".shove")(
command = command,
string = string,
data = data,
globals = globals,
seed = task_seed,
algorithm = algorithm,
packages = packages,
library = library,
.timeout = .timeout,
name = .subset(names, index)
)
}
if (scale) {
.subset2(self, "scale")(throttle = throttle)
}
invisible(tasks)
},
#' @description Apply a single command to multiple inputs,
#' wait for all tasks to complete,
#' and return the results of all tasks.
#' @details `map()` cannot be used unless all prior tasks are
#' completed and popped. You may need to wait and then pop them
#' manually. Alternatively, you can start over: either call
#' `terminate()` on the current controller object to reset it, or
#' create a new controller object entirely.
#' @return A `tibble` of results and metadata: one row per task
#' and columns corresponding to the output of `pop()`.
#' @param command Language object with R code to run.
#' @param iterate Named list of vectors or lists to iterate over.
#' For example, to run function calls
#' `f(x = 1, y = "a")` and `f(x = 2, y = "b")`,
#' set `command` to `f(x, y)`, and set `iterate` to
#' `list(x = c(1, 2), y = c("a", "b"))`. The individual
#' function calls are evaluated as
#' `f(x = iterate$x[[1]], y = iterate$y[[1]])` and
#' `f(x = iterate$x[[2]], y = iterate$y[[2]])`.
#' All the elements of `iterate` must have the same length.
#' If there are any name conflicts between `iterate` and `data`,
#' `iterate` takes precedence.
#' @param data Named list of constant local data objects in the
#' evaluation environment. Objects in this list are treated as single
#' values and are held constant for each iteration of the map.
#' @param globals Named list of constant objects to temporarily
#' assign to the global environment for each task. This list should
#' include any functions you previously defined in the global
#' environment which are required to run tasks.
#' See the `reset_globals` argument of [crew_controller_local()].
#' Objects in this list are treated as single
#' values and are held constant for each iteration of the map.
#' @param substitute Logical of length 1, whether to call
#' `base::substitute()` on the supplied value of the
#' `command` argument. If `TRUE` (default) then `command` is quoted
#' literally as you write it, e.g.
#' `push(command = your_function_call())`. If `FALSE`, then `crew`
#' assumes `command` is a language object and you are passing its
#' value, e.g. `push(command = quote(your_function_call()))`.
#' `substitute = TRUE` is appropriate for interactive use,
#' whereas `substitute = FALSE` is meant for automated R programs
#' that invoke `crew` controllers.
#' @param seed Integer of length 1 with the pseudo-random number generator
#' seed to set for the evaluation of the task. Passed to the
#' `seed` argument of `set.seed()` if not `NULL`.
#' If `algorithm` and `seed` are both `NULL`,
#' then the random number generator defaults to the
#' recommended widely spaced worker-specific
#' L'Ecuyer streams as supported by `mirai::nextstream()`.
#' See `vignette("parallel", package = "parallel")` for details.
#' @param algorithm Integer of length 1 with the pseudo-random number
#' generator algorithm to set for the evaluation of the task.
#' Passed to the `kind` argument of `RNGkind()` if not `NULL`.
#' If `algorithm` and `seed` are both `NULL`,
#' then the random number generator defaults to the
#' recommended widely spaced worker-specific
#' L'Ecuyer streams as supported by `mirai::nextstream()`.
#' See `vignette("parallel", package = "parallel")` for details.
#' @param packages Character vector of packages to load for the task.
#' @param library Library path to load the packages. See the `lib.loc`
#' argument of `require()`.
#' @param seconds_interval Number of seconds to wait between auto-scaling
#' operations while waiting for tasks to complete.
#' @param seconds_timeout Optional task timeout passed to the `.timeout`
#' argument of `mirai::mirai()` (after converting to milliseconds).
#' @param names Optional character of length 1, name of the element of
#' `iterate` with names for the tasks. If `names` is supplied,
#' then `iterate[[names]]` must be a character vector.
#' @param save_command Logical of length 1, whether to store
#' a text string version of the R command in the output.
#' @param error Character of length 1, choice of action if
#' a task has an error. Possible values:
#' * `"stop"`: throw an error in the main R session instead of returning
#' a value. In case of an error, the results from the last errored
#' `map()` are in the `error` field
#' of the controller, e.g. `controller_object$error`. To reduce
#' memory consumption, set `controller_object$error <- NULL` after
#' you are finished troubleshooting.
#' * `"warn"`: throw a warning. This allows the return value with
#' all the error messages and tracebacks to be generated.
#' * `"silent"`: do nothing special.
#' @param warnings Logical of length 1, whether to throw a warning in the
#' interactive session if at least one task encounters an error.
#' @param verbose Logical of length 1, whether to print progress messages.
#' @param scale Logical, whether to automatically scale workers to meet
#' demand. See also the `throttle` argument.
#' @param throttle `TRUE` to skip auto-scaling if it already happened
#' within the last `seconds_interval` seconds. `FALSE` to auto-scale
#' every time `scale()` is called. Throttling avoids
#' overburdening the `mirai` dispatcher and other resources.
#' @param controller Not used. Included to ensure the signature is
#' compatible with the analogous method of controller groups.
map = function(
command,
iterate,
data = list(),
globals = list(),
substitute = TRUE,
seed = NULL,
algorithm = NULL,
packages = character(0),
library = NULL,
seconds_interval = 0.5,
seconds_timeout = NULL,
names = NULL,
save_command = FALSE,
error = "stop",
warnings = TRUE,
verbose = interactive(),
scale = TRUE,
throttle = TRUE,
controller = NULL
) {
crew_assert(
length(private$.tasks) < 1L,
message = "cannot map() until all prior tasks are completed and popped"
)
crew_assert(substitute, isTRUE(.) || isFALSE(.))
crew_assert(error %in% c("stop", "warn", "silent"))
if (substitute) {
command <- substitute(command)
}
self$walk(
command = command,
iterate = iterate,
data = data,
globals = globals,
substitute = FALSE,
seed = seed,
algorithm = algorithm,
packages = packages,
library = library,
seconds_timeout = seconds_timeout,
names = names,
save_command = save_command,
scale = scale,
throttle = throttle
)
names <- if_any(
is.null(names),
as.character(seq_along(iterate[[1L]])),
iterate[[names]]
)
tasks <- private$.tasks
total <- length(tasks)
relay <- .subset2(.subset2(self, "client"), "relay")
start <- nanonext::mclock()
pushed <- private$.pushed
this_envir <- environment()
progress_envir <- new.env(parent = this_envir)
if (verbose) {
cli::cli_progress_bar(
total = total,
type = "custom",
format = paste(
"{cli::pb_current}/{cli::pb_total}",
"{cli::pb_bar}",
"{cli::pb_percent}"
),
format_done = "{cli::pb_total} tasks in {cli::pb_elapsed}",
clear = FALSE,
.envir = progress_envir
)
}
crew_retry(
fun = ~{
if (scale) {
.subset2(self, "scale")(throttle = throttle)
}
unresolved <- .subset2(self, "unresolved")()
if (verbose) {
cli::cli_progress_update(
set = total - unresolved,
.envir = progress_envir
)
}
if (unresolved > 0L) {
.subset2(relay, "wait")(seconds_timeout = seconds_interval)
}
.subset2(self, "unresolved")() < 1L
},
seconds_interval = 0,
seconds_timeout = Inf,
error = FALSE
)
if (verbose) {
cli::cli_progress_done(.envir = progress_envir)
}
out <- list()
for (index in seq_along(tasks)) {
out[[length(out) + 1L]] <- as_monad(
task = tasks[[index]],
name = names[[index]]
)
}
out <- tibble::new_tibble(data.table::rbindlist(out, use.names = FALSE))
out <- out[match(x = names, table = out$name),, drop = FALSE] # nolint
out <- out[!is.na(out$name),, drop = FALSE] # nolint
worker <- .subset2(out, "worker")
tasks <- table(worker)
seconds <- tapply(
X = .subset2(out, "seconds"),
INDEX = worker,
FUN = sum
)
summary_errors <- tapply(
X = as.integer(!is.na(.subset2(out, "error"))),
INDEX = worker,
FUN = sum
)
summary_warnings <- tapply(
X = as.integer(!is.na(.subset2(out, "warnings"))),
INDEX = worker,
FUN = sum
)
index <- as.integer(names(tasks))
summary <- .subset2(private, ".summary")
on.exit({
private$.tasks <- list()
private$.popped <- .subset2(self, "popped") + total
private$.summary$tasks[index] <- .subset2(summary, "tasks")[index] +
tasks
private$.summary$seconds[index] <- .subset2(
summary, "seconds"
)[index] + seconds
private$.summary$errors[index] <- .subset2(summary, "errors")[index] +
summary_errors
private$.summary$warnings[index] <- .subset2(
summary, "warnings"
)[index] + summary_warnings
})
warning_messages <- .subset2(out, "warnings")
if (!all(is.na(warning_messages)) && isTRUE(warnings)) {
message <- sprintf(
paste(
"%s tasks encountered warnings.",
"Warning messages of first such task: \"%s\"."
),
sum(!is.na(warning_messages)),
warning_messages[min(which(!is.na(warning_messages)))]
)
crew_warning(message)
}
error_messages <- .subset2(out, "error")
if (!all(is.na(error_messages)) && !identical(error, "silent")) {
message <- sprintf(
"%s tasks encountered errors. First error message: \"%s\".",
sum(!is.na(error_messages)),
error_messages[min(which(!is.na(error_messages)))]
)
if (identical(error, "stop")) {
private$.error <- out
message <- paste(
message,
"\nSee the \"error\" field of your controller object",
"for all results, including warnings, tracebacks, all",
"error messages, etc."
)
crew_error(message)
} else {
crew_warning(message)
}
}
out
},
#' @description Pop a completed task from the results data frame.
#' @details If not task is currently completed, `pop()`
#' will attempt to auto-scale workers as needed.
#' @return If there is no task to collect, return `NULL`. Otherwise,
#' return a one-row `tibble` with the following columns.
#' * `name`: the task name if given.
#' * `command`: a character string with the R command if `save_command`
#' was set to `TRUE` in `push()`.
#' * `result`: a list containing the return value of the R command.
#' * `seconds`: number of seconds that the task ran.
#' * `seed`: the single integer originally supplied to `push()`,
#' `NA` otherwise. The pseudo-random number generator state