1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
|
/* Copyright (c) 2008-2025 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include <fstream>
#include <sstream>
#include "file/json_utils.h"
#include "file/nifti_utils.h"
#include "app.h"
#include "axes.h"
#include "dwi/gradient.h"
#include "exception.h"
#include "header.h"
#include "metadata/bids.h"
#include "metadata/phase_encoding.h"
#include "metadata/slice_encoding.h"
#include "mrtrix.h"
#include "types.h"
#include "file/ofstream.h"
namespace MR
{
namespace File
{
namespace JSON
{
void load (Header& H, const std::string& path)
{
std::ifstream in (path);
if (!in)
throw Exception ("Error opening JSON file \"" + path + "\"");
nlohmann::json json;
try {
in >> json;
} catch (std::logic_error& e) {
throw Exception ("Error parsing JSON file \"" + path + "\": " + e.what());
}
read (json, H);
}
void save (const Header& H, const std::string& json_path, const std::string& image_path)
{
nlohmann::json json;
write (H, json, image_path);
File::OFStream out (json_path);
out << json.dump(4);
}
KeyValues read (const nlohmann::json& json)
{
KeyValues result;
for (auto i = json.cbegin(); i != json.cend(); ++i) {
if (i->is_boolean()) {
result.insert (std::make_pair (i.key(), i.value() ? "true" : "false"));
} else if (i->is_number_integer() || i->is_number_float()) {
result.insert (std::make_pair (i.key(), i->dump()));
} else if (i->is_string()) {
const std::string s = unquote(i.value());
result.insert (std::make_pair (i.key(), s));
} else if (i->is_array()) {
size_t num_subarrays = 0;
for (const auto& j : *i)
if (j.is_array())
++num_subarrays;
if (num_subarrays == 0) {
bool all_string = true;
bool all_numeric = true;
for (const auto& k : *i) {
if (!k.is_string())
all_string = false;
if (!(k.is_number()))
all_numeric = false;
}
if (all_string) {
vector<std::string> lines;
for (const auto& k : *i)
lines.push_back (unquote(k));
result.insert (std::make_pair (i.key(), join (lines, "\n")));
} else if (all_numeric) {
vector<std::string> line;
for (const auto& k : *i)
line.push_back (str(k));
result.insert (std::make_pair (i.key(), join (line, ",")));
} else {
throw Exception ("JSON entry \"" + i.key() + "\" is array but contains mixed data types");
}
}
else if (num_subarrays == i->size()) {
vector<std::string> s;
for (const auto& j : *i) {
vector<std::string> line;
for (const auto& k : j)
line.push_back (unquote(str(k)));
s.push_back (join(line, ","));
}
result.insert (std::make_pair (i.key(), join(s, "\n")));
}
else
throw Exception ("JSON entry \"" + i.key() + "\" contains mixture of elements and arrays");
}
}
return result;
}
void read(const nlohmann::json &json, Header &header) {
KeyValues keyval = read(json);
// Reorientation based on image load should be applied
// exclusively to metadata loaded via JSON; not anything pre-existing
Metadata::PhaseEncoding::transform_for_image_load(keyval, header);
Metadata::SliceEncoding::transform_for_image_load(keyval, header);
header.merge_keyval(keyval);
}
namespace {
template <typename T>
bool attempt_scalar (const std::pair<std::string, std::string>& kv, nlohmann::json& json)
{
try {
const T temp = to<T> (kv.second);
json[kv.first] = temp;
return true;
} catch (...) { }
return false;
}
bool attempt_matrix (const std::pair<std::string, std::string>& kv, nlohmann::json& json)
{
try {
auto M_float = parse_matrix<default_type> (kv.second);
if (M_float.cols() == 1)
M_float.transposeInPlace();
nlohmann::json temp;
bool noninteger = false;
for (ssize_t row = 0; row != M_float.rows(); ++row) {
vector<default_type> data (M_float.cols());
for (ssize_t i = 0; i != M_float.cols(); ++i) {
data[i] = M_float (row, i);
if (std::floor (data[i]) != data[i])
noninteger = true;
}
if (row)
temp[kv.first].push_back (data);
else if (M_float.rows() == 1)
temp[kv.first] = data;
else
temp[kv.first] = { data };
}
if (noninteger) {
json[kv.first] = temp[kv.first];
} else {
// No non-integer values found;
// Write the data natively as integers
auto M_int = parse_matrix<int> (kv.second);
if (M_int.cols() == 1)
M_int.transposeInPlace();
temp[kv.first] = nlohmann::json({});
for (ssize_t row = 0; row != M_int.rows(); ++row) {
vector<int> data (M_int.cols());
for (ssize_t i = 0; i != M_int.cols(); ++i)
data[i] = M_int (row, i);
if (row)
temp[kv.first].push_back (data);
else if (M_int.rows() == 1)
temp[kv.first] = data;
else
temp[kv.first] = { data };
}
json[kv.first] = temp[kv.first];
}
return true;
} catch (...) { return false; }
}
}
void write (const KeyValues& keyval, nlohmann::json& json)
{
auto write_string = [] (const std::pair<std::string, std::string>& kv,
nlohmann::json& json)
{
const auto lines = split_lines (kv.second);
if (lines.size() > 1)
json[kv.first] = lines;
else
json[kv.first] = kv.second;
};
for (const auto& kv : keyval) {
if (attempt_scalar<int> (kv, json)) continue;
if (attempt_scalar<default_type> (kv, json)) continue;
if (attempt_scalar<bool> (kv, json)) continue;
if (attempt_matrix (kv, json)) continue;
if (json.find (kv.first) == json.end()) {
write_string (kv, json);
} else {
nlohmann::json temp;
write_string (kv, temp);
if (json[kv.first] != temp[kv.first])
json[kv.first] = "variable";
}
}
}
void write (const Header& header, nlohmann::json& json, const std::string& image_path)
{
Header H_adj (header);
H_adj.name() = image_path;
if (!App::get_options("export_grad_fsl").empty() || !App::get_options("export_grad_mrtrix").empty())
DWI::clear_DW_scheme(H_adj);
if (!Path::has_suffix (image_path, { ".nii", ".nii.gz", ".img" })) {
write (H_adj.keyval(), json);
return;
}
Metadata::PhaseEncoding::transform_for_nifti_write(H_adj.keyval(), H_adj);
Metadata::SliceEncoding::transform_for_nifti_write(H_adj.keyval(), H_adj);
write (H_adj.keyval(), json);
}
}
}
}
|