/
provenance.R
1201 lines (1063 loc) · 61.2 KB
/
provenance.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
#' An object to query, record and modify an edibble graph
#'
#' The Provenance contains a set of operations to manipulate the nodes and edges of
#' the edibble graph object.
#'
#' @param role The role for the node.
#' @param name The name of the node.
#' @param value The value of the node.
#' @param id The id of the corresponding node.
#' @param fid The factor id.
#' @param attrs The attributes.
#' @param abort Whether to abort.
#' @param return To return in "id" or "value" format.
#' @importFrom vctrs vec_is
#' @importFrom R6 R6Class
#' @export
Provenance <- R6::R6Class("Provenance",
public = list(
#' @description
#' Initialise function
#' @param graph An edibble graph.
initialize = function(graph = NULL) {
private$record_track_internal()
#self$add_tracker_to_set_fns(track_fns)
private$graph <- graph %||% empty_edibble_graph()
private$edbl_version <- packageVersion("edibble")
private$session_info <- utils::sessionInfo()
private$trail <- list(new_trackable())
},
# add_tracker_to_set_fns = function(fnames) {
# for(f in fnames) {
# b <- body(self[[f]])
# if(length(b) > 1) {
# body(self[[f]]) <- as.call(c(b[[1]], expression(private$record_track_internal()), b[2:length(b)]))
# }
# }
# },
#' @description
#' Set the title.
#' @param title The title of the experiment
set_title = function(title) {
private$record_track_internal()
title <- vctrs::vec_cast(title, character())
vctrs::vec_assert(title, character(), 1)
private$title <- title
},
#' @description
#' Set the name.
#' @param name The name of the edibble graph object.
set_name = function(name) {
private$record_track_internal()
name <- vctrs::vec_cast(name, character())
vctrs::vec_assert(name, character(), 1)
private$name <- name
},
#' @description
#' Set the validation.
#' @param validation The validation statement.
#' @param type The type of validation.
set_validation = function(validation, type = "rcrds") {
private$record_track_internal()
private$validation[[type]] <- validation
},
#' @description
#' Set the simulation process
#' @param name The name of the process
#' @param process A function to simulate the record
#' @param rcrds The record factor name simulating for.
set_simulate = function(name, process, rcrds) {
private$record_track_internal()
private$simulate[[name]] <- list(process = process,
rcrds = rcrds)
},
#' @description
#' Reactivate the graph in the provenance object.
#' @param design An edibble design
#' @param overwrite A vector of character to overwrite from the
#' supplied design object.
reactivate = function(design, overwrite = c("graph", "anatomy", "recipe", "validation", "simulate", "simualte_result")) {
#private$record_track_internal()
for(obj in overwrite) {
if(obj=="simulate_result") {
e <- private$simulate_result_env
rm(list = ls(envir = e, all.names = TRUE), envir = e)
list2env(design[[obj]], envir = e)
} else {
private[[obj]] <- design[[obj]]
}
}
},
#' @description
#' Deactivate the provenance object.
#' @param delete A vector of character to delete.
deactivate = function(delete = c("graph", "anatomy", "recipe", "validation")) {
#private$record_track_internal()
for(obj in delete) {
private[[obj]] <- NULL
}
},
#' @description
#' Get the id based on either the name of the factor node.
#' If none supplied then it will give all.
fct_id = function(name = NULL, role = NULL) {
fnodes <- self$fct_nodes
if(!is_null(role)) {
fnodes <- fnodes[fnodes$role %in% role, ]
}
name_to_id <- set_names(fnodes$id, fnodes$name)
name <- name %||% names(name_to_id)
unname(name_to_id[name])
},
#' @description
#' Get the factor parent ids
#' @param type The type of edge link.
fct_id_parent = function(id = NULL, role = NULL, type = NULL) {
private$node_id_parent_child(id = id, role = role, type = type, node = "factor", return = "parent")
},
#' @description
#' Get the factor child ids. If `role` is
#' supplied then the child has to fit `role`
fct_id_child = function(id = NULL, role = NULL) {
private$node_id_parent_child(id = id, role = role, node = "factor", return = "child")
},
#' @description
#' Get the factor ancestor ids
fct_id_ancestor = function(id = NULL, role = NULL) {
private$var_id_ancestor(id = id, role = role, node = "factor")
},
#' @description
#' Get the factor descendant ids
fct_id_descendant = function(id = NULL, role = NULL) {
private$var_id_descendant(id = id, role = role, node = "factor")
},
#' @description
#' Get the leave factor ids.
fct_id_leaves = function(role = NULL) {
fids <- self$fct_id(role = role)
has_child <- map_lgl(fids, function(id) length(self$fct_id_child(id = id)) > 0)
fids[!has_child]
},
#' @description
#' Get the id based on name of level node.
#' Assumes that level ids obtained are all from the same fid
lvl_id = function(value = NULL, role = NULL, fid = NULL) {
lnodes_list <- self$lvl_nodes
if(!is_null(role)) {
private$validate_role(role)
private$validate_id(fid, 1)
lnodes_list <- lnodes_list[as.character(self$fct_id(role = role))]
}
if(is_null(fid)) {
if(is_null(value)) {
# return all lvl ids
return(unlist(map(lnodes_list, function(x) x$id)))
} else {
fid_search <- as.integer(names(lnodes_list))
fid <- self$fct_id_from_lvl_values(value = value, fid_search = fid_search)
return(self$lvl_id(value = value, role = role, fid = fid))
}
} else {
private$validate_id(fid, 1)
lnodes <- lnodes_list[[as.character(fid)]]
if(!is_null(value)) {
#lnodes[match(value, lnodes$value), ]$id
lnodes[match(as.character(value), as.character(lnodes$value)), ]$id
} else {
lnodes$id
}
}
},
#' @description
#' Get the level parent ids
lvl_id_parent = function(id = NULL, role = NULL) {
private$node_id_parent_child(id = id, role = role, node = "level", return = "parent")
},
#' @description
#' Get the level child ids
lvl_id_child = function(id = NULL, role = NULL) {
private$node_id_parent_child(id = id, role = role, node = "level", return = "child")
},
#' @description
#' Get the level ancestor ids
lvl_id_ancestor = function(id = NULL, role = NULL) {
private$var_id_ancestor(id = id, role = role, node = "level")
},
#' @description
#' Find the factor id from level ids.
#' @param fid_search A vector of fids to search from.
fct_id_from_lvl_id = function(id = NULL, fid_search = NULL) {
lnodes_list <- self$lvl_nodes
if(!is_null(fid_search)) lnodes_list <- lnodes_list[as.character(fid_search)]
for(fname in names(lnodes_list)) {
if(all(id %in% lnodes_list[[fname]]$id)) return(as.integer(fname))
}
},
#' @description
#' Find the factor id from level values.
#' @param fid_search A vector of fids to search from.
fct_id_from_lvl_values = function(value = NULL, fid_search = NULL) {
lnodes_list <- self$lvl_nodes
if(!is_null(fid_search)) lnodes_list <- lnodes_list[fid_search]
for(fname in names(lnodes_list)) {
if(all(value %in% lnodes_list[[fname]]$value)) return(as.integer(fname))
}
},
#' @description
#' Find the level id from the given fid
lvl_id_from_fct_id = function(fid = NULL) {
lnodes_list <- self$lvl_nodes
lnodes_list[[as.character(fid)]]$id
},
#' @description
#' Get the factor names based on id or role
fct_names = function(id = NULL, role = NULL) {
fnodes <- self$fct_nodes
if(!is_null(role)) {
private$validate_role(role)
fnodes <- fnodes[fnodes$role %in% role, ]
}
id <- id %||% fnodes$id
fnodes[match(id, fnodes$id), ]$name
},
#' @description
#' Get the unit names
unit_names = function(id = NULL) {
self$fct_names(id = id, role = "edbl_unit")
},
#' @description
#' Get the treatment names
trt_names = function(id = NULL) {
self$fct_names(id = id, role = "edbl_trt")
},
#' @description
#' Get the record names.
rcrd_names = function(id = NULL) {
self$fct_names(id = id, role = "edbl_rcrd")
},
#' @description
#' Get the class for record with validation.
rcrd_class = function(name = NULL) {
map_chr(name,
function(x) {
vrcrds <- private$validation[["rcrds"]]
if(x %in% names(vrcrds)) return(vrcrds[[x]]$record)
NA_character_
})
},
#' @description
#' Get the level values based on id or role
#' cannot have just role only defined.
#' id must be from the same fid
lvl_values = function(id = NULL, role = NULL, fid = NULL) {
lnodes_list <- self$lvl_nodes
if(!is_null(fid)) {
private$validate_id(fid, 1, role = role)
lnodes <- lnodes_list[[as.character(fid)]]
id <- id %||% lnodes$id
return(lnodes[match(id, lnodes$id), ]$value)
}
if(!is_null(id)) {
fid <- self$fct_id_from_lvl_id(id = id)
self$lvl_values(id = id, role = role, fid = fid)
} else {
abort("`id` or `fid` must be provided.")
}
},
#' @description
#' Get the unit values.
unit_values = function(id = NULL, fid = NULL) {
self$lvl_values(id = id, role = "edbl_unit", fid = fid)
},
#' @description
#' Get the treatment values.
trt_values = function(id = NULL, fid = NULL) {
self$lvl_values(id = id, role = "edbl_trt", fid = fid)
},
#' @description
#' Get the record values.
#' @param uid The unit level id
rcrd_values = function(uid = NULL, fid = NULL) {
lnodes_list <- self$lvl_nodes
if(is_null(fid)) abort("The rcrd id must be supplied.")
private$validate_id(fid, 1, role = "edbl_rcrd")
uid_fct <- self$fct_id_child(id = fid, role = "edbl_unit")
lnodes <- lnodes_list[[as.character(uid_fct)]]
id <- uid %||% lnodes$id
return(lnodes[["attr"]][lnodes$id %in% id, self$fct_names(id = fid)])
},
#' @description
#' Get the role of the vertex given the factor id
fct_role = function(id = NULL) {
fnodes <- self$fct_nodes
id <- id %||% fnodes$id
fnodes[match(id, fnodes$id), ]$role
},
#' @description
#' Get the levels for each factor
fct_levels = function(id = NULL, name = NULL, return = c("id", "value")) {
return <- match.arg(return)
qid <- id %||% self$fct_id(name = name)
lnodes <- self$lvl_nodes
switch(return,
id = lapply(unclass(lnodes[as.character(qid)]), function(x) x$id),
value = {
out <- lapply(unclass(lnodes[as.character(qid)]), function(x) x$value)
names(out) <- self$fct_names(id = qid)
out
})
},
#' @description
#' Factor levels to edble factor
#' @param fct_levels The factor levels in id.
fct_levels_id_to_edbl_fct = function(fct_levels, role) {
ret <- lapply(names(fct_levels), function(fid) {
lvls <- fct_levels[[fid]]
fid <- as.numeric(fid)
fname <- self$fct_names(id = fid)
lvls_value <- self$lvl_values(id = lvls, fid = fid)
new_edibble_fct(labels = lvls_value,
name = fname,
class = role)
})
names(ret) <- self$fct_names(id = as.numeric(names(fct_levels)))
ret
},
#' @description
#' Get the factor levels in value given id format
#' @param fct_levels A list of factor levels in id format.
fct_levels_id_to_value = function(fct_levels) {
out <- lapply(names(fct_levels), function(fid) {
lvls <- fct_levels[[fid]]
self$lvl_values(id = lvls, fid = as.numeric(fid))
})
names(out) <- self$fct_names(id = as.numeric(names(fct_levels)))
out
},
#' @description
#' Get the factor levels in id given value format.
#' @param fct_levels A list of factor levels in id format.
fct_levels_value_to_id = function(fct_levels) {
out <- lapply(names(fct_levels), function(fname) {
lvls <- fct_levels[[fname]]
self$lvl_id(value = lvls, fid = self$fct_id(name = fname))
})
names(out) <- self$fct_id(name = names(fct_levels))
out
},
#' @description
#' One of `name`, `id` or `role` is defined to check if it exists.
#' If more than one of the arguments `name`, `id` and `role` are supplied, then
#' the intersection of it will be checked.
fct_exists = function(id = NULL, name = NULL, role = NULL, abort = TRUE) {
exist <- TRUE
abort_missing <- function(vars = NULL, msg = NULL) {
if(abort & !exist) {
abort(msg)
}
}
msg_vars_missing <- function(vars, post_msg) {
sprintf(paste0("%s ", post_msg),
.combine_words(paste0("`", vars, "`")))
}
fnodes <- self$fct_nodes
# at least one node exists
if(is_null(name) & is_null(id) & is_null(role)) {
exist <- nrow(fnodes) > 0
abort_missing(msg = "There are no factor nodes.")
} else if(!is_null(name) & is_null(id) & is_null(role)) {
vexist <- name %in% fnodes$name
exist <- all(vexist)
abort_missing(vars = name[!vexist],
msg = msg_vars_missing(name[!vexist], "does not exist in the design."))
} else if(is_null(name) & !is_null(id) & is_null(role)) {
vexist <- id %in% fnodes$id
exist <- all(vexist)
abort_missing(vars = id[!vexist],
msg = msg_vars_missing(id[!vexist], "does not exist in the design."))
} else if(is_null(name) & is_null(id) & !is_null(role)) {
exist <- any(role %in% fnodes$role)
abort_missing(msg = sprintf("There are no factors with role %s",
.combine_words(paste0("`", role, "`"))))
} else if(is_null(name) & !is_null(id) & !is_null(role)) {
srole <- fnodes[match(id, fnodes$id), "role", drop = TRUE]
vexist <- srole %in% role
exist <- all(vexist)
abort_missing(vars = id[!vexist],
msg = msg_vars_missing(id[!vexist], "doesn't exist or don't have the specified role."))
} else if(!is_null(name) & is_null(id) & !is_null(role)) {
srole <- fnodes[match(name, fnodes$name), "role", drop = TRUE]
vexist <- srole %in% role
exist <- all(vexist)
abort_missing(vars = name[!vexist],
msg = msg_vars_missing(name[!vexist], "doesn't exist or don't have the specified role."))
} else if(!is_null(name) & !is_null(id) & is_null(role)) {
sid <- fnodes[match(name, fnodes$name), "id", drop = TRUE]
vexist <- sid %in% id
exist <- all(vexist)
abort_missing(vars = name[!vexist],
msg = msg_vars_missing(name[!vexist], "doesn't exist or have a specified id."))
} else {
snodes <- fnodes[match(name, fnodes$name), ]
vexist <- snodes$id %in% id & snodes$role %in% role
exist <- all(vexist)
abort_missing(vars = name[!vexist],
msg = msg_vars_missing(name[!vexist], "doesn't exist or have a specified id or role."))
}
return(exist)
},
#' @description
#' Check if treatment exists.
trt_exists = function(id = NULL, name = NULL, abort = TRUE) {
self$fct_exists(id = id, name = name, role = "edbl_trt", abort = abort)
},
#' @description
#' Check if unit exists.
unit_exists = function(id = NULL, name = NULL, abort = TRUE) {
self$fct_exists(id = id, name = name, role = "edbl_unit", abort = abort)
},
#' @description
#' Check if record exists.
rcrd_exists = function(id = NULL, name = NULL, abort = TRUE) {
self$fct_exists(id = id, name = name, role = "edbl_rcrd", abort = abort)
},
#lvl_exists = function(id = NULL, value = NULL, fid = NULL, abort = TRUE) {
# FIXME
#},
#' @description
#' Given node data, append the factor nodes
append_fct_nodes = function(name, role, attrs = NULL) {
private$record_track_internal()
fnodes <- self$fct_nodes
n <- length(name)
role <- vctrs::vec_recycle(role, n)
data <- tibble::tibble(id = private$fct_new_id(n = n),
role = role,
name = name)
out <- rbind_(fnodes[setdiff(names(fnodes), "attrs")], data)
out_attrs <- rbind_(fnodes$attrs, attrs %||% data.frame())
if(nrow(out_attrs) < nrow(out)) {
out_attrs <- data.frame(row.names = nrow(out))
}
out$attrs <- out_attrs
self$fct_nodes <- out
},
#' @description
#' Given node data, append the level nodes
#' @param n The number of replications.
#' @param label The labels for the levels.
append_lvl_nodes = function(value, n = NULL, label = NULL, attrs = NULL, fid = NULL) {
private$record_track_internal()
lnodes <- self$lvl_nodes
id <- private$lvl_new_id(n = length(value))
if(is_null(n) & is_null(label)) {
data <- tibble::tibble(id = id, value = value, attrs = attrs)
} else if(!is_null(n) & is_null(label)) {
data <- tibble::tibble(id = id, value = value, n = n, attrs = attrs)
} else if(is_null(n) & !is_null(label)) {
data <- tibble::tibble(id = id, value = value, label = label, attrs = attrs)
} else if(!is_null(n) & !is_null(label)) {
data <- tibble::tibble(id = id, value = value, n = n, label = label, attrs = attrs)
}
if(is.null(lnodes[[as.character(fid)]])) {
lnodes[[as.character(fid)]] <- data
} else {
lnodes[[as.character(fid)]] <- rbind_(lnodes[[as.character(fid)]], data)
}
self$lvl_nodes <- lnodes
},
#' @description
#' Given edge data, append the factor edges
#' @param from The node id from.
#' @param to The node id to.
#' @param type The type of edges.
#' @param group A logical value to indicate whether to create new group id or not.
append_fct_edges = function(from, to, type = NULL, group = FALSE, attrs = NULL) {
private$record_track_internal()
if(group) {
group_id <- private$allot_id_last + 1L
private$allot_id_last <- private$allot_id_last + 1L
} else group_id <- NULL
self$fct_edges <- rbind_(self$fct_edges, tibble::tibble(from = from,
to = to,
type = type,
group = group_id,
attrs = attrs))
},
#' @description
#' Given edge data, append the level edges
#' @param from The node id from.
#' @param to The node id to.
append_lvl_edges = function(from, to, attrs = NULL) {
private$record_track_internal()
self$lvl_edges <- rbind_(self$lvl_edges, tibble::tibble(from = from,
to = to,
attrs = attrs))
},
#' @description
#' Serve the units.
serve_units = function(id = NULL, return = c("id", "value")) {
return <- match.arg(return)
self$fct_exists(id = id, role = "edbl_unit")
id <- id %||% self$fct_id(role = "edbl_unit")
if(length(id) == 0) abort("There needs to be at least one unit supplied.")
id_ancestors <- self$fct_id_ancestor(id = id, role = "edbl_unit")
sub_graph <- self$graph_subset(id = id_ancestors, include = "self")
out <- private$build_subtable(sub_graph, return = "id")
private$table$units <- out
switch(return,
id = out,
value = self$fct_levels_id_to_edbl_fct(out, role = "edbl_unit"))
},
#' @description
#' Serve treatments
serve_trts = function(id = NULL, return = c("id", "value")) {
return <- match.arg(return)
lnodes <- self$lvl_nodes
ledges <- self$lvl_edges
serve_trt = function(fid) {
# linked unit -
# each treatment factor should only be applied to a single unit factor
uid <- self$fct_id_child(id = fid, role = "edbl_unit")
vctrs::vec_assert(uid, integer(), size = 1)
if(!uid %in% as.integer(names(private$table$units))) self$serve_units(id = uid)
tids <- self$lvl_id(fid = fid, role = "edbl_trt")
uids <- private$table$units[[as.character(uid)]]
ledges <- ledges[ledges$to %in% uids & ledges$from %in% tids, ]
ledges[match(uids, ledges$to), ]$from
}
id <- id %||% self$trt_ids
out <- lapply(id, serve_trt)
names(out) <- as.character(id)
private$table$trts <- out
switch(return,
id = out,
value = self$fct_levels_id_to_edbl_fct(out, role = "edbl_trt"))
},
#' @description
#' Serve records
serve_rcrds = function(id = NULL, return = c("id", "value")) {
id <- id %||% self$rcrd_ids
return <- match.arg(return)
out <- lapply(id, function(rid) {
uid <- self$fct_id_child(id = rid, role = "edbl_unit")
# should be only a single unit factor
vctrs::vec_assert(uid, integer(), size = 1)
if(!uid %in% as.integer(names(private$table$units))) self$serve_units(id = uid)
uid
})
names(out) <- as.character(id)
switch(return,
id = out,
value = {
N <- max(lengths(private$table$units))
lvs <- lapply(id, function(rid) {
uid <- out[[as.character(rid)]]
uids <- private$table$units[[as.character(uid)]]
new_edibble_rcrd(rep(NA_real_, N), uids)
})
names(lvs) <- self$fct_names(id = id)
lvs
})
},
#' @description
#' Make the treatments table
#' @return A treatment table
make_trts_table = function(id = NULL, return = c("id", "value")) {
id <- id %||% self$trt_ids
return <- match.arg(return)
self$fct_exists(id = id, role = "edbl_trt")
fnodes <- self$fct_graph_components(id = id)
ncomp <- length(unique(fnodes$component))
scomps <- split(fnodes$id, fnodes$component)
if(ncomp == length(id)) {
trts_list <- self$fct_levels(id = id, return = return)
trts_tbl <- expand.grid(trts_list, stringsAsFactors = FALSE)
} else {
for(i in seq(ncomp)) {
if(i == 1L) {
sub_graph <- self$graph_subset(id = scomps[[i]], include = "self")
trts_tbl <- private$build_condtable(sub_graph, return = return)
} else {
sub_graph <- self$graph_subset(id = scomps[[i]], include = "self")
new_trts_tbl <- private$build_condtable(sub_graph, return = return)
xtabs <- expand.grid(old = seq(nrow(trts_tbl)), new = seq(nrow(new_trts_tbl)))
trts_tbl <- cbind(trts_tbl[xtabs[[1]], , drop = FALSE], new_trts_tbl[xtabs[[2]], , drop = FALSE])
}
}
}
rownames(trts_tbl) <- NULL
switch(return,
id = trts_tbl[as.character(id)],
value = trts_tbl[self$fct_names(id = id)])
},
#' @description
#' Subset graph
#' @param include "self" for only input id, "child" for child also,
#' "parent" for parent also,
#' nodes immediately related, and "ancestors" for all ancestors
#' @return subsetted graph
graph_subset = function(id = NULL, include = c("self", "child", "parent", "ancestors")) {
include <- match.arg(include)
idx <- switch(include,
"self" = id,
"child" = c(id, self$fct_id_child(id = id)),
"parent" = c(id, self$fct_id_parent(id = id)),
"ancestors" = unique(c(id, self$fct_id_ancestor(id = id))))
fnodes <- self$fct_nodes
fedges <- self$fct_edges
lnodes <- self$lvl_nodes
ledges <- self$lvl_edges
# subset
fnodes <- fnodes[fnodes$id %in% idx, ]
fedges <- fedges[fedges$from %in% idx & fedges$to %in% idx, ]
lnodes <- lnodes[as.character(fnodes$id)]
lnodes_id <- unlist(lapply(lnodes, function(x) x$id))
ledges <- ledges[ledges$from %in% lnodes_id & ledges$to %in% lnodes_id, ]
new_edibble_graph(fnodes, lnodes, fedges, ledges)
},
#' @description
#' Save the seed
#' @param seed A seed.
#' @param type Type.
save_seed = function(seed, type) {
private$record_track_internal()
ranexists <- exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)
if(!ranexists) stats::runif(1)
if(is.null(seed)) {
RNGstate <- get(".Random.seed", envir = .GlobalEnv)
} else {
set.seed(seed)
RNGstate <- structure(seed, kind = as.list(RNGkind()))
}
private$seed[[type]] <- RNGstate
},
#' @description
#' Get the title
get_title = function() {
private$title
},
#' @description
#' Get the validation
#' @param type A type.
get_validation = function(type = NULL) {
if(is_null(type)) return(private$validation)
private$validation[[type]]
},
#' @description
#' Get the trail.
get_trail = function() {
private$trail[-length(private$trail)]
},
#' @description
#' Get the graph
get_graph = function() {
private$graph
},
#' @description
#' Get the seed
get_seed = function() {
private$seed
},
#' @description
#' Get the session information
get_session_info = function() {
private$session_info
},
#' @description
#' Get the edibble version.
get_edibble_version = function() {
private$edibble_version
},
#' @description
#' Get the simulation information
#' @param name The process name. Only one name allowed.
get_simulate = function(name = NULL) {
if(is_null(name)) return(private$simulate)
private$simulate[[name]]
},
#' @description
#' Get the simulation results
#' @param name The process name. Only one name allowed.
get_simulate_result_env = function(name = NULL) {
if(is_null(name)) return(private$simulate_result_env)
private$simulate_result_env[[name]]
},
#' @description
#' Mapping of a role to role
#' @param role_from The role from.
#' @param role_to The role to.
mapping = function(role_from, role_to) {
ids <- self$fct_id(role = role_from)
out <- map_int(ids, function(id_from) {
id_to <- self$fct_id_child(id = id_from, role = role_to)
vctrs::vec_assert(id_to, integer(), size = 1)
id_to
})
names(out) <- ids
out
},
#' @description
#' Mapping of an id to a unit
mapping_to_unit = function(id = NULL) {
self$fct_id_child(id = id, role = "edbl_unit")
},
#' @description
#' Record step.
record_step = function() {
do.call("on.exit",
list(quote(return(add_edibble_code(returnValue(default = FALSE),
paste(gsub("(^ +| +$)", "", deparse(match.call())), collapse = "")))),
add = TRUE),
envir = parent.frame())
},
#' @description
#' Get the level edges by factor
#' @param from,to The factor id.
lvl_mapping = function(from, to, return = c("vector", "table")) {
return <- match.arg(return)
lnodes <- self$lvl_nodes
nodes_from <- lnodes[[as.character(from)]]$id
nodes_to <- lnodes[[as.character(to)]]$id
ledges <- self$lvl_edges
map <- subset(ledges, from %in% nodes_from & to %in% nodes_to,
select = c(from, to))
if(return=="vector") return(setNames(map$to, map$from))
map
},
#' @description
#' Record track external.
#' @param code The code to record.
record_track_external = function(code) {
ncmds <- length(private$trail)
attr(private$trail[[ncmds]], "external_cmd") <- code
attr(private$trail[[ncmds]], "execution_time") <- Sys.time()
attr(private$trail[[ncmds]], "time_zone") <- Sys.timezone()
private$trail[[ncmds + 1]] <- new_trackable()
},
#' @description
#' Find all id that is linked.
#' @param link Whether the link should be direct or indirect
#' @return id of linked factors, excluding itself.
fct_id_links = function(id = NULL, role = NULL, link = c("direct", "indirect")) {
link <- match.arg(link)
if(link == "direct") {
cid <- self$fct_id_child(id = id, role = role)
pid <- self$fct_id_parent(id = id, role = role)
}
if(link == "indirect") {
cid <- self$fct_id_ancestor(id = id, role = role)
pid <- self$fct_id_descendant(id = id, role = role)
}
return(c(cid, pid))
},
#' @description
#' Get the nodes with components (subgraph number)
fct_graph_components = function(id = NULL) {
fnodes <- self$fct_nodes
fnodes <- fnodes[fnodes$id %in% id, ]
fedges <- self$fct_edges
fedges <- fedges[fedges$to %in% fnodes$id & fedges$from %in% fnodes$id, ]
fnodes$component <- NA_integer_
label_component <- function(fnodes, comp) {
id <- fnodes$id[is.na(fnodes$component)][1]
pids <- self$fct_id_ancestor(id = id)
cids <- self$fct_id_descendant(id = id)
fnodes$component[match(c(pids, cids), fnodes$id)] <- comp
fnodes
}
comp <- 0L
while(any(is.na(fnodes$component))) {
comp <- comp + 1L
fnodes <- label_component(fnodes, comp)
}
fnodes
},
#' @description
#' Get the nodes with components (subgraph number)
lvl_graph_components = function() {
lnodes <- self$lvl_nodes
ledges <- self$lvl_edges
lnodes$component <- NA_integer_
label_component <- function(comp) {
id <- lnodes$id[is.na(lnodes$component)][1]
pids <- self$lvl_id_ancestor(id = id)
cids <- self$lvl_id_descendant(id = id)
lnodes$component[match(c(pids, cids), lnodes$id)] <- comp
lnodes
}
comp <- 0L
while(any(is.na(lnodes$component))) {
comp <- comp + 1L
lnodes <- label_component(comp)
}
lnodes
}
),
active = list(
#' @field fct_nodes
#' Get the factor nodes
fct_nodes = function(data) {
if(missing(data)) return(private$graph$factors$nodes)
else private$graph$factors$nodes <- data
},
#' @field lvl_nodes
#' Get the level nodes
lvl_nodes = function(data) {
if(missing(data)) {
nodes <- private$graph$levels$nodes
return(nodes)
}
else private$graph$levels$nodes <- data
},
#' @field fct_edges
#' Get the factor edges
fct_edges = function(data) {
if(missing(data)) {
edges <- private$graph$factors$edges
edges$var_from <- self$fct_names(id = edges$from)
edges$var_to <- self$fct_names(id = edges$to)
return(edges)
} else {
private$graph$factors$edges <- data
}
},
#' @field lvl_edges
#' Get the level edges
lvl_edges = function(data) {
if(missing(data)) {
edges <- private$graph$levels$edges
return(edges)
} else {
private$graph$levels$edges <- data
}
},
#' @field fct_n
#' Get the number of nodes in factor graph
fct_n = function(value) {
if (missing(value)) {
nrow(self$fct_nodes)
} else {
stop("Can't set `$fct_n`.")
}
},
#' @field lvl_n
#' Get the number of nodes in level graph
lvl_n = function(value) {
if (missing(value)) {
sum(lengths(self$lvl_nodes))
} else {
stop("Can't set `$lvl_n`.")
}
},
#' @field rcrd_ids
#' Get the ids for all edbl_rcrd factors.
rcrd_ids = function() {
self$fct_id(role = "edbl_rcrd")
},
#' @field unit_ids
#' Get the ids for all edbl_unit factors.
unit_ids = function() {
self$fct_id(role = "edbl_unit")
},
#' @field trt_ids
#' Get the ids for all edbl_trt factors.
trt_ids = function() {
self$fct_id(role = "edbl_trt")
},
#' @field is_connected
#' Check if nodes are connected.
is_connected = function() {
# FIXME: use lvl_graph_components instead
nvar <- self$fct_n - length(self$rcrd_ids)
if(nvar==0) return(FALSE)
if(nvar==1) return(TRUE)
ledges <- self$lvl_edges
all(self$lvl_id() %in% c(ledges$to, ledges$from))
}
),
private = list(
fct_id_last = 0L,
lvl_id_last = 0L,
allot_id_last = 0L,