1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
|
/* 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 <limits>
#include "command.h"
#include "image.h"
#include "memory.h"
#include "progressbar.h"
#include "algo/threaded_loop.h"
#include "dwi/gradient.h"
#include "math/math.h"
#include "math/median.h"
#include "metadata/phase_encoding.h"
#include <limits>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"median",
"sum",
"product",
"rms",
"norm",
"var",
"std",
"min",
"max",
"absmax", // Maximum of absolute values
"magmax", // Value for which the magnitude is the maximum (i.e. preserves signed-ness)
NULL
};
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";
SYNOPSIS = "Compute summary statistic on image intensities either across images, "
"or along a specified axis of a single image";
DESCRIPTION
+ "Supported operations are:"
+ "mean, median, sum, product, rms (root-mean-square value), norm (vector 2-norm), var (unbiased variance), "
"std (unbiased standard deviation), min, max, absmax (maximum absolute value), "
"magmax (value with maximum absolute value, preserving its sign)."
+ "This command is used to traverse either along an image axis, or across a "
"set of input images, calculating some statistic from the values along each "
"traversal. If you are seeking to instead perform mathematical calculations "
"that are done independently for each voxel, pleaase see the 'mrcalc' command.";
EXAMPLES
+ Example ("Calculate a 3D volume representing the mean intensity across a 4D image series",
"mrmath 4D.mif mean 3D_mean.mif -axis 3",
"This is a common operation for calculating e.g. the mean value within a "
"specific DWI b-value. Note that axis indices start from 0; thus, axes 0, 1 & 2 "
"are the three spatial axes, and axis 3 operates across volumes.")
+ Example ("Generate a Maximum Intensity Projection (MIP) along the inferior-superior direction",
"mrmath input.mif max MIP.mif -axis 2",
"Since a MIP is literally the maximal value along a specific projection direction, "
"axis-aligned MIPs can be generated easily using mrmath with the \'max\' operation.");
ARGUMENTS
+ Argument ("input", "the input image(s).").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer (0)
+ Option ("keep_unary_axes", "Keep unary axes in input images prior to calculating the stats. "
"The default is to wipe axes with single elements.")
+ DataType::options();
}
using value_type = float;
class Mean { NOMEMALIGN
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Median { NOMEMALIGN
public:
Median () { }
void operator() (value_type val) {
if (!std::isnan (val))
values.push_back(val);
}
value_type result () {
return Math::median(values);
}
vector<value_type> values;
};
class Sum { NOMEMALIGN
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product { NOMEMALIGN
public:
Product () : product (NAN) { }
void operator() (value_type val) {
if (std::isfinite (val))
product = std::isfinite (product) ? product * val : val;
}
value_type result () const {
return product;
}
double product;
};
class RMS { NOMEMALIGN
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return std::sqrt(sum / count);
}
double sum;
size_t count;
};
class NORM2 { NOMEMALIGN
public:
NORM2() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return std::sqrt(sum);
}
double sum;
size_t count;
};
// Welford's algorithm to avoid catastrophic cancellation
class Var { NOMEMALIGN
public:
Var () : delta (0.0), delta2 (0.0), mean (0.0), m2 (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
++count;
delta = val - mean;
mean += delta / count;
delta2 = val - mean;
m2 += delta * delta2;
}
}
value_type result () const {
if (count < 2)
return NAN;
return m2 / (static_cast<double> (count) - 1.0);
}
double delta, delta2, mean, m2;
size_t count;
};
class Std : public Var { NOMEMALIGN
public:
Std() : Var() { }
value_type result () const { return std::sqrt (Var::result()); }
};
class Min { NOMEMALIGN
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max { NOMEMALIGN
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax { NOMEMALIGN
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && abs(val) > max)
max = abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax { NOMEMALIGN
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && (!std::isfinite (max) || abs(val) > abs (max)))
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel { NOMEMALIGN
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputImageType, class OutputImageType>
void operator() (InputImageType& in, OutputImageType& out) {
Operation op;
for (auto l = Loop (axis) (in); l; ++l)
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase { NOMEMALIGN
public:
virtual ~ImageKernelBase () { }
virtual void process (Header& image_in) = 0;
virtual void write_back (Image<value_type>& out) = 0;
};
template <class Operation>
class ImageKernel : public ImageKernelBase { NOMEMALIGN
protected:
class InitFunctor { NOMEMALIGN
public:
template <class ImageType>
void operator() (ImageType& out) const { out.value() = Operation(); }
};
class ProcessFunctor { NOMEMALIGN
public:
template <class ImageType1, class ImageType2>
void operator() (ImageType1& out, ImageType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor { NOMEMALIGN
public:
template <class ImageType1, class ImageType2>
void operator() (ImageType1& out, ImageType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Header& header) :
image (Header::scratch (header).get_image<Operation>()) {
ThreadedLoop (image).run (InitFunctor(), image);
}
void write_back (Image<value_type>& out)
{
ThreadedLoop (image).run (ResultFunctor(), out, image);
}
void process (Header& header_in)
{
auto in = header_in.get_image<value_type>();
ThreadedLoop (image).run (ProcessFunctor(), image, in);
}
protected:
Image<Operation> image;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
auto opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
auto image_in = Header::open (argument[0]).get_image<value_type>().with_direct_io (axis);
if (axis >= image_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(image_in.ndim()) + " axes");
Header header_out (image_in);
if (axis == 3) {
try {
const auto DW_scheme = DWI::parse_DW_scheme (header_out);
DWI::stash_DW_scheme (header_out, DW_scheme);
} catch (...) { }
DWI::clear_DW_scheme (header_out);
Metadata::PhaseEncoding::clear_scheme (header_out.keyval());
}
header_out.datatype() = DataType::from_command_line (DataType::Float32);
header_out.size(axis) = 1;
squeeze_dim (header_out);
auto image_out = Header::create (output_path, header_out).get_image<float>();
auto loop = ThreadedLoop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", image_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), image_in, image_out); return;
case 1: loop.run (AxisKernel<Median> (axis), image_in, image_out); return;
case 2: loop.run (AxisKernel<Sum> (axis), image_in, image_out); return;
case 3: loop.run (AxisKernel<Product>(axis), image_in, image_out); return;
case 4: loop.run (AxisKernel<RMS> (axis), image_in, image_out); return;
case 5: loop.run (AxisKernel<NORM2> (axis), image_in, image_out); return;
case 6: loop.run (AxisKernel<Var> (axis), image_in, image_out); return;
case 7: loop.run (AxisKernel<Std> (axis), image_in, image_out); return;
case 8: loop.run (AxisKernel<Min> (axis), image_in, image_out); return;
case 9: loop.run (AxisKernel<Max> (axis), image_in, image_out); return;
case 10: loop.run (AxisKernel<AbsMax> (axis), image_in, image_out); return;
case 11: loop.run (AxisKernel<MagMax> (axis), image_in, image_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
vector<Header> headers_in (num_inputs);
// Header of first input image is the template to which all other input images are compared
headers_in[0] = Header::open (argument[0]);
Header header (headers_in[0]);
header.datatype() = DataType::from_command_line (DataType::Float32);
// Wipe any excess unary-dimensional axes
if ( ! get_options ("keep_unary_axes").size() ) {
while (header.size (header.ndim() - 1) == 1)
header.ndim() = header.ndim() - 1;
}
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
// headers_in.push_back (std::unique_ptr<Header> (new Header (Header::open (path))));
headers_in[i] = Header::open (path);
const Header& temp (headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first input image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.size(axis) != header.size(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.size(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
header.merge_keyval (temp.keyval());
}
// Instantiate a kernel depending on the operation requested
std::unique_ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel.reset (new ImageKernel<Mean> (header)); break;
case 1: kernel.reset (new ImageKernel<Median> (header)); break;
case 2: kernel.reset (new ImageKernel<Sum> (header)); break;
case 3: kernel.reset (new ImageKernel<Product> (header)); break;
case 4: kernel.reset (new ImageKernel<RMS> (header)); break;
case 5: kernel.reset (new ImageKernel<NORM2> (header)); break;
case 6: kernel.reset (new ImageKernel<Var> (header)); break;
case 7: kernel.reset (new ImageKernel<Std> (header)); break;
case 8: kernel.reset (new ImageKernel<Min> (header)); break;
case 9: kernel.reset (new ImageKernel<Max> (header)); break;
case 10: kernel.reset (new ImageKernel<AbsMax> (header)); break;
case 11: kernel.reset (new ImageKernel<MagMax> (header)); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
assert (headers_in[i].valid());
assert (headers_in[i].is_file_backed());
kernel->process (headers_in[i]);
++progress;
}
}
auto out = Header::create (output_path, header).get_image<value_type>();
kernel->write_back (out);
}
}
|