Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Fix regressions by BrianMichell · Pull Request #2 · BrianMichell/mdio-cpp · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,063 changes: 320 additions & 743 deletions mdio/acceptance_test.cc

Large diffs are not rendered by default.

66 changes: 28 additions & 38 deletions mdio/dataset.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -100,44 +100,27 @@ inline Future<void> write_zmetadata(
inline Future<tensorstore::KvStore> dataset_kvs_store(
const std::string& dataset_path,
tensorstore::Context context = tensorstore::Context::Default()) {
// the tensorstore driver needs a bucket field
::nlohmann::json kvstore;

absl::string_view output_file = dataset_path;

if (absl::StartsWith(output_file, "gs://")) {
absl::ConsumePrefix(&output_file, "gs://");
kvstore["driver"] = "gcs";
} else if (absl::StartsWith(output_file, "s3://")) {
absl::ConsumePrefix(&output_file, "s3://");
kvstore["driver"] = "s3";
} else {
kvstore["driver"] = "file";
std::string path = std::string(output_file);
if (!path.empty() && path.back() != '/') {
path.push_back('/');
}
kvstore["path"] = path;
// Use shared utility to infer driver from path prefix
std::string driver = zarr::InferDriverFromPath(dataset_path);
kvstore["driver"] = driver;

if (driver == "file") {
// Local file system - just normalize with trailing slash
kvstore["path"] = zarr::NormalizePathWithSlash(dataset_path);
return tensorstore::kvstore::Open(kvstore, context);
} // FIXME - we need azure support ...
}

std::vector<std::string> file_parts = absl::StrSplit(output_file, '/');
if (file_parts.size() < 2) {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, path] = zarr::ExtractCloudPath(dataset_path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"gcs/s3 drivers requires [s3/gs]://[bucket]/[path_to_file]");
}

std::string bucket = file_parts[0];
std::string filepath(file_parts[1]);
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
if (!filepath.empty() && filepath.back() != '/') {
filepath.push_back('/');
}
// update the bucket and path ...
kvstore["bucket"] = bucket;
kvstore["path"] = filepath;
kvstore["path"] = zarr::NormalizePathWithSlash(path);

return tensorstore::kvstore::Open(kvstore, context);
}
Expand DownExpand Up@@ -1135,19 +1118,31 @@ class Dataset {
return specJsonResult.status();
}
nlohmann::json specJson = specJsonResult.value();
if (!specJson["metadata"]["dtype"].is_array()) {

// Detect Zarr version from the spec and get the dtype key
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";
bool isV3 = (driverName == "zarr3");
std::string dtype_key = isV3 ? "data_type" : "dtype";

// Ensure that the Variable is of dtype structarray
if (!specJson["metadata"].contains(dtype_key) ||
!specJson["metadata"][dtype_key].is_array()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
"Variable '" + variableName + "' is not a structured dtype.");
}

const auto& dtype_array = specJson["metadata"][dtype_key];

// Ensure the field exists in the Variable
int found = -1;
if (fieldName == "") {
found = -2;
} else {
for (std::size_t i = 0; i < specJson["metadata"]["dtype"].size(); i++) {
if (specJson["metadata"]["dtype"][i][0] == fieldName) {
for (std::size_t i = 0; i < dtype_array.size(); i++) {
if (dtype_array[i][0] == fieldName) {
found = i;
break;
}
Expand All@@ -1159,11 +1154,6 @@ class Dataset {
variableName + "'.");
}

// Detect Zarr version from the spec
std::string driverName = specJson.contains("driver")
? specJson["driver"].get<std::string>()
: "zarr";

// Create a new Variable with the selected field
std::string baseStr = R"(
{
Expand All@@ -1182,7 +1172,7 @@ class Dataset {
"Failed to parse base JSON.");
}
if (found >= 0) {
base["field"] = specJson["metadata"]["dtype"][found][0];
base["field"] = dtype_array[found][0];
} else {
base.erase("field");
}
Expand Down
96 changes: 48 additions & 48 deletions mdio/dataset_factory.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -83,14 +83,10 @@ inline absl::Status transform_dtype(
(version == mdio::zarr::ZarrVersion::kV3) ? "data_type" : "dtype";

if (input["dataType"].contains("fields")) {
if (version == mdio::zarr::ZarrVersion::kV3) {
// V3 doesn't support structured dtypes in the same way
return absl::InvalidArgumentError(
"Structured dtypes are not yet supported in Zarr V3");
}
// Structured dtypes are supported in both V2 and V3
nlohmann::json dtypeFields = nlohmann::json::array();
for (const auto& field : input["dataType"]["fields"]) {
auto dtype = to_zarr_dtype(field["format"]);
auto dtype = to_zarr_dtype(field["format"], version);
if (!dtype.status().ok()) {
return dtype.status();
}
Expand DownExpand Up@@ -256,44 +252,26 @@ inline void transform_shape(
*/
inline absl::Status transform_metadata(const std::string& path,
nlohmann::json& variable /*NOLINT*/) {
std::string bucket =
"NULL"; // Default value, if is NULL don't add a bucket field
std::string driver = "file";
if (absl::StartsWith(path, "gs://")) {
driver = "gcs";
} else if (absl::StartsWith(path, "s3://")) {
driver = "s3";
}
// Use shared utilities for driver inference and path handling
std::string driver = mdio::zarr::InferDriverFromPath(path);
std::string var_name = variable["kvstore"]["path"].get<std::string>();

std::string filepath;
variable["kvstore"]["driver"] = driver;

if (driver != "file") {
std::string _path = path;
// Ensure _path has a trailing slash or the mdio file will not be created
// properly
if (_path.back() != '/') {
_path += '/';
}
_path = _path.substr(5);
std::vector<std::string> file_parts = absl::StrSplit(_path, '/');
if (file_parts.size() < 2) {
if (driver == "file") {
// Local filesystem - normalize path with trailing slash
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(path) + var_name;
} else {
// Cloud storage (GCS or S3) - extract bucket and path
auto [bucket, cloud_path] = mdio::zarr::ExtractCloudPath(path);
if (bucket.empty()) {
return absl::InvalidArgumentError(
"Cloud path requires [gs/s3]://[bucket]/[path to file] name");
}
bucket = file_parts[0];
filepath = file_parts[1];
for (std::size_t i = 2; i < file_parts.size(); ++i) {
filepath += "/" + file_parts[i];
}
filepath += variable["kvstore"]["path"].get<std::string>();
} else {
filepath = path + "/";
filepath += variable["kvstore"]["path"].get<std::string>();
}
variable["kvstore"]["path"] = filepath;
variable["kvstore"]["driver"] = driver;
if (bucket != "NULL") {
variable["kvstore"]["bucket"] = bucket;
variable["kvstore"]["path"] =
mdio::zarr::NormalizePathWithSlash(cloud_path) + var_name;
}

return absl::OkStatus();
Expand DownExpand Up@@ -416,20 +394,42 @@ inline tensorstore::Result<nlohmann::json> from_json_to_spec(
} else {
variableStub["metadata"]["fill_value"] = 0;
}
} else if (version == mdio::zarr::ZarrVersion::kV2) {
// Structured dtypes only for V2
} else {
// Structured dtypes for both V2 and V3
// Accumulate the total number of bytes (N)
uint16_t num_bytes = 0;
std::string dtype;
for (auto field : variableStub["metadata"]["dtype"]) {
dtype = field[1].get<std::string>();
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
std::string dtype_key =
version == mdio::zarr::ZarrVersion::kV3 ? "data_type" : "dtype";
for (const auto& field : variableStub["metadata"][dtype_key]) {
std::string dtype = field[1].get<std::string>();
if (version == mdio::zarr::ZarrVersion::kV2) {
// V2 format: "<i2", "<f4", "<c8", etc. - number is byte size
if (dtype.at(1) != 'c') {
num_bytes += std::stoi(dtype.substr(2));
} else {
// Complex types: c8 = 8 bytes, c16 = 16 bytes
if (dtype.at(2) == '8') {
num_bytes += 8;
} else {
num_bytes += 16;
}
}
} else {
if (dtype.at(2) == '8') {
num_bytes += 8;
// V3 format: "int16", "float32", "complex64", etc. - number is bit
// size
if (dtype.find("complex") == 0) {
// complex64 = 8 bytes, complex128 = 16 bytes
int bits = std::stoi(dtype.substr(7));
num_bytes += bits / 8;
} else if (dtype == "bool") {
num_bytes += 1;
} else {
num_bytes += 16;
// Extract the number from the end (int16 -> 16, float32 -> 32)
size_t pos = dtype.find_first_of("0123456789");
if (pos != std::string::npos) {
int bits = std::stoi(dtype.substr(pos));
num_bytes += bits / 8;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions mdio/regression_tests/xarray_compatibility_test.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ def test_xarray_dataset(file_path, consolidated_metadata):
else:
consolidated_metadata = False
try:
print(f"Opening dataset: {file_path} with consolidated metadata: {consolidated_metadata}")
ds = xr.open_zarr(
file_path,
consolidated=consolidated_metadata,
Expand Down
43 changes: 33 additions & 10 deletions mdio/variable.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,6 @@
#ifndef MDIO_VARIABLE_H_
#define MDIO_VARIABLE_H_

#include <filesystem>
#include <limits>
#include <map>
#include <memory>
Expand DownExpand Up@@ -282,9 +281,13 @@ Result<std::tuple<nlohmann::json, nlohmann::json>> ValidateAndProcessJson(

// 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();
// update the variable name - extract last path component
std::string path = json_spec["kvstore"]["path"].get<std::string>();
// Remove trailing slashes
path = zarr::NormalizePath(path);
// Extract last component (variable name)
std::vector<std::string> path_parts = absl::StrSplit(path, '/');
new_json["variable_name"] = path_parts.empty() ? path : path_parts.back();

return std::make_tuple(json_for_store, new_json);
}
Expand DownExpand Up@@ -437,10 +440,10 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
"Variable metadata requires dtype (V2) or data_type (V3)");
}

// For V3, we don't use ParseDType (which is V2-specific)
// Instead, we handle structured arrays differently
// Handle structured arrays for both V2 and V3
bool do_handle_structarray = false;
tensorstore::internal_zarr::ZarrDType zarr_dtype;
std::string first_field_name;

if (zarr_version == zarr::ZarrVersion::kV2 && has_dtype) {
MDIO_ASSIGN_OR_RETURN(zarr_dtype, tensorstore::internal_zarr::ParseDType(
Expand All@@ -449,12 +452,25 @@ Future<Variable<T, R, M>> CreateVariable(const nlohmann::json& json_spec,
// void.
do_handle_structarray =
zarr_dtype.has_fields && !json_spec.contains("field");
if (do_handle_structarray) {
first_field_name = zarr_dtype.fields[0].name;
}
} else if (zarr_version == zarr::ZarrVersion::kV3 && has_data_type) {
// For V3, structured dtypes are represented as an array of [name, type]
// pairs e.g., [["cdp-x", "int32"], ["cdp-y", "int32"], ...]
const auto& data_type = json_spec["metadata"]["data_type"];
if (data_type.is_array() && !data_type.empty() && data_type[0].is_array() &&
!json_spec.contains("field")) {
do_handle_structarray = true;
// Extract the first field name from the structured dtype
first_field_name = data_type[0][0].get<std::string>();
}
}

auto json_spec_with_open_flag = json_spec;
if (do_handle_structarray) {
// pick the first name, it won't effect the .zarray json:
json_spec_with_open_flag["field"] = zarr_dtype.fields[0].name;
// pick the first field name, it won't affect the zarr.json/zarray:
json_spec_with_open_flag["field"] = first_field_name;
}

auto json_spec_without_metadata = json_spec_with_open_flag;
Expand DownExpand Up@@ -646,10 +662,17 @@ Future<Variable<T, R, M>> OpenVariable(const nlohmann::json& json_store,
nlohmann::json::parse(std::string(kvs_read.value), nullptr, false);
if (zarr_version == zarr::ZarrVersion::kV3) {
// For V3, extract attributes from zarr.json
nlohmann::json result;
if (parsed.contains("attributes")) {
return parsed["attributes"];
result = parsed["attributes"];
} else {
result = nlohmann::json::object();
}
// For V3, dimension_names is at the root level of zarr.json
if (parsed.contains("dimension_names")) {
result["dimension_names"] = parsed["dimension_names"];
}
return nlohmann::json::object();
return result;
}
// For V2, the entire file is attributes
return parsed;
Expand Down
2 changes: 1 addition & 1 deletion mdio/zarr/zarr.h
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
// Copyright 2024 TGS
// Copyright 2026 TGS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down
Loading