File size: 21,827 Bytes
2c3c408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#include <tiledb/tiledb.h>              // for enums
#include <tiledb/tiledb>                // C++
#include <tiledb/tiledb_experimental.h> // for `tiledb_subarray_has_label_range`
#include <tiledb/tiledb_experimental>   // C++

#include "common.h"

#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <pybind11/stl.h>

namespace libtiledbcpp {

using namespace tiledb;
namespace py = pybind11;

template <typename T> struct SubarrayDimensionManipulator {

  static void copy(Subarray &subarray, Subarray &original, uint32_t dim_idx) {
    for (uint64_t range_idx{0}; range_idx < original.range_num(dim_idx);
         ++range_idx) {
      std::array<T, 3> range = original.range<T>(dim_idx, range_idx);
      subarray.add_range(dim_idx, range[0], range[1], range[2]);
    }
  }

  static py::ssize_t length(Subarray &subarray, uint32_t dim_idx) {
    uint64_t length = 0;
    for (uint64_t range_idx{0}; range_idx < subarray.range_num(dim_idx);
         ++range_idx) {
      std::array<T, 3> range = subarray.range<T>(dim_idx, range_idx);
      if (range[2] != 0 && range[1] != 1) {
        throw TileDBPyError("Support for getting the lenght of ranges with a "
                            "stride is not yet implemented.");
      }

      auto range_length = static_cast<uint64_t>(range[1] - range[0]);
      if (length > std::numeric_limits<uint64_t>::max() - range_length - 1) {
        throw TileDBPyError("Overflow error computing subarray shape");
      }
      length += range_length + 1;
    }
    if (length > PY_SSIZE_T_MAX) {
      throw TileDBPyError("Overflow error computing subarray shape");
    }
    return Py_SAFE_DOWNCAST(length, Py_ssize_t, uint64_t);
  }
};

template <> struct SubarrayDimensionManipulator<std::string> {

  static void copy(Subarray &subarray, Subarray &original, uint32_t dim_idx) {
    for (uint64_t range_idx{0}; range_idx < original.range_num(dim_idx);
         ++range_idx) {
      std::array<std::string, 2> range = original.range(dim_idx, range_idx);
      subarray.add_range(dim_idx, range[0], range[1]);
    }
  }

  static uint64_t length(Subarray &, uint32_t) {
    throw TileDBPyError(
        "Getting length of ranges is not supported on string dimensions.");
  }
};

void add_dim_range(Subarray &subarray, uint32_t dim_idx, py::tuple r) {
  if (py::len(r) == 0)
    return;
  else if (py::len(r) != 2)
    TPY_ERROR_LOC("Unexpected range len != 2");

  auto r0 = r[0];
  auto r1 = r[1];

  auto tiledb_type =
      subarray.array().schema().domain().dimension(dim_idx).type();

  try {
    switch (tiledb_type) {
    case TILEDB_INT32: {
      using T = int32_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_INT64: {
      using T = int64_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_INT8: {
      using T = int8_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT8: {
      using T = uint8_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_INT16: {
      using T = int16_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT16: {
      using T = uint16_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT32: {
      using T = uint32_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT64: {
      using T = uint64_t;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_FLOAT32: {
      using T = float;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_FLOAT64: {
      using T = double;
      subarray.add_range(dim_idx, r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_STRING_ASCII:
    case TILEDB_STRING_UTF8:
    case TILEDB_CHAR: {
      if (!py::isinstance<py::none>(r0) != !py::isinstance<py::none>(r1)) {
        TPY_ERROR_LOC(
            "internal error: ranges must both be strings or (None, None)");
      } else if (!py::isinstance<py::none>(r0) &&
                 !py::isinstance<py::none>(r1) &&
                 !py::isinstance<py::str>(r0) && !py::isinstance<py::str>(r1) &&
                 !py::isinstance<py::bytes>(r0) &&
                 !py::isinstance<py::bytes>(r1)) {
        TPY_ERROR_LOC(
            "internal error: expected string type for var-length dim!");
      }

      if (!py::isinstance<py::none>(r0) && !py::isinstance<py::none>(r0))
        subarray.add_range(dim_idx, r0.cast<std::string>(),
                           r1.cast<std::string>());

      break;
    }
    case TILEDB_DATETIME_YEAR:
    case TILEDB_DATETIME_MONTH:
    case TILEDB_DATETIME_WEEK:
    case TILEDB_DATETIME_DAY:
    case TILEDB_DATETIME_HR:
    case TILEDB_DATETIME_MIN:
    case TILEDB_DATETIME_SEC:
    case TILEDB_DATETIME_MS:
    case TILEDB_DATETIME_US:
    case TILEDB_DATETIME_NS:
    case TILEDB_DATETIME_PS:
    case TILEDB_DATETIME_FS:
    case TILEDB_DATETIME_AS: {
    case TILEDB_TIME_HR:
    case TILEDB_TIME_MIN:
    case TILEDB_TIME_SEC:
    case TILEDB_TIME_MS:
    case TILEDB_TIME_US:
    case TILEDB_TIME_NS:
    case TILEDB_TIME_PS:
    case TILEDB_TIME_FS:
    case TILEDB_TIME_AS:
      py::dtype dtype = tdb_to_np_dtype(tiledb_type, 1);
      auto dt0 = py::isinstance<py::int_>(r0) ? r0 : r0.attr("astype")(dtype);
      auto dt1 = py::isinstance<py::int_>(r1) ? r1 : r1.attr("astype")(dtype);

      // TODO, this is suboptimal, should define pybind converter
      if (py::isinstance<py::int_>(dt0) && py::isinstance<py::int_>(dt1)) {
        subarray.add_range(dim_idx, py::cast<int64_t>(dt0),
                           py::cast<int64_t>(dt1));
      } else {
        auto darray = py::array(py::make_tuple(dt0, dt1));
        subarray.add_range(dim_idx, *(int64_t *)darray.data(0),
                           *(int64_t *)darray.data(1));
      }

      break;
    }
    default:
      TPY_ERROR_LOC("Unknown dim type conversion!");
    }
  } catch (py::cast_error &e) {
    (void)e;
    std::string msg = "Failed to cast dim range '" + (std::string)py::repr(r) +
                      "' to dim type " + tiledb::impl::type_to_str(tiledb_type);
    TPY_ERROR_LOC(msg);
  }
}

void copy_ranges_on_dim(Subarray &subarray, Subarray original,
                        uint32_t dim_idx) {

  auto tiledb_type =
      subarray.array().schema().domain().dimension(dim_idx).type();

  switch (tiledb_type) {
  case TILEDB_INT32: {
    using T = int32_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_INT64: {
    using T = int64_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_INT8: {
    using T = int8_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_UINT8: {
    using T = uint8_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_INT16: {
    using T = int16_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_UINT16: {
    using T = uint16_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_UINT32: {
    using T = uint32_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_UINT64: {
    using T = uint64_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_FLOAT32: {
    using T = float;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_FLOAT64: {
    using T = double;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_STRING_ASCII:
  case TILEDB_STRING_UTF8:
  case TILEDB_CHAR: {
    using T = std::string;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  case TILEDB_DATETIME_YEAR:
  case TILEDB_DATETIME_MONTH:
  case TILEDB_DATETIME_WEEK:
  case TILEDB_DATETIME_DAY:
  case TILEDB_DATETIME_HR:
  case TILEDB_DATETIME_MIN:
  case TILEDB_DATETIME_SEC:
  case TILEDB_DATETIME_MS:
  case TILEDB_DATETIME_US:
  case TILEDB_DATETIME_NS:
  case TILEDB_DATETIME_PS:
  case TILEDB_DATETIME_FS:
  case TILEDB_DATETIME_AS: {
  case TILEDB_TIME_HR:
  case TILEDB_TIME_MIN:
  case TILEDB_TIME_SEC:
  case TILEDB_TIME_MS:
  case TILEDB_TIME_US:
  case TILEDB_TIME_NS:
  case TILEDB_TIME_PS:
  case TILEDB_TIME_FS:
  case TILEDB_TIME_AS:
    using T = int64_t;
    SubarrayDimensionManipulator<T>::copy(subarray, original, dim_idx);
    break;
  }
  default:
    TPY_ERROR_LOC("Unknown dim type conversion!");
  }
}

py::ssize_t length_ranges(Subarray &subarray, uint32_t dim_idx) {

  auto tiledb_type =
      subarray.array().schema().domain().dimension(dim_idx).type();

  switch (tiledb_type) {
  case TILEDB_INT32: {
    using T = int32_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_INT64: {
    using T = int64_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_INT8: {
    using T = int8_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_UINT8: {
    using T = uint8_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_INT16: {
    using T = int16_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_UINT16: {
    using T = uint16_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_UINT32: {
    using T = uint32_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_UINT64: {
    using T = uint64_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  case TILEDB_DATETIME_YEAR:
  case TILEDB_DATETIME_MONTH:
  case TILEDB_DATETIME_WEEK:
  case TILEDB_DATETIME_DAY:
  case TILEDB_DATETIME_HR:
  case TILEDB_DATETIME_MIN:
  case TILEDB_DATETIME_SEC:
  case TILEDB_DATETIME_MS:
  case TILEDB_DATETIME_US:
  case TILEDB_DATETIME_NS:
  case TILEDB_DATETIME_PS:
  case TILEDB_DATETIME_FS:
  case TILEDB_DATETIME_AS: {
  case TILEDB_TIME_HR:
  case TILEDB_TIME_MIN:
  case TILEDB_TIME_SEC:
  case TILEDB_TIME_MS:
  case TILEDB_TIME_US:
  case TILEDB_TIME_NS:
  case TILEDB_TIME_PS:
  case TILEDB_TIME_FS:
  case TILEDB_TIME_AS:
    using T = int64_t;
    return SubarrayDimensionManipulator<T>::length(subarray, dim_idx);
  }
  default:
    TPY_ERROR_LOC("Dimension length not supported on a dimension with the "
                  "given datatype.");
  }
}

void add_dim_point_ranges(const Context &ctx, Subarray &subarray,
                          uint32_t dim_idx, pybind11::handle dim_range) {

  // Cast range object to appropriately typed py::array.
  auto tiledb_type =
      subarray.array().schema().domain().dimension(dim_idx).type();
  py::dtype dtype = tdb_to_np_dtype(tiledb_type, 1);
  py::array ranges = dim_range.attr("astype")(dtype);

  // Set point ranges using C-API.
  tiledb_ctx_t *c_ctx = ctx.ptr().get();
  tiledb_subarray_t *c_subarray = subarray.ptr().get();
  ctx.handle_error(tiledb_subarray_add_point_ranges(
      c_ctx, c_subarray, dim_idx, (void *)ranges.data(), ranges.size()));
}

void add_label_range(const Context &ctx, Subarray &subarray,
                     const std::string &label_name, py::tuple r) {
  if (py::len(r) == 0)
    return;
  else if (py::len(r) != 2)
    TPY_ERROR_LOC("Unexpected range len != 2");

  auto r0 = r[0];
  auto r1 = r[1];

  auto tiledb_type = ArraySchemaExperimental::dimension_label(
                         ctx, subarray.array().schema(), label_name)
                         .label_type();

  try {
    switch (tiledb_type) {
    case TILEDB_INT32: {
      using T = int32_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_INT64: {
      using T = int64_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_INT8: {
      using T = int8_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT8: {
      using T = uint8_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_INT16: {
      using T = int16_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT16: {
      using T = uint16_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT32: {
      using T = uint32_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_UINT64: {
      using T = uint64_t;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_FLOAT32: {
      using T = float;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_FLOAT64: {
      using T = double;
      SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                            r0.cast<T>(), r1.cast<T>());
      break;
    }
    case TILEDB_STRING_ASCII:
    case TILEDB_STRING_UTF8:
    case TILEDB_CHAR: {
      if (!py::isinstance<py::none>(r0) != !py::isinstance<py::none>(r1)) {
        TPY_ERROR_LOC(
            "internal error: ranges must both be strings or (None, None)");
      } else if (!py::isinstance<py::none>(r0) &&
                 !py::isinstance<py::none>(r1) &&
                 !py::isinstance<py::str>(r0) && !py::isinstance<py::str>(r1) &&
                 !py::isinstance<py::bytes>(r0) &&
                 !py::isinstance<py::bytes>(r1)) {
        TPY_ERROR_LOC(
            "internal error: expected string type for var-length label!");
      }

      if (!py::isinstance<py::none>(r0) && !py::isinstance<py::none>(r0)) {
        std::string r0_string = r0.cast<std::string>();
        std::string r1_string = r1.cast<std::string>();
        SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                              r0_string, r1_string);
      }
      break;
    }
    case TILEDB_DATETIME_YEAR:
    case TILEDB_DATETIME_MONTH:
    case TILEDB_DATETIME_WEEK:
    case TILEDB_DATETIME_DAY:
    case TILEDB_DATETIME_HR:
    case TILEDB_DATETIME_MIN:
    case TILEDB_DATETIME_SEC:
    case TILEDB_DATETIME_MS:
    case TILEDB_DATETIME_US:
    case TILEDB_DATETIME_NS:
    case TILEDB_DATETIME_PS:
    case TILEDB_DATETIME_FS:
    case TILEDB_DATETIME_AS: {
    case TILEDB_TIME_HR:
    case TILEDB_TIME_MIN:
    case TILEDB_TIME_SEC:
    case TILEDB_TIME_MS:
    case TILEDB_TIME_US:
    case TILEDB_TIME_NS:
    case TILEDB_TIME_PS:
    case TILEDB_TIME_FS:
    case TILEDB_TIME_AS:
      py::dtype dtype = tdb_to_np_dtype(tiledb_type, 1);
      auto dt0 = py::isinstance<py::int_>(r0) ? r0 : r0.attr("astype")(dtype);
      auto dt1 = py::isinstance<py::int_>(r1) ? r1 : r1.attr("astype")(dtype);

      if (py::isinstance<py::int_>(dt0) && py::isinstance<py::int_>(dt1)) {
        SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                              py::cast<int64_t>(dt0),
                                              py::cast<int64_t>(dt1));
      } else {
        auto darray = py::array(py::make_tuple(dt0, dt1));
        SubarrayExperimental::add_label_range(ctx, subarray, label_name,
                                              *(int64_t *)darray.data(0),
                                              *(int64_t *)darray.data(1));
      }

      break;
    }
    default:
      TPY_ERROR_LOC("Unknown dimension label type conversion!");
    }
  } catch (py::cast_error &e) {
    (void)e;
    std::string msg = "Failed to cast label range '" +
                      (std::string)py::repr(r) + "' to label type " +
                      tiledb::impl::type_to_str(tiledb_type);
    TPY_ERROR_LOC(msg);
  }
}

bool has_label_range(const Context &ctx, Subarray &subarray, uint32_t dim_idx) {
  int32_t has_label;
  auto rc = tiledb_subarray_has_label_ranges(
      ctx.ptr().get(), subarray.ptr().get(), dim_idx, &has_label);
  if (rc == TILEDB_ERR) {
    throw TileDBError("Failed to check dimension for label ranges");
  }
  return has_label == 1;
}

void init_subarray(py::module &m) {
  py::class_<tiledb::Subarray>(m, "Subarray")
      .def(py::init<Subarray>())

      .def(py::init<const Context &, const Array &>(),
           py::keep_alive<1, 2>() /* Keep context alive. */,
           py::keep_alive<1, 3>() /* Keep array alive. */)

      .def("__capsule__",
           [](Subarray &subarray) {
             return py::capsule(subarray.ptr().get(), "subarray");
           })

      .def("_add_dim_range",
           [](Subarray &subarray, uint32_t dim_idx, py::tuple range) {
             add_dim_range(subarray, dim_idx, range);
           })

      .def("_add_label_range",
           [](Subarray &subarray, const Context &ctx,
              const std::string &label_name, py::tuple range) {
             add_label_range(ctx, subarray, label_name, range);
           })

      .def("_add_ranges_bulk",
           [](Subarray &subarray, const Context &ctx, py::iterable ranges) {
             uint32_t dim_idx = 0;
             for (auto dim_range : ranges) {
               if (py::isinstance<py::array>(dim_range)) {
                 add_dim_point_ranges(ctx, subarray, dim_idx, dim_range);
               } else {
                 py::tuple dim_range_iter = dim_range.cast<py::iterable>();
                 for (auto r : dim_range_iter) {
                   py::tuple range_tuple = r.cast<py::tuple>();
                   add_dim_range(subarray, dim_idx, range_tuple);
                 }
               }
               dim_idx++;
             }
           })

      .def("_add_dim_point_ranges",
           [](Subarray &subarray, const Context &ctx, uint32_t dim_idx,
              pybind11::handle dim_range) {
             add_dim_point_ranges(ctx, subarray, dim_idx, dim_range);
           })

      .def("_add_ranges",
           [](Subarray &subarray, const Context &ctx, py::iterable ranges) {
             uint32_t dim_idx = 0;
             for (auto dim_range : ranges) {
               py::tuple dim_range_iter = dim_range.cast<py::iterable>();
               for (auto r : dim_range_iter) {
                 py::tuple r_tuple = r.cast<py::tuple>();
                 add_dim_range(subarray, dim_idx, r_tuple);
               }
               dim_idx++;
             }
           })

      .def("_add_label_ranges",
           [](Subarray &subarray, const Context &ctx, py::iterable ranges) {
             py::dict label_ranges = ranges.cast<py::dict>();
             for (std::pair<py::handle, py::handle> pair : label_ranges) {
               py::str label_name = pair.first.cast<py::str>();
               py::tuple label_range_iter = pair.second.cast<py::iterable>();
               for (auto r : label_range_iter) {
                 py::tuple r_tuple = r.cast<py::tuple>();
                 add_label_range(ctx, subarray, label_name, r_tuple);
               }
             }
           })

      .def("_has_label_range",
           [](Subarray &subarray, const Context &ctx, uint32_t dim_idx) {
             return has_label_range(ctx, subarray, dim_idx);
           })

      .def("copy_ranges",
           [](Subarray &subarray, Subarray &original, py::iterable dims) {
             for (auto dim_idx : dims) {
               copy_ranges_on_dim(subarray, original, dim_idx.cast<uint32_t>());
             }
           })

      .def("_range_num", py::overload_cast<const std::string &>(
                             &Subarray::range_num, py::const_))

      .def("_range_num",
           py::overload_cast<unsigned>(&Subarray::range_num, py::const_))

      .def("_label_range_num",
           [](Subarray &subarray, const Context &ctx,
              const std::string &label_name) {
             return SubarrayExperimental::label_range_num(ctx, subarray,
                                                          label_name);
           })

      .def("_shape",
           [](Subarray &subarray, const Context &ctx) {
             auto ndim = subarray.array().schema().domain().ndim();
             // Create numpy array and get pointer to data.
             py::array_t<py::ssize_t> shape(ndim);
             py::buffer_info shape_result = shape.request();
             py::ssize_t *shape_ptr =
                 static_cast<py::ssize_t *>(shape_result.ptr);
             // Set size for each dimension.
             for (uint32_t dim_idx{0}; dim_idx < ndim; ++dim_idx) {
               shape_ptr[dim_idx] = length_ranges(subarray, dim_idx);
             }
             return shape;
           })

      // End definitions.
      ;
}

} // namespace libtiledbcpp