-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathTileDBArray.R
More file actions
2473 lines (2261 loc) · 92.3 KB
/
TileDBArray.R
File metadata and controls
2473 lines (2261 loc) · 92.3 KB
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
# MIT License
#
# Copyright (c) 2017-2025 TileDB Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#' An S4 class for a TileDB Array
#'
#' This class replaces the earlier (and now removed) \code{tiledb_dense}
#' and \code{tiledb_sparse} and provides equivalent functionality
#' based on a refactored implementation utilising newer TileDB features.
#'
#' @slot ctx A TileDB context object
#' @slot uri A character description with the array URI
#' @slot is.sparse A logical value whether the array is sparse or not
#' @slot attrs A character vector to select particular column
#' \sQuote{attributes}; default is an empty character vector implying
#' \sQuote{all} columns, the special value \code{NA_character_} has the opposite
#' effect and selects \sQuote{none}.
#' @slot extended A logical value, defaults to \code{TRUE}, indicating whether
#' index columns are returned as well.
#' @slot selected_ranges An optional list with matrices where each matrix i
#' describes the (min,max) pair of ranges for dimension i
#' @slot selected_points An optional list with vectors where each vector i
#' describes the selected points for dimension i
#' @slot query_layout An optional character value
#' @slot datetimes_as_int64 A logical value
#' @slot encryption_key A character value
#' @slot query_condition A Query Condition object
#' @slot timestamp_start A POSIXct datetime variable for the inclusive
#' interval start
#' @slot timestamp_end A POSIXct datetime variable for the inclusive
#' interval start
#' @slot return_as A character value with the desired \code{tiledb_array}
#' conversion, permitted values are \sQuote{asis} (default, returning a list
#' of columns), \sQuote{array}, \sQuote{matrix},\sQuote{data.frame},
#' \sQuote{data.table} \sQuote{tibble}, \sQuote{arrow_table} or \sQuote{arrow}
#' (where the last two are synonyms); note that \sQuote{data.table},
#' \sQuote{tibble} and \sQuote{arrow} require the respective packages
#' to be installed.
#' @slot query_statistics A logical value, defaults to \sQuote{FALSE}; if
#' \sQuote{TRUE} the query statistics are returned (as a JSON string) via the
#' attribute \sQuote{query_statistics} of the return object.
#' @slot sil An optional and internal list object with schema information, used
#' for parsing queries.
#' @slot dumpbuffers An optional character variable with a directory name
#' (relative to \code{/dev/shm}) for writing out results buffers (for internal
#' use / testing)
#' @slot buffers An optional list with full pathnames of shared memory buffers
#' to read data from
#' @slot strings_as_factors An optional logical to convert character columns to
#' factor type
#' @slot keep_open An optional logical to not close after read or write
#' @slot ptr External pointer to the underlying implementation
#' @exportClass tiledb_array
setClass(
"tiledb_array",
slots = list(
ctx = "tiledb_ctx",
uri = "character",
is.sparse = "logical",
attrs = "character",
extended = "logical",
selected_ranges = "list",
selected_points = "list",
query_layout = "character",
datetimes_as_int64 = "logical",
encryption_key = "character",
query_condition = "tiledb_query_condition",
timestamp_start = "POSIXct",
timestamp_end = "POSIXct",
return_as = "character",
query_statistics = "logical",
strings_as_factors = "logical",
keep_open = "logical",
sil = "list",
dumpbuffers = "character",
buffers = "list",
ptr = "externalptr"
)
)
#' Constructs a tiledb_array object backed by a persisted tiledb array uri
#'
#' tiledb_array returns a new object. This class is experimental.
#'
#' @param uri uri path to the tiledb array
#' @param query_type optionally loads the array in "READ" or "WRITE" only modes.
#' @param is.sparse optional logical switch, defaults to "NA"
#' letting array determine it
#' @param attrs optional character vector to select attributes, default is
#' empty implying all are selected, the special value \code{NA_character_}
#' has the opposite effect and implies no attributes are returned.
#' @param extended optional logical switch selecting wide \sQuote{data.frame}
#' format, defaults to \code{TRUE}
#' @param selected_ranges optional A list with matrices where each matrix i
#' describes the (min,max) pair of ranges selected for dimension i
#' @param selected_points optional A list with vectors where each vector i
#' describes the points selected in dimension i
#' @param query_layout optional A value for the TileDB query layout, defaults to
#' an empty character variable indicating no special layout is set
#' @param datetimes_as_int64 optional A logical value selecting date and
#' datetime value representation as \sQuote{raw} \code{integer64} and not as
#' \code{Date}, \code{POSIXct} or \code{nanotime} objects.
#' @param encryption_key optional A character value with an AES-256 encryption
#' key in case the array was written with encryption.
#' @param query_condition optional \code{tiledb_query_condition} object, by
#' default uninitialized without a condition; this functionality requires
#' TileDB 2.3.0 or later
#' @param timestamp_start optional A POSIXct Datetime value determining the
#' inclusive time point at which the array is to be opened. No fragments
#' written earlier will be considered.
#' @param timestamp_end optional A POSIXct Datetime value determining the
#' inclusive time point until which the array is to be opened. No fragments
#' written earlier later be considered.
#' @param return_as optional A character value with the desired
#' \code{tiledb_array} conversion, permitted values are \sQuote{asis} (default,
#' returning a list of columns), \sQuote{array}, \sQuote{matrix},
#' \sQuote{data.frame}, \sQuote{data.table}, \sQuote{tibble},
#' \sQuote{arrow_table}, or \sQuote{arrow} (as an alias for
#' \sQuote{arrow_table}; here \sQuote{data.table}, \sQuote{tibble} and
#' \sQuote{arrow} require the respective packages to be installed.
#' The existing \code{as.*} arguments take precedent over this.
#' @param query_statistics optional A logical value, defaults to \sQuote{FALSE};
#' if \sQuote{TRUE} the query statistics are returned (as a JSON string) via
#' the attribute \sQuote{query_statistics} of the return object.
#' @param strings_as_factors An optional logical to convert character columns to
#' factor type; defaults to the value of
#' \code{getOption("stringsAsFactors", FALSE)}.
#' @param keep_open An optional logical to not close after read or write
#' @param sil optional A list, by default empty to store schema information
#' when query objects are parsed.
#' @param dumpbuffers An optional character variable with a directory name
#' (relative to \code{/dev/shm}) for writing out results buffers (for
#' internal use / testing)
#' @param buffers An optional list with full pathnames of shared memory buffers
#' to read data from
#' @param ctx optional tiledb_ctx
#' @param as.data.frame An optional deprecated alternative to
#' \code{return_as="data.frame"} which has been deprecated and removed, but is
#' still used in one BioConductor package; this argument will be removed
#' once the updated package has been released.
#' @return tiledb_array object
#' @importFrom spdl set_level
#' @export
tiledb_array <- function(
uri,
query_type = c("READ", "WRITE"),
is.sparse = NA,
attrs = character(),
extended = TRUE,
selected_ranges = list(),
selected_points = list(),
query_layout = character(),
datetimes_as_int64 = FALSE,
encryption_key = character(),
query_condition = new("tiledb_query_condition"),
timestamp_start = as.POSIXct(double(), origin = "1970-01-01"),
timestamp_end = as.POSIXct(double(), origin = "1970-01-01"),
return_as = get_return_as_preference(),
query_statistics = FALSE,
strings_as_factors = getOption("stringsAsFactors", FALSE),
keep_open = FALSE,
sil = list(),
dumpbuffers = character(),
buffers = list(),
ctx = tiledb_get_context(),
as.data.frame = FALSE
) {
stopifnot(
"Argument 'ctx' must be a tiledb_ctx object" = is(ctx, "tiledb_ctx"),
"Argument 'uri' must be a string scalar" = !missing(uri) && is.scalar(uri, "character"),
"Argument 'matrix' (for 'return_as') cannot be selected for sparse arrays" =
!(isTRUE(is.sparse) && return_as == "matrix")
)
query_type <- match.arg(query_type)
spdl::debug("[tiledb_array] query is {}", query_type)
if (length(encryption_key) > 0) {
stopifnot("if used, argument aes_key must be character" = is.character(encryption_key))
array_xptr <- libtiledb_array_open_with_key(ctx@ptr, uri, query_type, encryption_key)
} else {
array_xptr <- libtiledb_array_open(ctx@ptr, uri, query_type)
}
if (as.data.frame) {
## accommodating TileDBArray prior to BioConductor 3.20
.Deprecated(old = "as.data.frame", new = r"(return_as="data.frame")")
return_as <- "data.frame"
}
if (length(timestamp_start) > 0) {
libtiledb_array_set_open_timestamp_start(array_xptr, timestamp_start)
}
if (length(timestamp_end) > 0) {
libtiledb_array_set_open_timestamp_end(array_xptr, timestamp_end)
}
schema_xptr <- libtiledb_array_get_schema(array_xptr)
is_sparse_status <- libtiledb_array_schema_sparse(schema_xptr)
if (!is.na(is.sparse) && is.sparse != is_sparse_status) {
libtiledb_array_close(array_xptr)
if (is_sparse_status) {
stop("dense array selected but sparse array found", call. = FALSE)
} else {
stop("sparse array selected but dense array found", call. = FALSE)
}
}
is.sparse <- is_sparse_status
if (!keep_open) array_xptr <- libtiledb_array_close(array_xptr)
new("tiledb_array",
ctx = ctx,
uri = uri,
is.sparse = is.sparse,
attrs = attrs,
extended = extended,
selected_ranges = selected_ranges,
selected_points = selected_points,
query_layout = query_layout,
datetimes_as_int64 = datetimes_as_int64,
encryption_key = encryption_key,
query_condition = query_condition,
timestamp_start = timestamp_start,
timestamp_end = timestamp_end,
return_as = return_as,
query_statistics = query_statistics,
strings_as_factors = strings_as_factors,
keep_open = keep_open,
sil = sil,
dumpbuffers = dumpbuffers,
buffers = buffers,
ptr = array_xptr
)
}
#' Return a schema from a tiledb_array object
#'
#' @param object tiledb array object
#' @param ... Extra parameter for function signature, currently unused
#' @return The schema for the object
setMethod("schema", "tiledb_array", function(object, ...) {
ctx <- object@ctx
uri <- object@uri
enckey <- object@encryption_key
if (length(enckey) > 0) {
schema_xptr <- libtiledb_array_schema_load_with_key(ctx@ptr, uri, enckey)
} else {
schema_xptr <- libtiledb_array_schema_load(ctx@ptr, uri)
}
return(tiledb_array_schema.from_ptr(schema_xptr, object@ptr))
})
## unexported helper function to deal with ... args / enckey in next method
.array_schema_load <- function(ctxptr, uri, enckey = character()) {
if (length(enckey) > 0) {
schema_xptr <- libtiledb_array_schema_load_with_key(ctxptr, uri, enckey)
} else {
schema_xptr <- libtiledb_array_schema_load(ctxptr, uri)
}
}
.array_open <- function(ctxptr, uri, enckey = character()) {
if (length(enckey) > 0) {
arr_xptr <- libtiledb_array_open_with_key(ctxptr, uri, "READ", enckey)
} else {
arr_xptr <- libtiledb_array_open(ctxptr, uri, "READ")
}
}
#' Return a schema from a URI character value
#'
#' @param object A character variable with a URI
#' @param ... Extra parameters such as \sQuote{enckey}, the encryption key
#' @return The schema for the object
setMethod("schema", "character", function(object, ...) {
ctx <- tiledb_get_context()
schema_xptr <- .array_schema_load(ctx@ptr, object, ...)
array_xptr <- .array_open(ctx@ptr, object, ...)
return(tiledb_array_schema.from_ptr(schema_xptr, array_xptr))
})
#' Prints a tiledb_array object
#'
#' @param object A tiledb array object
#' @export
setMethod(
"show",
signature = "tiledb_array",
definition = function(object) {
cat("tiledb_array\n",
" uri = '", object@uri, "'\n",
" schema_version = ", tiledb_array_schema_version(schema(object)), "\n",
" is.sparse = ", if (object@is.sparse) "TRUE" else "FALSE", "\n",
" attrs = ", if (length(object@attrs) == 0) {
"(none)"
} else {
paste(object@attrs, collapse = ",")
}, "\n",
" selected_ranges = ", if (length(object@selected_ranges) > 0) {
sprintf("(%d non-null sets)", sum(sapply(object@selected_ranges, function(x) !is.null(x))))
} else {
"(none)"
}, "\n",
" selected_points = ", if (length(object@selected_points) > 0) {
sprintf("(%d non-null points)", sum(sapply(object@selected_points, function(x) !is.null(x))))
} else {
"(none)"
}, "\n",
" extended = ", if (object@extended) "TRUE" else "FALSE", "\n",
" query_layout = ", if (length(object@query_layout) == 0) "(none)" else object@query_layout, "\n",
" datetimes_as_int64 = ", if (object@datetimes_as_int64) "TRUE" else "FALSE", "\n",
" encryption_key = ", if (length(object@encryption_key) == 0) "(none)" else "(set)", "\n",
" query_condition = ", if (isTRUE(object@query_condition@init)) "(set)" else "(none)", "\n",
" timestamp_start = ", if (length(object@timestamp_start) == 0) "(none)" else format(object@timestamp_start), "\n",
" timestamp_end = ", if (length(object@timestamp_end) == 0) "(none)" else format(object@timestamp_end), "\n",
" return_as = '", object@return_as, "'\n",
" query_statistics = ", if (object@query_statistics) "TRUE" else "FALSE", "\n",
" strings_as_factors = ", if (object@strings_as_factors) "TRUE" else "FALSE", "\n",
" keep_open = ", if (object@keep_open) "TRUE" else "FALSE", "\n",
sep = ""
)
}
)
setValidity("tiledb_array", function(object) {
msg <- NULL
valid <- TRUE
if (!is(object@ctx, "tiledb_ctx")) {
valid <- FALSE
msg <- c(msg, "The 'ctx' slot does not contain a ctx object.")
}
if (!is.character(object@uri)) {
valid <- FALSE
msg <- c(msg, "The 'uri' slot does not contain a character value.")
}
if (!is.logical(object@is.sparse)) {
valid <- FALSE
msg <- c(msg, "The 'is.sparse' slot does not contain a logical value.")
}
if (!is.character(object@attrs)) {
valid <- FALSE
msg <- c(msg, "The 'attrs' slot does not contain a character vector.")
}
if (!is.logical(object@extended)) {
valid <- FALSE
msg <- c(msg, "The 'extended' slot does not contain a logical value.")
}
if (!is.list(object@selected_ranges)) {
valid <- FALSE
msg <- c(msg, "The 'selected_ranges' slot does not contain a list.")
} else {
for (i in (seq_len(length(object@selected_ranges)))) {
if (!is.null(object@selected_ranges[[i]])) {
if (length(dim(object@selected_ranges[[i]])) != 2) {
valid <- FALSE
msg <- c(msg, sprintf("Element '%d' of 'selected_ranges' is not 2-d.", i))
}
if (ncol(object@selected_ranges[[i]]) != 2) {
valid <- FALSE
msg <- c(msg, sprintf("Element '%d' of 'selected_ranges' is not two column.", i))
}
}
}
}
if (!is.list(object@selected_points)) {
valid <- FALSE
msg <- c(msg, "The 'selected_points' slot does not contain a list.")
} else {
for (i in (seq_len(length(object@selected_points)))) {
if (!is.null(object@selected_points[[i]])) {
if (!is.vector(object@selected_points[[i]]) && !inherits(object@selected_points[[i]], "integer64")) {
valid <- FALSE
msg <- c(msg, sprintf("Element '%d' of 'selected_points' is not a vector.", i))
}
}
}
}
if (!is.character(object@query_layout)) {
valid <- FALSE
msg <- c(msg, "The 'query_layout' slot does not contain a character value.")
}
if (!is.logical(object@datetimes_as_int64)) {
valid <- FALSE
msg <- c(msg, "The 'datetimes_as_int64' slot does not contain a logical value.")
}
if (!is.character(object@encryption_key)) {
valid <- FALSE
msg <- c(msg, "The 'encryption_key' slot does not contain a character vector.")
}
if (!is(object@query_condition, "tiledb_query_condition")) {
valid <- FALSE
msg <- c(msg, "The 'query_condition' slot does not contain a query condition object.")
}
if (!inherits(object@timestamp_start, "POSIXct")) {
valid <- FALSE
msg <- c(msg, "The 'timestamp_start' slot does not contain a POSIXct value.")
}
if (!inherits(object@timestamp_end, "POSIXct")) {
valid <- FALSE
msg <- c(msg, "The 'timestamp_end' slot does not contain a POSIXct value.")
}
if (!is(object@ptr, "externalptr")) {
valid <- FALSE
msg <- c(msg, "The 'ptr' slot does not contain an external pointer.")
}
if (!(object@return_as %in% c(
"asis", "array", "matrix", "data.frame",
"data.table", "tibble", "arrow_table", "arrow"
))) {
valid <- FALSE
msg <- c(msg, paste(
"The 'return_as' slot must contain one of 'asis', 'array', 'matrix',",
"'data.frame', 'data.table', 'tibble', 'arrow_table' or 'arrow'."
))
}
if (!is.logical(object@query_statistics)) {
valid <- FALSE
msg <- c(msg, "The 'query_statistics' slot does not contain a logical value.")
}
if (!is.logical(object@strings_as_factors)) {
valid <- FALSE
msg <- c(msg, "The 'strings_as_factors' slot does not contain a logical value.")
}
if (!is.logical(object@keep_open)) {
valid <- FALSE
msg <- c(msg, "The 'keep_open' slot does not contain a logical value.")
}
if (valid) TRUE else msg
})
## Internal helper function to map DATETIME_* data to the internal representation (where
## we mostly follow NumPy). An example is DATETIME_YEAR where the current year (2021) is
## encoded as the offset relative to the _year_ of the epoch, i.e. 51. When an R user submits
## a date type as a min or max value for a range, if would likely be as.Date("2021-01-01")
## which, being an R date, has an internal representation of _days_ since the epoch, i.e.
## as.numeric(as.Date("2021-01-01")) yields 18628.
##
## We also convert the value to integer64 because that is the internal storage format
.map2integer64 <- function(val, dtype) {
## in case it is not a (datetime or (u)int64) type), or already an int64, return unchanged
if ((!grepl("^DATETIME_", dtype) && !grepl("INT64$", dtype)) || inherits(val, "integer64")) {
return(val)
}
val <- switch(dtype,
"DATETIME_YEAR" = as.numeric(strftime(val, "%Y")) - 1970,
"DATETIME_MONTH" = 12 * (as.numeric(strftime(val, "%Y")) - 1970) + as.numeric(strftime(val, "%m")) - 1,
"DATETIME_WEEK" = as.numeric(val) / 7,
"DATETIME_DAY" = as.numeric(val),
"DATETIME_HR" = as.numeric(val) / 3600,
"DATETIME_MIN" = as.numeric(val) / 60,
"DATETIME_SEC" = as.numeric(val),
"DATETIME_MS" = as.numeric(val) * 1e3,
"DATETIME_US" = as.numeric(val) * 1e6,
"DATETIME_NS" = as.numeric(val),
"DATETIME_PS" = as.numeric(val) * 1e3,
"DATETIME_FS" = as.numeric(val) * 1e6,
"DATETIME_AS" = as.numeric(val) * 1e9,
"UINT64" = val,
"INT64" = val
)
bit64::as.integer64(val)
}
#' Returns a TileDB array, allowing for specific subset ranges.
#'
#' Heterogenous domains are supported, including timestamps and characters.
#'
#' This function may still change; the current implementation should be
#' considered as an initial draft.
#' @param x A `tiledb_array` object.
#' @param i optional row index expression which can be a list in which case
#' minimum and maximum of each list element determine a range; multiple list
#' elements can be used to supply multiple ranges.
#' @param j optional column index expression which can be a list in which case
#' minimum and maximum of each list element determine a range; multiple list
#' elements can be used to supply multiple ranges.
#' @param ... Extra parameters for method signature, currently unused.
#' @param drop Optional logical switch to drop dimensions, default FALSE,
#' currently unused.
#' @return The resulting elements in the selected format
#' @import nanotime
#' @importFrom nanoarrow as_nanoarrow_array
#' @aliases [,tiledb_array
#' @aliases [,tiledb_array-method
#' @aliases [,tiledb_array,ANY,tiledb_array-method
#' @aliases [,tiledb_array,ANY,ANY,tiledb_array-method
setMethod(
"[",
"tiledb_array",
function(x, i, j, ..., drop = FALSE) {
## add defaults
if (missing(i)) i <- NULL
if (missing(j)) j <- NULL
k <- NULL
# verbose <- getOption("verbose", FALSE)
spdl::trace("[tiledb_array] '[' accessor started")
## deal with possible n-dim indexing
ndlist <- nd_index_from_syscall(sys.call(), parent.frame())
if (length(ndlist) >= 0) {
if (length(ndlist) >= 1 && !is.null(ndlist[[1]])) i <- ndlist[[1]]
if (length(ndlist) >= 2 && !is.null(ndlist[[2]])) j <- ndlist[[2]]
if (length(ndlist) >= 3 && !is.null(ndlist[[3]])) k <- ndlist[[3]]
if (length(ndlist) >= 4) message("Indices beyond the third dimension not supported in [i,j,k] form. Use selected_ranges() or selected_points().")
}
ctx <- x@ctx
uri <- x@uri
sel <- x@attrs
sch <- tiledb::schema(x)
dom <- tiledb::domain(sch)
layout <- x@query_layout
asint64 <- x@datetimes_as_int64
enckey <- x@encryption_key
tstamp <- x@timestamp_end
sparse <- libtiledb_array_schema_sparse(sch@ptr)
if (x@return_as == "arrow_table") {
x@return_as <- "arrow"
} # normalize
if (x@return_as %in% c("data.table", "tibble", "arrow")) {
if (!requireNamespace(x@return_as, quietly = TRUE)) {
stop("The 'return_as' argument value '", x@return_as, "' requires the package '",
x@return_as, "' to be installed.",
call. = FALSE
)
}
}
use_arrow <- x@return_as == "arrow"
if (use_arrow) {
suppressMessages(do.call(rawToChar(as.raw(c(0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65))), list("nanoarrow")))
}
dims <- tiledb::dimensions(dom)
ndims <- length(dims)
dimnames <- sapply(dims, function(d) libtiledb_dim_get_name(d@ptr))
dimtypes <- sapply(dims, function(d) libtiledb_dim_get_datatype(d@ptr))
dimvarnum <- sapply(dims, function(d) libtiledb_dim_get_cell_val_num(d@ptr))
dimnullable <- sapply(dims, function(d) FALSE)
dimdictionary <- sapply(dims, function(d) FALSE)
attrs <- tiledb::attrs(schema(x))
attrnames <- unname(sapply(attrs, function(a) libtiledb_attribute_get_name(a@ptr)))
attrtypes <- unname(sapply(attrs, function(a) libtiledb_attribute_get_type(a@ptr)))
attrvarnum <- unname(sapply(attrs, function(a) libtiledb_attribute_get_cell_val_num(a@ptr)))
attrnullable <- unname(sapply(attrs, function(a) libtiledb_attribute_get_nullable(a@ptr)))
attrdictionary <- unname(sapply(attrs, function(a) libtiledb_attribute_has_enumeration(ctx@ptr, a@ptr)))
if (length(sel) == 1 && is.na(sel[1])) { # special case of NA selecting no attrs
attrnames <- character()
attrtypes <- character()
attrvarnum <- integer()
attrnullable <- logical()
attrdictionary <- logical()
}
if (length(sel) != 0 && !any(is.na(sel))) {
ind <- match(sel, attrnames)
if (length(ind) == 0) {
stop("Only non-existing columns selected.", call. = FALSE)
}
attrnames <- attrnames[ind]
attrtypes <- attrtypes[ind]
attrvarnum <- attrvarnum[ind]
attrnullable <- attrnullable[ind]
attrdictionary <- attrdictionary[ind]
}
if (x@extended) { # if true return dimensions and attributes
allnames <- c(dimnames, attrnames)
alltypes <- c(dimtypes, attrtypes)
allvarnum <- c(dimvarnum, attrvarnum)
allnullable <- c(dimnullable, attrnullable)
alldictionary <- c(dimdictionary, attrdictionary)
} else { # otherwise only return attributes
allnames <- attrnames
alltypes <- attrtypes
allvarnum <- attrvarnum
allnullable <- attrnullable
alldictionary <- attrdictionary
}
## A preference can be set in a local per-user configuration file; if no value
## is set a fallback from the TileDB config object is used.
memory_budget <- get_allocation_size_preference()
spdl::debug("['['] memory budget is {}", memory_budget)
if (length(enckey) > 0) {
arrptr <- libtiledb_array_open_with_key(ctx@ptr, uri, "READ", enckey)
} else {
arrptr <- libtiledb_array_open(ctx@ptr, uri, "READ")
}
if (length(x@timestamp_start) > 0) {
spdl::debug("['['] set open_timestamp_start to {}", x@timestamp_start)
arrptr <- libtiledb_array_set_open_timestamp_start(arrptr, x@timestamp_start)
}
if (length(x@timestamp_end) > 0) {
spdl::debug("['['] set open_timestamp_end to {}", x@timestamp_end)
arrptr <- libtiledb_array_set_open_timestamp_end(arrptr, x@timestamp_end)
}
if (length(x@timestamp_start) > 0 || length(x@timestamp_end) > 0) {
arrptr <- libtiledb_array_reopen(arrptr)
}
## dictionaries are schema-level objects to fetch them now where we expect to have some
dictionaries <- vector(mode = "list", length = length(allnames))
names(dictionaries) <- allnames
ordered_dict <- dictionaries
for (ii in seq_along(dictionaries)) {
if (isTRUE(alldictionary[ii])) {
attr <- attrs[[allnames[ii]]]
tpstr <- tiledb_attribute_get_enumeration_type_ptr(attr, arrptr)
if (tpstr %in% c("ASCII", "UTF8")) {
dictionaries[[ii]] <- tiledb_attribute_get_enumeration_ptr(attr, arrptr)
} else if (tpstr %in% c(
"FLOAT32", "FLOAT64", "BOOL",
"UINT8", "UINT16", "UINT32", "UINT64",
"INT8", "INT16", "INT32", "INT64"
)) {
dictionaries[[ii]] <- tiledb_attribute_get_enumeration_vector_ptr(attr, arrptr)
} else {
stop("Unsupported enumeration vector payload of type '%s'", tpstr, call. = FALSE)
}
ordered_dict[[ii]] <- tiledb_attribute_is_ordered_enumeration_ptr(attr, arrptr)
attr(dictionaries[[ii]], "ordered") <- ordered_dict[[ii]]
}
}
## helper function to sweep over names and types of domain
getDomain <- function(nm, tp) {
if (tp %in% c("ASCII", "CHAR", "UTF8")) {
libtiledb_array_get_non_empty_domain_var_from_name(arrptr, nm)
} else {
libtiledb_array_get_non_empty_domain_from_name(arrptr, nm, tp)
}
}
nonemptydom <- mapply(getDomain, dimnames, dimtypes, SIMPLIFY = FALSE)
## open query
qryptr <- libtiledb_query(ctx@ptr, arrptr, "READ")
qryptr <- libtiledb_query_set_layout(qryptr, if (isTRUE(nzchar(layout))) {
layout
} else {
if (sparse) "UNORDERED" else "COL_MAJOR"
})
## ranges seem to interfere with the byte/element adjustment below so set up toggle
rangeunset <- TRUE
## ensure selected_ranges, if submitted, is of correct length
if (length(x@selected_ranges) != 0 &&
length(x@selected_ranges) != length(dimnames) &&
is.null(names(x@selected_ranges))) {
stop(paste0(
"If ranges are selected by index alone (and not named), ",
"one is required for each dimension."
), call. = FALSE)
}
## ensure selected_points, if submitted, is of correct length
if (length(x@selected_points) != 0 &&
length(x@selected_points) != length(dimnames) &&
is.null(names(x@selected_points))) {
stop(paste0(
"If points are selected by index alone (and not named), ",
"one is required for each dimension."
), call. = FALSE)
}
## expand a shorter-but-named selected_ranges list
if ((length(x@selected_ranges) < length(dimnames)) &&
(!is.null(names(x@selected_ranges)))) {
fulllist <- vector(mode = "list", length = length(dimnames))
ind <- match(names(x@selected_ranges), dimnames)
if (any(is.na(ind))) stop("Name for selected ranges does not match dimension names.")
for (ii in seq_len(length(ind))) {
fulllist[[ind[ii]]] <- x@selected_ranges[[ii]]
}
x@selected_ranges <- fulllist
}
## expand a shorter-but-named selected_points list
if ((length(x@selected_points) < length(dimnames)) &&
(!is.null(names(x@selected_points)))) {
fulllist <- vector(mode = "list", length = length(dimnames))
ind <- match(names(x@selected_points), dimnames)
if (any(is.na(ind))) stop("Name for selected points does not match dimension names.")
for (ii in seq_len(length(ind))) {
fulllist[[ind[ii]]] <- x@selected_points[[ii]]
}
x@selected_points <- fulllist
}
## selected_ranges may be in different order than dimnames, so reorder if need be
if ((length(x@selected_ranges) == length(dimnames)) &&
(!is.null(names(x@selected_ranges))) &&
(!identical(names(x@selected_ranges), dimnames))) {
x@selected_ranges <- x@selected_ranges[dimnames]
}
## selected_points may be in different order than dimnames, so reorder if need be
if ((length(x@selected_points) == length(dimnames)) &&
(!is.null(names(x@selected_points))) &&
(!identical(names(x@selected_points), dimnames))) {
x@selected_points <- x@selected_points[dimnames]
}
## if selected_ranges is still an empty list, make it an explicit one
if (length(x@selected_ranges) == 0) {
x@selected_ranges <- vector(mode = "list", length = length(dimnames))
}
## if selected_points is still an empty list, make it an explicit one
if (length(x@selected_points) == 0) {
x@selected_points <- vector(mode = "list", length = length(dimnames))
}
if (!is.null(i)) {
if (!is.null(x@selected_ranges[[1]])) {
stop("Cannot set both 'i' and first element of 'selected_ranges'.", call. = FALSE)
}
x@selected_ranges[[1]] <- i
}
if (!is.null(j)) {
if (ndims == 1) {
stop("Setting dimension 'j' requires at least two dimensions.", call. = FALSE)
}
if (!is.null(x@selected_ranges[[2]])) {
stop("Cannot set both 'j' and second element of 'selected_ranges'.", call. = FALSE)
}
x@selected_ranges[[2]] <- j
}
if (!is.null(k)) {
if (ndims <= 2) {
stop("Setting dimension 'k' requires at least three dimensions.", call. = FALSE)
}
if (!is.null(x@selected_ranges[[3]])) {
stop("Cannot set both 'k' and second element of 'selected_ranges'.", call. = FALSE)
}
x@selected_ranges[[3]] <- k
}
## (i,j,k) are now done and transferred to x@selected_ranges
## pointer to subarray needed for iterated setting of points from selected_ranges
## and selected_points across all possible dimensions
have_made_selection <- FALSE
sbrptr <- libtiledb_subarray(qryptr)
## if ranges selected, use those
for (k in seq_len(length(x@selected_ranges))) {
if (is.null(x@selected_ranges[[k]]) && is.null(x@selected_points[[k]])) {
vec <- .map2integer64(nonemptydom[[k]], dimtypes[k])
if (vec[1] != 0 || vec[2] != 0) { # corner case of A[] on empty array
sbrptr <- libtiledb_subarray_add_range_with_type(sbrptr, k - 1, dimtypes[k], vec[1], vec[2])
spdl::debug("[tiledb_array] Adding non-zero dim {}:{} on {} with ({},{})", k, i, dimtypes[k], vec[1], vec[2])
rangeunset <- FALSE
have_made_selection <- TRUE
}
} else if (is.null(nrow(x@selected_ranges[[k]])) && is.null(x@selected_points[[k]])) {
vec <- x@selected_ranges[[k]]
vec <- .map2integer64(vec, dimtypes[k])
sbrptr <- libtiledb_subarray_add_range_with_type(sbrptr, k - 1, dimtypes[k], min(vec), max(vec))
spdl::debug("[tiledb_array] Adding non-zero dim {}:{} on {} with ({},{})", k, i, dimtypes[k], vec[1], vec[2])
rangeunset <- FALSE
have_made_selection <- TRUE
} else if (is.null(x@selected_points[[k]])) {
m <- x@selected_ranges[[k]]
for (i in seq_len(nrow(m))) {
vec <- .map2integer64(c(m[i, 1], m[i, 2]), dimtypes[k])
sbrptr <- libtiledb_subarray_add_range_with_type(sbrptr, k - 1, dimtypes[k], vec[1], vec[2])
spdl::debug("[tiledb_array] Adding non-zero dim {}:{} on {} with ({},{})", k, i, dimtypes[k], vec[1], vec[2])
}
rangeunset <- FALSE
have_made_selection <- TRUE
}
}
## if points selected, use those (and fewer special cases as A[i,j,k] not folded into points)
for (k in seq_len(length(x@selected_points))) {
if (!is.null(x@selected_points[[k]])) {
m <- x@selected_points[[k]]
for (i in seq_along(m)) {
vec <- .map2integer64(c(m[i], m[i]), dimtypes[k])
sbrptr <- libtiledb_subarray_add_range_with_type(sbrptr, k - 1, dimtypes[k], vec[1], vec[2])
spdl::debug("[tiledb_array] Adding point on non-zero dim {}:{} on {} with ({},{})", k, i, dimtypes[k], vec[1], vec[2])
}
rangeunset <- FALSE
have_made_selection <- TRUE
}
}
if (have_made_selection) {
libtiledb_query_set_subarray_object(qryptr, sbrptr)
}
buflist <- vector(mode = "list", length = length(allnames))
if (length(x@buffers) != 0) { # if we were given buffers (as in the case of TileDB Cloud ops)
nm <- names(x@buffers)
if (!isTRUE(all.equal(nm, allnames))) {
stop("Expected ", paste(allnames, collapse = ","), " got ", paste(nm, collapse = ","), call. = FALSE)
}
for (i in seq_along(allnames)) {
n <- allnames[i]
path <- x@buffers[[n]]
if (!file.exists(path)) stop("No buffer for ", n, call. = FALSE)
if (is.na(allvarnum[i])) {
buflist[[i]] <- vlcbuf_from_shmem(path, alltypes[i])
} else {
buflist[[i]] <- querybuf_from_shmem(path, alltypes[i])
}
}
## get results (shmem variant)
getResultShmem <- function(buf, name, varnum) { # , resrv, qryptr) {
if (is.na(varnum)) {
vec <- length_from_vlcbuf(buf)
libtiledb_query_get_buffer_var_char(buf, vec[1], vec[2])[, 1]
} else {
col <- libtiledb_query_get_buffer_ptr(buf, asint64)
if (!is.null(dictionaries[[name]])) { # if there is a dictionary
dct <- dictionaries[[name]] # access it from utility
ord <- ordered_dict[[name]]
## the following expands out to a char vector first; we can do better
## col <- factor(dct[col+1], levels=dct)
## so we do it "by hand"
col <- col + 1L # adjust for zero-index C/C++ layer
attr(col, "levels") <- dct
attr(col, "class") <- if (ord) c("ordered", "factor") else "factor"
}
col
}
}
reslist <- mapply(getResultShmem, buflist, allnames, allvarnum, SIMPLIFY = FALSE)
ind <- which(allvarnum != 1 & !is.na(allvarnum))
for (k in ind) {
ncells <- allvarnum[k]
v <- reslist[[k]]
## we split a vector v into 'list-columns' which element containing
## ncells value (and we get ncells from the Array schema)
## see https://stackoverflow.com/a/9547594/143305 for I()
## and https://stackoverflow.com/a/3321659/143305 for split()
reslist[[k]] <- I(unname(split(v, ceiling(seq_along(v) / ncells))))
}
res <- data.frame(reslist)
colnames(res) <- allnames
} else { # -- start 'big else' of standard query build
## retrieve est_result_size
getEstimatedSize <- function(name, varnum, nullable, qryptr, datatype) {
if (is.na(varnum) && !nullable) {
res <- libtiledb_query_get_est_result_size_var(qryptr, name)[1]
spdl::debug("[getEstimatedSize] column '{}' (is.na(varnum) and !nullable) {}", name, res)
} else if (is.na(varnum) && nullable) {
res <- libtiledb_query_get_est_result_size_var_nullable(qryptr, name)[1]
spdl::debug("[getEstimatedSize] column '{}' (is.na(varnum) and nullable) {}", name, res)
} else if (!is.na(varnum) && !nullable) {
res <- libtiledb_query_get_est_result_size(qryptr, name)
spdl::debug("[getEstimatedSize] column '{}' (!is.na(varnum) and !nullable) {}", name, res)
} else if (!is.na(varnum) && nullable) {
res <- libtiledb_query_get_est_result_size_nullable(qryptr, name)[1]
spdl::debug("[getEstimatedSize] column '{}' (!is.na(varnum) and nullable) {}", name, res)
}
if (rangeunset) {
sz <- tiledb_datatype_string_to_sizeof(datatype)
res <- res / sz
spdl::debug("[getEstimatedSize] column '{}' rangeunset and res scaled to {}", name, res)
}
res
}
ressizes <- mapply(getEstimatedSize, allnames, allvarnum, allnullable, alltypes,
MoreArgs = list(qryptr = qryptr), SIMPLIFY = TRUE
)
## ensure > 0 for correct handling of zero-length outputs, ensure respecting memory budget
spdl::debug("['['] result of size estimates is {}", paste(ressizes, collapse=","))
idx <- ressizes > 0
ressizes <- if (any(idx)) {
ressizes[idx]
} else {
0
}
resrv <- max(1, min(memory_budget/8, ressizes))
spdl::debug("['['] overall estimate {} rows", resrv)
## allocate and set buffers
if (!use_arrow) {
getBuffer <- function(name, type, varnum, nullable, resrv, qryptr, arrptr) {
if (is.na(varnum)) {
if (type %in% c("CHAR", "ASCII", "UTF8")) {
spdl::debug("[getBuffer] '{}' allocating 'char' {} rows given budget of {}", name, resrv, memory_budget)
buf <- libtiledb_query_buffer_var_char_alloc_direct(resrv, memory_budget, nullable)
buf <- libtiledb_query_buffer_var_char_legacy_validity_mode(ctx@ptr, buf)
qryptr <- libtiledb_query_set_buffer_var_char(qryptr, name, buf)
buf
} else {
message("Non-char var.num columns are not currently supported.")
}
} else {
spdl::debug("[getBuffer] '{}' allocating non-char {} rows given budget of {}", name, resrv, memory_budget)
buf <- libtiledb_query_buffer_alloc_ptr(type, resrv, nullable, varnum)
qryptr <- libtiledb_query_set_buffer_ptr(qryptr, name, buf)
buf
}
}
buflist <- mapply(getBuffer, allnames, alltypes, allvarnum, allnullable,
MoreArgs = list(resrv = resrv, qryptr = qryptr, arrptr = arrptr),
SIMPLIFY = FALSE
)
spdl::debug("['['] buffers allocated in list")
}
## if we have a query condition, apply it
if (isTRUE(x@query_condition@init)) {
qryptr <- libtiledb_query_set_condition(qryptr, x@query_condition@ptr)
}
overallresults <- list()
counter <- 1L
finished <- FALSE
while (!finished) {
if (use_arrow) {
abptr <- libtiledb_allocate_column_buffers(ctx@ptr, qryptr, uri, allnames, memory_budget)
spdl::debug("['['] buffers allocated and set")
}
## fire off query
spdl::debug(
"['['] query submission: {} array_open {}", counter,
if (libtiledb_array_is_open(arrptr)) "true" else "false"
)
qryptr <- libtiledb_query_submit(qryptr)
## check status
status <- libtiledb_query_status(qryptr)
# if (status != "COMPLETE") warning("Query returned '", status, "'.", call. = FALSE)
if (status != "COMPLETE") spdl::debug("['['] query returned '{}'.", status)
if (use_arrow) {
## rl <- libtiledb_to_arrow(abptr, qryptr, dictionaries)
## at <- .as_arrow_table(rl)
na <- libtiledb_to_arrow(abptr, qryptr, dictionaries)
at <- arrow::as_arrow_table(na)
## special case from schema evolution could have added twice so correcting
for (n in colnames(at)) {
v <- at[[n]]$as_vector()
lvls <- levels(v)
if (inherits(v, "factor")) {
vec <- as.integer(v)
vec[vec == -.Machine$integer.max] <- NA_integer_
if (min(vec, na.rm = TRUE) == 2 && max(vec, na.rm = TRUE) == length(lvls) + 1) {
vec <- vec - 1L
attr(vec, "levels") <- attr(v, "levels")
class(vec) <- class(v)
at[[n]] <- vec
}