forked from TGSAI/mdio-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariable.h
More file actions
1865 lines (1686 loc) · 69.3 KB
/
variable.h
File metadata and controls
1865 lines (1686 loc) · 69.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
// Copyright 2024 TGS
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_
#include <filesystem>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/strings/str_split.h"
#include "mdio/impl.h"
#include "mdio/stats.h"
#include "tensorstore/array.h"
#include "tensorstore/driver/driver.h"
#include "tensorstore/driver/registry.h"
#include "tensorstore/driver/zarr/dtype.h"
#include "tensorstore/index_space/dim_expression.h"
#include "tensorstore/index_space/index_domain_builder.h"
#include "tensorstore/kvstore/kvstore.h"
#include "tensorstore/kvstore/operations.h"
#include "tensorstore/open.h"
#include "tensorstore/stack.h"
#include "tensorstore/tensorstore.h"
#include "tensorstore/util/future.h"
// clang-format off
#include <nlohmann/json.hpp> // NOLINT
// clang-format on
namespace mdio {
template <typename T, DimensionIndex R, ReadWriteMode M>
struct Variable;
template <typename T = void, DimensionIndex R = dynamic_rank,
ArrayOriginKind OriginKind = offset_origin>
struct VariableData;
template <typename T, DimensionIndex R, ArrayOriginKind OriginKind>
struct LabeledArray;
template <typename T>
struct extract_descriptor_Ttype;
template <typename T>
struct outer_type;
/**
* @brief A descriptor for slicing a Variable or Dataset.
* @tparam T The type of the range. Default is `Index` for `isel` based slicing.
* @param label The label of the dimension to slice. The recommended is to use a
* label instead of an index.
* @param start The start index or value of the slice.
* @param stop The stop index or value of the slice.
* @param step The step index or value of the slice. Default is 1.
*/
template <typename T = Index>
struct RangeDescriptor {
using type = T;
/// The label of the dimension to slice. Either a string or an index.
DimensionIdentifier label;
/// The start index or value of the slice.
T start;
/// The stop index or value of the slice.
T stop;
/// The step index or value of the slice. Only 1 is supported currently.
Index step = 1;
};
/**
* @brief A descriptor for slicing a Variable.
* A struct representing how to slice a Variable or Dataset.
* All slices using this will be performed as half open intervals.
* @param label The label of the dimension to slice.
* @param start The start index of the slice.
* @param stop The stop index of the slice.
* @param step The step index of the slice.
* @details \b Usage
* This provides an example of describing a slice for [0, 100) with a step of 1
* along the inline dimension and [0, 200) with a step of 1 along the crossline
* dimension. The depth dimension would remain wholely intact as it is not
* specified.
* @code
* mdio::SliceDescriptor desc1 = {"inline", 0, 100, 1};
* mdio::SliceDescriptor desc2 = {"crossline", 0, 200, 1};
* @endcode
*
* @deprecated This struct is deprecated in favor of using the
* `mdio::RangeDescriptor` struct.
*/
struct SliceDescriptor {
DimensionIdentifier label;
Index start;
Index stop;
Index step;
// Implicit conversion to RangeDescriptor
operator RangeDescriptor<Index>() const { return {label, start, stop, step}; }
};
/**
* @brief A descriptor for slicing a single dimension value from a Dataset.
* This structure is not supported for index-based slicing.
* @tparam T The type of the value.
* @param label The label of the dimension to slice.
* @param value The value to slice.
*/
template <typename T>
struct ValueDescriptor {
using type = T;
/// The label of the dimension to slice.
DimensionIdentifier label;
/// The value to slice.
T value;
};
/**
* @brief A descriptor for slicing a list of values from a Dataset.
* This structure is not supported for index-based slicing.
* @tparam T The type of the values.
* @param label The label of the dimension to slice.
* @param values The vector of values to slice.
*/
template <typename T>
struct ListDescriptor {
using type = T;
/// The label of the dimension to slice.
DimensionIdentifier label;
/// The vector of values to slice.
std::vector<T> values;
};
template <typename T>
struct outer_type {
using type = T;
};
template <template <typename> class Outer, typename T>
struct outer_type<Outer<T>> {
using type = Outer<T>;
};
// Specialization for lvalue references
template <typename T>
struct outer_type<T&> {
using type = typename outer_type<std::remove_reference_t<T>>::type;
};
// Specialization for rvalue references
template <typename T>
struct outer_type<T&&> {
using type = typename outer_type<std::remove_reference_t<T>>::type;
};
template <typename T>
struct extract_descriptor_Ttype {
using type = T;
};
template <typename T>
struct extract_descriptor_Ttype<RangeDescriptor<T>> {
using type = T;
};
template <typename T>
struct extract_descriptor_Ttype<ValueDescriptor<T>> {
using type = T;
};
template <typename T>
struct extract_descriptor_Ttype<ListDescriptor<T>> {
using type = T;
};
// Specialization for lvalue references
template <typename T>
struct extract_descriptor_Ttype<T&> {
using type =
typename extract_descriptor_Ttype<std::remove_reference_t<T>>::type;
};
// Specialization for rvalue references
template <typename T>
struct extract_descriptor_Ttype<T&&> {
using type =
typename extract_descriptor_Ttype<std::remove_reference_t<T>>::type;
};
namespace internal {
/**
* @brief Checks a status for a missing driver message and returns an MDIO
* specific error message.
* @param status The status to check
* @return A driver specific message if the status is a missing driver message,
* otherwise the original status.
*/
inline absl::Status CheckMissingDriverStatus(const absl::Status& status) {
std::string error(status.message());
if (error.find("Error parsing object member \"driver\"") !=
std::string::npos) {
if (error.find("is not registered") != std::string::npos) {
if (error.find("gcs") != std::string::npos) {
return absl::InvalidArgumentError(
"A GCS path was detected but the GCS driver was not "
"registered.\nPlease ensure that your CMake includes the "
"mdio_INTERNAL_GCS_DRIVER_DEPS variable.");
} else if (error.find("s3") != std::string::npos) {
return absl::InvalidArgumentError(
"An S3 path was detected but the S3 driver was not "
"registered.\nPlease ensure that your CMake includes the "
"mdio_INTERNAL_S3_DRIVER_DEPS variable.");
} else {
return absl::InvalidArgumentError(
"An unexpected driver registration error has occured. Please file "
"a bug report with the error message to "
"https://github.com/TGSAI/mdio-cpp/issues\n" +
error);
}
}
}
return status;
}
/**
* @brief Validates and processes a JSON specification for a tensorstore
* variable.
*
* This function validates and processes the JSON specification for a zarr V2
* tensorstore variable. It expects the JSON specification will have a field
* called attributes that contains a field called dimension_names. This is a
* specification of MDIO and is not specifically required by zarr V2
*
* @tparam Mode The read-write mode to use.
* @param json_spec The JSON specification to validate and process.
* @return A tuple containing the processed JSON specification and a new JSON
* object with the kvstore and updated variable name.
* @throws absl::InvalidArgumentError if the JSON specification is invalid
* (according to the MDIO standard).
*/
template <ReadWriteMode Mode = ReadWriteMode::dynamic>
Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(
const nlohmann::json& json_spec) {
// Check if attributes are in the original JSON
if (!json_spec.contains("attributes")) {
return absl::InvalidArgumentError(
"The json_spec does not contain 'attributes'.");
}
// Check if dimensions field exists in attributes
if (!json_spec["attributes"].contains("dimension_names")) {
return absl::InvalidArgumentError(
"The 'attributes' does not contain 'dimension_names'.");
}
nlohmann::json json_for_store = json_spec;
// remove attributes, the v2 store won't parse it.
json_for_store.erase("attributes");
// Create a new JSON and add the kvstore
nlohmann::json new_json = json_spec["attributes"];
// update the variable name
new_json["variable_name"] =
std::filesystem::path(json_spec["kvstore"]["path"]).stem().string();
return std::make_tuple(json_for_store, new_json);
}
/**
* @brief Creates a Variable object.
*
* Parses the JSON spec for attributes constructs the Variable object according
* to the MDIO standard.
*
* @tparam T The data type of the Variable.
* @tparam R The rank of the Variable.
* @tparam M The read-write mode of the Variable.
* @param spec The JSON specification to parse. `spec` is expected to contain
* ["attributes"]["variable_name"] and ["attributes"]["dimension_names"].
* @param store The TensorStore to use for the Variable.
* @return A Result object containing the created Variable.
*/
template <typename T = void, DimensionIndex R = dynamic_rank,
ReadWriteMode M = ReadWriteMode::dynamic>
Result<Variable<T, R, M>> from_json(
const ::nlohmann::json spec,
const tensorstore::TensorStore<T, R, M> store) {
auto attributes = spec;
// There seems to be a case where we don't actually strip out the super
// attributes field by this point.
if (attributes.contains("attributes") &&
attributes["attributes"].contains("variable_name")) {
attributes = attributes["attributes"];
}
if (!attributes.contains("variable_name")) {
return absl::NotFoundError("Could not find Variable's name.");
}
std::string name = attributes["variable_name"];
nlohmann::json scrubbed_spec = attributes;
scrubbed_spec.erase("variable_name");
auto specWithoutChunkgrid = spec;
if (specWithoutChunkgrid.contains("metadata")) {
if (specWithoutChunkgrid["metadata"].contains("chunkGrid")) {
specWithoutChunkgrid["metadata"].erase("chunkGrid");
}
}
auto attrsRes = UserAttributes::FromVariableJson(specWithoutChunkgrid);
if (!attrsRes.ok()) {
return attrsRes.status();
}
// Default case.
// TODO(BrianMichell): Look into making this optional.
std::string long_name = "";
if (scrubbed_spec.contains("long_name")) {
if (scrubbed_spec["long_name"].is_string() &&
scrubbed_spec["long_name"].get<std::string>().size() > 0) {
long_name = scrubbed_spec["long_name"].get<std::string>();
} else {
scrubbed_spec.erase("long_name");
}
} // Not having this field is fine. If it doesn't get seralized returning an
// error status is not necessary.
// These live in our `UserAttributes` object and are technically mutable. The
// best kind of mutable!
if (scrubbed_spec.contains("metadata")) {
if (scrubbed_spec["metadata"].contains("attributes")) {
scrubbed_spec["metadata"].erase("attributes");
}
if (scrubbed_spec["metadata"].contains("statsV1")) {
scrubbed_spec["metadata"].erase("statsV1");
}
if (scrubbed_spec["metadata"].contains("unitsV1")) {
scrubbed_spec["metadata"].erase("unitsV1");
}
}
std::shared_ptr<std::shared_ptr<UserAttributes>> attrs =
std::make_shared<std::shared_ptr<UserAttributes>>(
std::make_shared<UserAttributes>(attrsRes.value()));
const void* attributesAddress = static_cast<const void*>(&attributes);
// clang-format off
Variable<T, R, M> res = {
name,
long_name,
scrubbed_spec,
store,
attrs
};
// clang-format on
return res;
}
/**
* @brief Creates a new variable with the given attributes and returns a future
* that will be fulfilled with the created variable. Provide an Open method for
* a new file ...
* @tparam T The element type of the variable.
* @tparam R The rank of the variable.
* @tparam M The read-write mode of the variable.
* @param json_store The JSON object representing the TensorStore to create the
* variable in.
* @param json_var The JSON object representing the attributes of the variable
* to create.
* @param options The transactional open options to use when opening the
* TensorStore.
* @return absl::StatusCode::kInvalidArgument if the attributes are empty.
* @return mdio::Future<Variable<T, R, M>> A future that will be fulfilled with
* the created variable.
*/
template <typename T = void, DimensionIndex R = dynamic_rank,
ReadWriteMode M = ReadWriteMode::dynamic, typename... Option>
Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
const nlohmann::json& json_var,
Option&&... options) {
auto spec = tensorstore::MakeReadyFuture<::nlohmann::json>(json_var);
// FIXME - add schematized validation of the variable.
if (json_var.empty()) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Expected attributes to be non-empty.");
}
if (!json_spec.contains("metadata")) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Variable spec requires metadata");
}
if (!json_spec["metadata"].contains("dtype")) {
return absl::Status(absl::StatusCode::kInvalidArgument,
"Variable metadata requires dtype");
}
MDIO_ASSIGN_OR_RETURN(auto zarr_dtype, tensorstore::internal_zarr::ParseDType(
json_spec["metadata"]["dtype"]))
// Handles the use case of creating a struct array, but intending to open as
// void.
auto do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
auto json_spec_with_field = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_field["field"] = zarr_dtype.fields[0].name;
}
auto json_spec_without_metadata = json_spec;
json_spec_without_metadata.erase("metadata");
auto future_json_store = tensorstore::MakeReadyFuture<::nlohmann::json>(
json_spec_without_metadata);
auto publish = [](const ::nlohmann::json& json_var, bool isCloudStore,
const tensorstore::TensorStore<T, R, M>& store)
-> Future<tensorstore::TimestampedStorageGeneration> {
auto output_json = json_var;
output_json["_ARRAY_DIMENSIONS"] = output_json["dimension_names"];
output_json.erase("dimension_names");
output_json.erase("variable_name");
if (output_json.contains("metadata")) {
output_json["metadata"].erase("chunkGrid");
for (auto& item : output_json["metadata"].items()) {
output_json[item.key()] = std::move(item.value());
}
output_json.erase("metadata");
}
if (output_json.contains("long_name")) {
if (output_json["long_name"] == "") {
output_json.erase("long_name");
}
}
// Case where empty array of coordinates is provided
if (output_json.contains("coordinates")) {
auto coords = output_json["coordinates"];
if (coords.empty() ||
(coords.is_string() && coords.get<std::string>() == "")) {
output_json.erase("coordinates");
}
}
std::string outpath = "/.zattrs";
if (isCloudStore) {
outpath = ".zattrs";
}
// It's important to use the store's kvstore or else we get a race condition
// on "mkdir".
return tensorstore::kvstore::Write(store.kvstore(), outpath,
absl::Cord(output_json.dump(4)));
};
// this is intended to handle the struct array where we "reopen" the store
// but this time as struct ... but we loose the capactity for forward options.
// FIXME - strip "create/delete existing" and foward other options.
auto apply_reopen = [](const tensorstore::TensorStore<T, R, M>& store,
const ::nlohmann::json& attributes,
const ::nlohmann::json& json_spec) {
return tensorstore::Open<T, R, M>(json_spec);
};
auto build = [](const ::nlohmann::json& metadata,
const tensorstore::TensorStore<T, R, M>& store)
-> Future<Variable<T, R, M>> {
auto labeled_store = store;
if (metadata.contains("dimension_names")) {
auto dimension_names =
metadata["dimension_names"].get<std::vector<std::string>>();
for (DimensionIndex i = 0; i < dimension_names.size(); ++i) {
MDIO_ASSIGN_OR_RETURN(
labeled_store,
labeled_store | tensorstore::Dims(i).Label(dimension_names[i]));
}
}
return from_json<T, R, M>(metadata, labeled_store);
};
// Start by creating a future for the store ...
auto future_store = tensorstore::Open<T, R, M>(
json_spec_with_field, std::forward<Option>(options)...);
auto handled_store = future_store;
if (do_handle_structarray) {
handled_store =
tensorstore::MapFutureValue(tensorstore::InlineExecutor{}, apply_reopen,
future_store, spec, future_json_store);
} else {
handled_store = std::move(future_store);
}
auto variable_future = tensorstore::MapFutureValue(
tensorstore::InlineExecutor{}, build, spec, handled_store);
bool isCloudStore = false;
std::string driver = json_spec["kvstore"]["driver"].get<std::string>();
if (driver == "gcs" || driver == "s3") {
isCloudStore = true;
}
auto isCloudStoreRF = tensorstore::MakeReadyFuture<bool>(isCloudStore);
auto write_metadata_future =
tensorstore::MapFutureValue(tensorstore::InlineExecutor{}, publish, spec,
isCloudStoreRF, handled_store);
// wait for the variable to be created and the zattrs to be written.
auto all_done_future =
tensorstore::WaitAllFuture(variable_future, write_metadata_future);
auto pair = tensorstore::PromiseFuturePair<Variable<T, R, M>>::Make();
all_done_future.ExecuteWhenReady(
[promise = pair.promise, variable_future = std::move(variable_future)](
tensorstore::ReadyFuture<void> readyFut) {
auto ready_result = readyFut.result();
if (!ready_result.ok()) {
promise.SetResult(CheckMissingDriverStatus(ready_result.status()));
} else {
promise.SetResult(variable_future.result());
}
});
return pair.future;
}
/**
* @brief Opens a Variable from a JSON specification.
* Provide an Open method for an existing file...
* @tparam T The data type of the Variable.
* @tparam R The rank of the Variable.
* @tparam M The read-write mode of the Variable.
* @param json_store The JSON specification of the store.
* @param options The transactional open options.
* @return mdio::Future<Variable<T, R, M>> A future that resolves to the opened
* Variable.
*/
template <typename T = void, DimensionIndex R = dynamic_rank,
ReadWriteMode M = ReadWriteMode::dynamic, typename... Option>
Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
Option&&... options) {
// Infer the name from the path
std::string variable_name = json_store["kvstore"]["path"].get<std::string>();
std::vector<std::string> pathComponents = absl::StrSplit(variable_name, "/");
variable_name = pathComponents.back();
auto store_spec = json_store;
// retain attributes if we want to check values ...
::nlohmann::json suppliedAttributes;
if (store_spec.contains("attributes")) {
suppliedAttributes["attributes"] = store_spec["attributes"];
store_spec.erase("attributes");
}
// attributes is not a valid key for the tensorstore open ...
// FIXME - resolve opening struct array with field and no metadata
// updates to Tensorstore required ...
if (!store_spec.contains("field") && store_spec.contains("metadata")) {
store_spec.erase("metadata");
}
// the negative of this is valid for tensorstore ...
// TODO(BrianMichell): Look into making the recheck_cached_data an open
// option. store_spec["recheck_cached_data"] = false; // This could become
// problematic if we are doing read/write operations.
auto spec = tensorstore::MakeReadyFuture<::nlohmann::json>(store_spec);
// open a store:
auto future_store =
tensorstore::Open<T, R, M>(store_spec, std::forward<Option>(options)...);
// start by creating a kvstore future ...
auto kvs_future = tensorstore::kvstore::Open(store_spec["kvstore"]);
// go read the metadata return json ...
auto read = [](const tensorstore::KvStore& kvstore)
-> Future<tensorstore::kvstore::ReadResult> {
return tensorstore::kvstore::Read(kvstore, "/.zattrs");
};
// go read the attributes return json ...
auto parse = [](const tensorstore::kvstore::ReadResult& kvs_read,
const ::nlohmann::json& spec) {
auto attributes =
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
return attributes;
};
auto make_variable = [variable_name](
const ::nlohmann::json& metadata,
const tensorstore::TensorStore<T, R, M>& store,
const ::nlohmann::json& suppliedAttributes)
-> Future<Variable<T, R, M>> {
// use to load the store
tensorstore::TensorStore<T, R, M> labeled_store = store;
::nlohmann::json updated_metadata = metadata;
// Create a new JSON object with "attributes" as the parent key
::nlohmann::json new_metadata;
new_metadata = updated_metadata;
new_metadata["variable_name"] = variable_name;
if (new_metadata.contains("_ARRAY_DIMENSIONS")) {
// Move "_ARRAY_DIMENSIONS" to "dimension_names"
new_metadata["dimension_names"] = new_metadata["_ARRAY_DIMENSIONS"];
new_metadata.erase("_ARRAY_DIMENSIONS");
}
if (new_metadata.contains("dimension_names")) {
auto dimension_names =
new_metadata["dimension_names"].get<std::vector<std::string>>();
for (DimensionIndex i = 0; i < dimension_names.size(); ++i) {
MDIO_ASSIGN_OR_RETURN(
labeled_store,
labeled_store | tensorstore::Dims(i).Label(dimension_names[i]));
}
} else {
return absl::NotFoundError(
absl::StrCat("Field not found in JSON: ", "metadata"));
}
if (new_metadata.contains("attributes")) {
new_metadata["metadata"]["attributes"] = new_metadata["attributes"];
new_metadata.erase("attributes");
}
if (new_metadata.contains("statsV1")) {
new_metadata["metadata"]["statsV1"] = new_metadata["statsV1"];
new_metadata.erase("statsV1");
}
if (new_metadata.contains("unitsV1")) {
new_metadata["metadata"]["unitsV1"] = new_metadata["unitsV1"];
new_metadata.erase("unitsV1");
}
if (!suppliedAttributes.is_null()) {
// The supplied attributes contain some things that we do not serialize.
// We need to remove them. This could cause confusion. If the user
// specifies a different chunkGrid, it will not be used and should
// actually fail here.
nlohmann::json correctedSuppliedAttrs = suppliedAttributes;
if (correctedSuppliedAttrs.contains("attributes")) {
if (correctedSuppliedAttrs["attributes"].contains("metadata")) {
if (correctedSuppliedAttrs["attributes"]["metadata"].contains(
"chunkGrid")) {
correctedSuppliedAttrs["attributes"]["metadata"].erase("chunkGrid");
}
}
auto savedAttrs = correctedSuppliedAttrs["attributes"];
correctedSuppliedAttrs.erase("attributes");
for (auto& item : savedAttrs.items()) {
correctedSuppliedAttrs[item.key()] = std::move(item.value());
}
}
// BFS to make sure supplied attributes match stored attributes
nlohmann::json searchableMetadata = new_metadata;
if (searchableMetadata.contains("variable_name")) {
// Since we don't actually want to have to specify the variable name
searchableMetadata.erase("variable_name");
}
std::queue<std::pair<nlohmann::json, nlohmann::json>> queue;
queue.push({searchableMetadata, correctedSuppliedAttrs});
while (!queue.empty()) {
auto [currentMetadata, currentAttributes] = queue.front();
queue.pop();
for (auto& [key, value] : currentMetadata.items()) {
if (!currentAttributes.contains(key)) {
return absl::NotFoundError(
absl::StrCat("Field not found in JSON: ", key));
}
if (value.is_object() && currentAttributes[key].is_object()) {
// If the value is a JSON object, add it to the queue for further
// processing
queue.push({value, currentAttributes[key]});
} else if (value != currentAttributes[key]) {
return absl::InvalidArgumentError(absl::StrCat(
"Conflicting values for field: ", key, ". ", "Expected: ",
value.dump(4), ", but got: ", currentAttributes[key].dump(4)));
}
}
}
}
return from_json<T, R, M>(new_metadata, labeled_store);
};
// a future to the metadata ...
auto kvs_read_future = tensorstore::MapFutureValue(
tensorstore::InlineExecutor{}, read, kvs_future);
auto metadata = tensorstore::MapFutureValue(tensorstore::InlineExecutor{},
parse, kvs_read_future, spec);
return tensorstore::MapFutureValue(
tensorstore::InlineExecutor{}, make_variable, metadata, future_store,
tensorstore::MakeReadyFuture<::nlohmann::json>(suppliedAttributes));
}
/**
* @brief Opens or creates a Variable object from a JSON specification.
* Provide an Open method for an existing file...
* @tparam T The data type of the Variable.
* @tparam R The rank of the Variable.
* @tparam M The read/write mode of the Variable.
* @param json_spec The JSON specification of the Variable.
* @param options The transactional open options.
* @return A future that resolves to the opened or created Variable object.
*/
template <typename T = void, DimensionIndex R = dynamic_rank,
ReadWriteMode M = ReadWriteMode::dynamic>
Future<Variable<T, R, M>> Open(const nlohmann::json& json_spec,
TransactionalOpenOptions&& options) {
// situations where we would create new metadata
if (options.open_mode == constants::kCreateClean ||
options.open_mode == constants::kCreate) {
MDIO_ASSIGN_OR_RETURN(auto json_schema, ValidateAndProcessJson(json_spec))
// extract the json for the store and our metadata
auto [json_store, metadata] = json_schema;
// this will write metadata
return CreateVariable<T, R, M>(json_store, metadata, std::move(options));
} else {
return OpenVariable<T, R, M>(json_spec, std::move(options));
}
}
} // namespace internal
/**
* @brief A templated struct representing an MDIO Variable with a tensorstore.
* This is an MDIO specified zarr V2 tensorstore variable.
* It represents the non-volitile (on-disk, in-cloud, etc.) data.
*
* @tparam T The type of the data stored in the tensorstore.
* @tparam R The rank of the tensorstore.
* @tparam M The read-write mode of the tensorstore.
* @param variableName The name of the variable.
* @param longName The optional long name of the variable.
* @param metadata Any metadata associated with the variable.
* @param store The underlying Tensorstore.
* @param attributes The user attributes associated with the variable.
*/
template <typename T = void, DimensionIndex R = dynamic_rank,
ReadWriteMode M = ReadWriteMode::dynamic>
class Variable {
public:
Variable() = default;
Variable(const std::string& variableName, const std::string& longName,
const ::nlohmann::json& metdata,
const tensorstore::TensorStore<T, R, M>& store,
const std::shared_ptr<std::shared_ptr<UserAttributes>> attributes)
: variableName(variableName),
longName(longName),
metadata(metdata),
store(store),
attributes(attributes) {
attributesAddress = reinterpret_cast<std::uintptr_t>((*attributes).get());
}
// Allows for conversion to compatible types (SourceElement), which should
// always be possible to void.
template <typename SourceElement, DimensionIndex SourceRank,
ReadWriteMode SourceMode>
Variable(const Variable<SourceElement, SourceRank, SourceMode>& other)
: variableName(other.get_variable_name()),
longName(other.get_long_name()),
metadata(other.getReducedMetadata()),
store(other.get_store()),
attributes(other.attributes),
attributesAddress(other.get_attributes_address()) {}
friend std::ostream& operator<<(std::ostream& os, const Variable& obj) {
os << obj.variableName << "\t" << obj.dimensions() << "\n";
os << obj.store.dtype() << "\t" << obj.store.rank();
return os;
}
/**
* @brief Opens a variable with the specified options.
* Provide an Open method for an existing file...
* @tparam T The element type of the variable. Defaults to `void`.
* @tparam R The rank of the variable. Defaults to `mdio::dynamic_rank`.
* @tparam M The read/write mode of the variable. Defaults to
* `mdio::ReadWriteMode::dynamic`.
* @tparam Option The options to use when opening the variable.
* @param json_spec The JSON specification of the variable to open.
* @param option The options to use when opening the variable.
* @return An `mdio::Future` that resolves to a `Variable` object.
*
* This function opens an existing Variable with the specified options.
*/
template <typename... Option>
static std::enable_if_t<(tensorstore::IsCompatibleOptionSequence<
TransactionalOpenOptions, Option...>),
Future<Variable<T, R, M>>>
Open(const nlohmann::json& json_spec, Option&&... option) {
TENSORSTORE_INTERNAL_ASSIGN_OPTIONS_OR_RETURN(TransactionalOpenOptions,
options, option)
return mdio::internal::Open<T, R, M>(json_spec, std::move(options));
}
/**
* @brief Read the data from the variable.
* Reads the data from the source variable.
* Provide an Open method for an existing file...
* @tparam T The type of the data to be read.
* @tparam R The tensorstore rank of the data to be read.
* @tparam M The read/write mode of the data to be read.
* @param variable A Variable object with the source store.
* @return A future of VariableData that will be ready when the read is
* complete.
*/
template <ArrayOriginKind OriginKind = offset_origin>
Future<VariableData<T, R, OriginKind>> Read() {
auto data = tensorstore::Read(store);
// We need to capture this to ensure the Variable doesn't get prematurely
// destoryed if its parent goes out of scope before the future resolves.
auto thisVar = std::make_shared<Variable<T, R, M>>(*this);
auto pair =
tensorstore::PromiseFuturePair<VariableData<T, R, OriginKind>>::Make();
data.ExecuteWhenReady(
[thisVar, promise = pair.promise](
tensorstore::ReadyFuture<SharedArray<T, R, OriginKind>> readyFut) {
auto ready_result = readyFut.result();
if (!ready_result.ok()) {
promise.SetResult(ready_result.status());
} else {
LabeledArray<T, R, OriginKind> labeledArray{thisVar->dimensions(),
ready_result.value()};
VariableData<T, R, OriginKind> variableData{
thisVar->variableName, thisVar->longName,
thisVar->getMetadata(), labeledArray};
promise.SetResult(variableData);
}
});
return pair.future;
}
/**
* @brief Write the data to the variable.
* Writes the data from the source variable data to the target variable.
* @param source A VariableData object with the data to write. This is the
* in-memory representation of the data.
* @param target A Variable object with the target store. This is the
* non-volitile representation of the data.
*
* @details \b Usage
* This provides an example of writing the data from the source variable data
* to the target variable.
* @code
* MDIO_ASSIGN_OR_RETURN(auto velocity, mdio::Variable<>::Open(velocity_path,
* mdio::constants::kOpen));
* // Get an empty version of the Variable.
* MDIO_ASSIGN_OR_RETURN(auto velocityData, mdio::from_variable(velocity));
* // Do some manipulation of velocity here before writing it out.
* auto velocityWriteFuture = velocity.Write(velocityData);
* // This is a future. It will be ready when the write is complete.
* @endcode
* @return A future that will be ready when the write is complete.
*/
template <ArrayOriginKind OriginKind = offset_origin>
WriteFutures Write(const VariableData<T, R, OriginKind> source) const {
if (source.dtype() != this->dtype()) {
return absl::InvalidArgumentError(
"The source and target dtypes do not match.");
}
return tensorstore::Write(source.data.data, store);
}
/**
* @brief Returns the index domain view of the variable.
* Specifies the origin, shape and labels of the domain
* @return The index domain view of the variable.
*/
IndexDomainView<R> dimensions() const { return store.domain(); }
/**
* @brief Gets the rank of the variable.
* @return std::size_t The rank of the variable.
*/
std::size_t rank() const { return store.rank(); }
/**
* @brief Returns the number of samples in the variable.
* @return Index The number of samples in the variable.
*/
Index num_samples() const {
// Accessing the shape
auto shape = dimensions().shape();
// Calculating the total number of elements
size_t totalElements = 1;
for (auto dim_size : shape) {
totalElements *= dim_size;
}
return totalElements;
}
/**
* @brief Get the data type of the tensor store.
* The type of the store, T ~ void
* @return The data type of the tensor store.
*/
DataType dtype() const { return store.dtype(); }
/**
* @brief Retrieves the specification of the variable.
* Includes information about the compressor etc.
* This function returns an `mdio::Result` object containing the specification
* of the variable.
* @return An `mdio::Result` object containing the specification of the
* variable.
*/
Result<Spec> spec() const { return store.spec(); }
/**
* @brief Checks if the Variable contains a specified label
* @param labelToCheck The label to check for
* @return true if the Variable contains the label, false otherwise
*/
bool hasLabel(const DimensionIdentifier& labelToCheck) const {
// if it's an index slice, that is always valid ...
if (!labelToCheck.label().data()) {
auto rank = store.domain().rank();
// and we're in bounds
return (labelToCheck.index() < rank && labelToCheck.index() >= 0);
}
// otherwise see if the label is in the domain
const auto labels = store.domain().labels();
for (const auto& label : labels) {
if (label == labelToCheck) {
return true;
}
}
return false;
}
/**
* @brief Clamps a slice descriptor to the domain of the Variable.
* Intended for internal use.
* @param desc The slice descriptor to be clamped
* @return A slice descriptor that will not go out-of-bounds for the given
* Variable.
*/
RangeDescriptor<Index> sliceInRange(
const RangeDescriptor<Index>& desc) const {
auto domain = dimensions();
const auto labels = domain.labels();
for (size_t idx = 0; idx < labels.size(); ++idx) {
if (labels[idx] == desc.label) {
// Clamp the descriptor to the domain using absolute coordinates.
// NOTE: domain.shape()[idx] is a size, not an absolute upper bound when
// the origin is non-zero. The correct exclusive upper bound is
// origin + shape.
Index dim_origin = domain.origin()[idx];
Index dim_upper = dim_origin + domain.shape()[idx]; // exclusive
Index clamped_start = desc.start < dim_origin ? dim_origin : desc.start;
Index clamped_stop = desc.stop > dim_upper ? dim_upper : desc.stop;
return {desc.label, clamped_start, clamped_stop, desc.step};
}
}
// We don't slice along a dimension that doesn't exist, so the descriptor is
// valid
return desc;
}
template <size_t... I>
struct index_sequence {};
template <size_t N, size_t... I>
struct make_index_sequence : make_index_sequence<N - 1, N - 1, I...> {};
template <size_t... I>
struct make_index_sequence<0, I...> : index_sequence<I...> {};
template <std::size_t... I>
Result<Variable> call_slice_with_vector_impl(
const std::vector<RangeDescriptor<Index>>& slices,
std::index_sequence<I...>) {
return slice(slices[I]...);
}
/**