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
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
from collections import OrderedDict

import numpy as np
import pytest

import tiledb
from tiledb.tests.common import DiskTestCase


class DimensionLabelTestCase(DiskTestCase):
    def test_dim_label_schema(self):
        dim_label_schema1 = tiledb.DimLabelSchema(
            "decreasing", label_dtype=np.float64, dim_dtype=np.int32
        )
        filter = tiledb.FilterList()
        dim_label_schema2 = tiledb.DimLabelSchema(
            "increasing",
            label_dtype=np.float32,
            dim_dtype=np.int64,
            dim_tile=20,
            label_filters=filter,
        )

        assert dim_label_schema1.label_order == "decreasing"
        assert dim_label_schema1.label_dtype == np.float64
        assert dim_label_schema1.dim_dtype == np.int32
        assert dim_label_schema1.dim_tile is None
        assert dim_label_schema1.label_filters is None

        assert dim_label_schema2.label_order == "increasing"
        assert dim_label_schema2.label_dtype == np.float32
        assert dim_label_schema2.dim_dtype == np.int64
        assert dim_label_schema2.dim_tile == 20
        assert dim_label_schema2.label_filters == filter

    def test_dim_label_schema_from_dim(self):
        dim = tiledb.Dim("dim", domain=(1, 10), dtype=np.int32, tile=10)
        dim_label_schema3 = dim.create_label_schema("decreasing", np.int32, tile=2)
        filter = tiledb.FilterList()
        dim_label_schema2 = dim.create_label_schema(
            order="increasing", dtype=np.float32, tile=5, filters=filter
        )
        dim_label_schema1 = dim.create_label_schema("decreasing", np.float64, tile=None)

        assert dim_label_schema1.label_order == "decreasing"
        assert dim_label_schema1.label_dtype == np.float64
        assert dim_label_schema1.dim_dtype == np.int32
        assert dim_label_schema1.dim_tile == 10
        assert dim_label_schema1.label_filters is None

        assert dim_label_schema3.label_order == "decreasing"
        assert dim_label_schema3.label_dtype == np.int32
        assert dim_label_schema3.dim_dtype == np.int32
        assert dim_label_schema3.dim_tile == 2
        assert dim_label_schema3.label_filters is None

        assert dim_label_schema2.label_order == "increasing"
        assert dim_label_schema2.label_dtype == np.float32
        assert dim_label_schema2.dim_dtype == np.int32
        assert dim_label_schema2.dim_tile == 5
        assert dim_label_schema2.label_filters == filter
        assert dim.tile == 10

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    def test_add_to_array_schema(self):
        dim = tiledb.Dim("dim", domain=(1, 10))
        dom = tiledb.Domain(dim)
        att = tiledb.Attr("val", dtype=np.uint64)
        filters = tiledb.FilterList([tiledb.ZstdFilter(10)])
        dim_labels = {
            0: {
                "l1": tiledb.DimLabelSchema(
                    "increasing",
                    label_dtype=np.float64,
                    dim_dtype=dim.dtype,
                    dim_tile=10,
                    label_filters=filters,
                )
            }
        }
        schema = tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels)
        assert schema.has_dim_label("l1")
        assert not schema.has_dim_label("fake_name")

        # Check the dimension label properties
        dim_label = schema.dim_label("l1")
        assert dim_label.dtype == np.float64
        assert not dim_label.isvar
        assert not dim_label.isascii

        # Create array check values in dimension label schema
        uri = self.path("array_with_label")
        tiledb.Array.create(uri, schema)

        # Load the array schema for the dimension label
        base_array_schema = tiledb.ArraySchema.load(uri)
        dim_label = base_array_schema.dim_label("l1")
        label_array_schema = tiledb.ArraySchema.load(dim_label.uri)

        # Chack the array schema for the dimension label
        label_dim = label_array_schema.domain.dim(0)
        assert label_dim.tile == 10
        assert label_dim.dtype == np.uint64
        label_attr = label_array_schema.attr(dim_label.label_attr_name)
        assert label_attr.dtype == np.float64
        assert label_attr.filters == filters

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    def test_add_to_array_schema_out_of_bounds(self):
        dim = tiledb.Dim("label", domain=(1, 10))
        dom = tiledb.Domain(dim)
        att = tiledb.Attr("val", dtype=np.uint64)
        dim_labels = {
            2: {
                "l1": tiledb.DimLabelSchema(
                    "increasing", label_dtype=dim.dtype, dim_dtype=dim.dtype
                )
            }
        }

        with pytest.raises(tiledb.TileDBError):
            tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels)

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    def test_add_to_array_schema_dim_dtype_mismatch(self):
        dim = tiledb.Dim("label", domain=(1, 10))
        dom = tiledb.Domain(dim)
        att = tiledb.Attr("val", dtype=np.uint64)
        dim_labels = {
            2: {
                "label": tiledb.DimLabelSchema(
                    "increasing", label_dtype=dim.dtype, dim_dtype=np.int32
                )
            }
        }

        with pytest.raises(tiledb.TileDBError):
            tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels)

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    @pytest.mark.parametrize("var", [True, False])
    def test_dimension_label_round_trip_dense_array(self, var):
        # Create array schema with dimension labels
        dim = tiledb.Dim("d1", domain=(1, 10))
        dom = tiledb.Domain(dim)
        att = tiledb.Attr("a1", dtype=np.int64)
        dim_labels = {0: {"l1": dim.create_label_schema("increasing", np.int64)}}
        if var:
            dim_labels = {0: {"l1": dim.create_label_schema("increasing", np.bytes_)}}
        schema = tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels)

        # Create array
        uri = self.path("dense_array_with_label")
        tiledb.Array.create(uri, schema)

        # Write data to the array and the label
        attr_data = np.arange(1, 11)
        label_data = np.arange(-9, 10, 2)
        if var:
            label_data = np.array(
                [str(chr(ord("a") + c) * (10 - c)).encode("utf-8") for c in range(10)]
            )
        with tiledb.open(uri, "w") as array:
            array[:] = {"a1": attr_data, "l1": label_data}

        # Load the array schema and get the URI of the dimension label
        schema = tiledb.ArraySchema.load(uri)
        dim_label = schema.dim_label("l1")

        # Read and check the data directly from the dimension label
        with tiledb.open(dim_label.uri, "r") as L1:
            output_data = L1[:]
            output_label_data = output_data[dim_label.label_attr_name]
            np.testing.assert_array_equal(output_label_data, label_data)

        # Read and check the data using label indexer on parent array
        with tiledb.open(uri, "r") as array:
            indexer = array.label_index(["l1"])

            # Read full array
            result = indexer[label_data[0] : label_data[-1]]

            np.testing.assert_array_equal(result["a1"], attr_data)
            np.testing.assert_array_equal(result["l1"], label_data)

            # Read each individual index
            for index in range(10):
                label_index = label_data[index]
                result = indexer[label_index:label_index]
                assert result["a1"][0] == attr_data[index]
                assert result["l1"][0] == label_index

            for index in range(10):
                label_index = label_data[index:]
                result = indexer[label_index[0] : label_index[-1]]
                np.testing.assert_array_equal(result["a1"], attr_data[index:])
                np.testing.assert_array_equal(result["l1"], label_index)

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    @pytest.mark.parametrize("var", [True, False])
    def test_dimension_label_round_trip_multidim_dense_array(self, var):
        # Create array schema with dimension labels
        dim1 = tiledb.Dim("x_index", domain=(1, 8))
        dim2 = tiledb.Dim("y_index", domain=(1, 8))
        dom = tiledb.Domain(dim1, dim2)
        att = tiledb.Attr("value", dtype=np.int64)
        dim_labels = {
            0: {
                "x1": dim1.create_label_schema(
                    "increasing", np.float64 if not var else "U"
                ),
                "x2": dim1.create_label_schema("decreasing", np.int64),
            },
            1: {
                "y1": dim2.create_label_schema("increasing", np.int64),
            },
        }
        schema = tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels)

        # Create array
        uri = self.path("dense_array_with_label")
        tiledb.Array.create(uri, schema)

        # Write data to the array and the label
        attr_data = np.reshape(np.arange(1, 65), (8, 8))
        x1_data = np.linspace(-1.0, 1.0, 8)
        if var:
            x1_data = np.array(
                [str(chr(ord("a") + c - 1) * c).encode("utf-8") for c in range(1, 9)]
            )
        x2_data = np.arange(8, 0, -1)
        y1_data = np.arange(9, 17)
        with tiledb.open(uri, "w") as array:
            array[:, :] = {
                "value": attr_data,
                "x1": x1_data,
                "y1": y1_data,
                "x2": x2_data,
            }

        # Test querying by label
        with tiledb.open(uri, "r") as array:
            # Read full array: labels on both ranges
            result = array.label_index(["x1", "y1"])[x1_data[0] : x1_data[-1], 9:17]
            np.testing.assert_array_equal(result["value"], attr_data)
            np.testing.assert_array_equal(result["x1"], x1_data)
            np.testing.assert_array_equal(result["y1"], y1_data)
            assert "x2" not in result

            # Read full array: label only on first range
            result = array.label_index(["x2"])[0:8]
            np.testing.assert_array_equal(result["value"], attr_data)
            np.testing.assert_array_equal(result["x2"], x2_data)
            assert "x1" not in result
            assert "y1" not in result

            # Read full array: Label only on second range
            result = array.label_index(["y1"])[:, 9:17]
            np.testing.assert_array_equal(result["value"], attr_data)
            np.testing.assert_array_equal(result["y1"], y1_data)
            assert "x1" not in result
            assert "x2" not in result

            # Check conflicting labels are not allowed
            with pytest.raises(tiledb.TileDBError):
                array.label_index(["x1", "x2"])

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    @pytest.mark.parametrize("var", [True, False])
    def test_dimension_label_round_trip_sparse_array(self, var):
        # Create array schema with dimension labels
        dim = tiledb.Dim("index", domain=(1, 10))
        dom = tiledb.Domain(dim)
        att = tiledb.Attr("value", dtype=np.int64)
        dim_labels = {
            0: {
                "l1": dim.create_label_schema(
                    "increasing", np.int64 if not var else "ascii"
                )
            }
        }
        schema = tiledb.ArraySchema(
            domain=dom, attrs=(att,), dim_labels=dim_labels, sparse=True
        )

        # Create array
        uri = self.path("sparse_array_with_label")
        tiledb.Array.create(uri, schema)

        # Write data to the array and the label
        index_data = np.arange(1, 11)
        attr_data = np.arange(11, 21)
        label_data = np.arange(-10, 0)
        if var:
            label_data = np.array(
                [str(chr(ord("a") + c) * (10 - c)).encode("utf-8") for c in range(10)]
            )
        with tiledb.open(uri, "w") as array:
            array[index_data] = {"value": attr_data, "l1": label_data}

        # Load the array schema and get the URI of the dimension label
        schema = tiledb.ArraySchema.load(uri)
        dim_label = schema.dim_label("l1")

        # Read and check the data directly from the dimension label
        with tiledb.open(dim_label.uri, "r") as label1:
            output_label_data = label1[:][dim_label.label_attr_name]
            np.testing.assert_array_equal(output_label_data, label_data)

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    def test_dimension_label_round_trip_dense_var(self):
        # Create array schema with dimension labels
        dims = [
            tiledb.Dim("d1", domain=(1, 10), dtype=np.int64),
            tiledb.Dim("d2", domain=(1, 10), dtype=np.int64),
        ]
        dom = tiledb.Domain(*dims)
        att = tiledb.Attr("value", var=True, dtype="S")
        dim_labels = {
            0: {
                "l1": dims[0].create_label_schema("increasing", np.float32),
            },
            1: {
                "l2": dims[1].create_label_schema("decreasing", np.int32),
                "l3": dims[1].create_label_schema("increasing", np.bytes_),
            },
        }

        schema = tiledb.ArraySchema(
            domain=dom, attrs=(att,), dim_labels=dim_labels, sparse=False
        )

        # Create array
        uri = self.path("dense_array_with_var_label2")
        tiledb.Array.create(uri, schema)

        # Write data to the array and the label
        attr_data = np.array(
            [
                [str(chr(ord("z") - c) * (10 - c)).encode("utf-8") for c in range(10)]
                for i in range(10)
            ]
        )
        l1_data = np.arange(10, dtype=np.float32)
        l2_data = np.arange(10, 0, -1, dtype=np.int32)
        l3_data = np.array(
            [str(chr(ord("a") + c) * (c + 1)).encode("utf-8") for c in range(10)]
        )

        with tiledb.open(uri, "w") as array:
            array[:, :] = {
                "value": attr_data,
                "l1": l1_data,
                "l2": l2_data,
                "l3": l3_data,
            }

        # Load the array schema and get the URI of the dimension label
        schema = tiledb.ArraySchema.load(uri)
        for label_name, label_data in {
            "l1": l1_data,
            "l2": l2_data,
            "l3": l3_data,
        }.items():
            dim_label = schema.dim_label(label_name)
            # Read and check the data directly from the dimension label
            with tiledb.open(dim_label.uri, "r") as label:
                output_label_data = label[:][dim_label.label_attr_name]
                np.testing.assert_array_equal(output_label_data, label_data)

            with tiledb.open(uri, "r") as array:
                indexer = array.label_index([label_name])
                lower = min(label_data[0], label_data[-1])
                upper = max(label_data[0], label_data[-1])
                if label_name == "l1":
                    all_data = indexer[lower:upper]
                else:
                    all_data = indexer[:, lower:upper]
                np.testing.assert_array_equal(all_data[label_name], label_data)
                np.testing.assert_array_equal(all_data["value"], attr_data)

                # Slice array with varying sizes.
                for index in range(10):
                    label_index = label_data[index:]
                    lower = min(label_index[0], label_index[-1])
                    upper = max(label_index[0], label_index[-1])
                    if label_name == "l1":
                        result = indexer[lower:upper]
                        # Check against dim1
                        np.testing.assert_array_equal(
                            result["value"], attr_data[index:, :]
                        )
                    else:
                        result = indexer[:, lower:upper]
                        # Check against dim2
                        np.testing.assert_array_equal(
                            result["value"], attr_data[:, index:]
                        )
                    np.testing.assert_array_equal(result[label_name], label_index)

    @pytest.mark.skipif(
        tiledb.libtiledb.version()[0] == 2 and tiledb.libtiledb.version()[1] < 15,
        reason="dimension labels requires libtiledb version 2.15 or greater",
    )
    def test_dimension_label_on_query(self):
        uri = self.path("query_label_index")

        dim1 = tiledb.Dim("d1", domain=(1, 4))
        dim2 = tiledb.Dim("d2", domain=(1, 3))
        dom = tiledb.Domain(dim1, dim2)
        att = tiledb.Attr("a1", dtype=np.int64)
        dim_labels = {
            0: {"l1": dim1.create_label_schema("decreasing", np.int64)},
            1: {
                "l2": dim2.create_label_schema("increasing", np.int64),
                "l3": dim2.create_label_schema("increasing", np.float64),
            },
        }
        schema = tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels)
        tiledb.Array.create(uri, schema)

        a1_data = np.reshape(np.arange(1, 13), (4, 3))
        l1_data = np.arange(4, 0, -1)
        l2_data = np.arange(-1, 2)
        l3_data = np.linspace(0, 1.0, 3)

        with tiledb.open(uri, "w") as A:
            A[:] = {"a1": a1_data, "l1": l1_data, "l2": l2_data, "l3": l3_data}

        with tiledb.open(uri, "r") as A:
            np.testing.assert_equal(
                A.query().label_index(["l1"])[3:4],
                OrderedDict(
                    {"l1": np.array([4, 3]), "a1": np.array([[1, 2, 3], [4, 5, 6]])}
                ),
            )
            np.testing.assert_equal(
                A.query().label_index(["l1", "l3"])[2, 0.5:1.0],
                OrderedDict(
                    {
                        "l3": np.array([0.5, 1.0]),
                        "l1": np.array([2]),
                        "a1": np.array([[8, 9]]),
                    }
                ),
            )
            np.testing.assert_equal(
                A.query().label_index(["l2"])[:, -1:0],
                OrderedDict(
                    {
                        "l2": np.array([-1, 0]),
                        "a1": np.array([[1, 2], [4, 5], [7, 8], [10, 11]]),
                    },
                ),
            )
            np.testing.assert_equal(
                A.query().label_index(["l3"])[:, 0.5:1.0],
                OrderedDict(
                    {
                        "l3": np.array([0.5, 1.0]),
                        "a1": np.array([[2, 3], [5, 6], [8, 9], [11, 12]]),
                    },
                ),
            )