Statistics.cpp 15.3 KB
 Gigg, Martyn Anthony committed Jul 20, 2012 1 2 3 ``````// Includes #include "MantidKernel/Statistics.h" `````` Hahn, Steven committed Feb 06, 2016 4 ``````#include `````` Hahn, Steven committed Feb 06, 2016 5 ``````#include `````` Hahn, Steven committed Feb 06, 2016 6 7 8 9 ``````#include #include #include `````` David Fairbrother committed Jun 09, 2017 10 11 12 13 14 15 ``````#include #include #include #include #include `````` Whitfield, Ross committed Dec 16, 2014 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 ``````namespace Mantid { namespace Kernel { using std::string; using std::vector; /** * Generate a Statistics object where all of the values are NaN. This is a good * initial default. */ Statistics getNanStatistics() { double nan = std::numeric_limits::quiet_NaN(); Statistics stats; stats.minimum = nan; stats.maximum = nan; stats.mean = nan; stats.median = nan; stats.standard_deviation = nan; return stats; } /** * There are enough special cases in determining the median where it useful to * put it in a single function. */ template double getMedian(const vector &data, const size_t num_data, const bool sorted) { if (num_data == 1) return static_cast(*(data.begin())); `````` Hahn, Steven committed Feb 06, 2016 49 `````` bool is_even = ((num_data & 1) == 0); `````` Whitfield, Ross committed Dec 16, 2014 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 `````` if (is_even) { double left = 0.0; double right = 0.0; if (sorted) { // Just get the centre two elements. left = static_cast(*(data.begin() + num_data / 2 - 1)); right = static_cast(*(data.begin() + num_data / 2)); } else { // If the data is not sorted, make a copy we can mess with vector temp(data.begin(), data.end()); // Get what the centre two elements should be... std::nth_element(temp.begin(), temp.begin() + num_data / 2 - 1, temp.end()); left = static_cast(*(temp.begin() + num_data / 2 - 1)); std::nth_element(temp.begin(), temp.begin() + num_data / 2, temp.end()); right = static_cast(*(temp.begin() + num_data / 2)); `````` Campbell, Stuart committed Mar 30, 2011 67 `````` } `````` Whitfield, Ross committed Dec 16, 2014 68 69 70 `````` // return the average return (left + right) / 2.; } else `````` Lynch, Vickie committed Feb 22, 2018 71 `````` // Odd number `````` Whitfield, Ross committed Dec 16, 2014 72 73 74 75 76 77 78 79 80 81 82 `````` { if (sorted) { // If sorted and odd, just return the centre value return static_cast(*(data.begin() + num_data / 2)); } else { // If the data is not sorted, make a copy we can mess with vector temp(data.begin(), data.end()); // Make sure the centre value is in the correct position std::nth_element(temp.begin(), temp.begin() + num_data / 2, temp.end()); // Now return the centre value return static_cast(*(temp.begin() + num_data / 2)); `````` Lynch, Vickie committed May 14, 2012 83 `````` } `````` Whitfield, Ross committed Dec 16, 2014 84 `````` } `````` Hahn, Steven committed Feb 06, 2016 85 ``````} `````` Hahn, Steven committed Feb 06, 2016 86 `````` `````` Whitfield, Ross committed Dec 16, 2014 87 88 89 90 91 ``````/** * There are enough special cases in determining the Z score where it useful to * put it in a single function. */ template `````` Martyn Gigg committed Sep 02, 2015 92 ``````std::vector getZscore(const vector &data) { `````` Whitfield, Ross committed Dec 16, 2014 93 94 95 96 97 `````` if (data.size() < 3) { std::vector Zscore(data.size(), 0.); return Zscore; } std::vector Zscore; `````` Martyn Gigg committed Sep 02, 2015 98 `````` Statistics stats = getStatistics(data); `````` Whitfield, Ross committed Dec 16, 2014 99 100 101 102 `````` if (stats.standard_deviation == 0.) { std::vector Zscore(data.size(), 0.); return Zscore; } `````` Hahn, Steven committed Jan 06, 2016 103 `````` for (auto it = data.cbegin(); it != data.cend(); ++it) { `````` Whitfield, Ross committed Dec 16, 2014 104 `````` double tmp = static_cast(*it); `````` Lynch, Vickie committed Feb 20, 2018 105 `````` Zscore.push_back(fabs((stats.mean - tmp) / stats.standard_deviation)); `````` Whitfield, Ross committed Dec 16, 2014 106 107 108 `````` } return Zscore; } `````` Lynch, Vickie committed Feb 21, 2018 109 110 111 112 113 ``````/** * There are enough special cases in determining the Z score where it useful to * put it in a single function. */ template `````` Lynch, Vickie committed Feb 22, 2018 114 115 ``````std::vector getWeightedZscore(const vector &data, const vector &weights) { `````` Lynch, Vickie committed Feb 21, 2018 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 `````` if (data.size() < 3) { std::vector Zscore(data.size(), 0.); return Zscore; } std::vector Zscore; Statistics stats = getStatistics(data); if (stats.standard_deviation == 0.) { std::vector Zscore(data.size(), 0.); return Zscore; } double sumWeights = 0.0; double sumWeightedData = 0.0; double weightedVariance = 0.0; for (size_t it = 0; it != data.size(); ++it) { sumWeights += static_cast(weights[it]); sumWeightedData += static_cast(weights[it] * data[it]); } `````` Lynch, Vickie committed Feb 22, 2018 133 `````` double weightedMean = sumWeightedData / sumWeights; `````` Lynch, Vickie committed Feb 21, 2018 134 `````` for (size_t it = 0; it != data.size(); ++it) { `````` Lynch, Vickie committed Mar 05, 2018 135 136 137 `````` weightedVariance += std::pow(static_cast(data[it]) - weightedMean, 2) * std::pow(static_cast(weights[it]) / sumWeights, 2); `````` Lynch, Vickie committed Feb 21, 2018 138 139 `````` } for (auto it = data.cbegin(); it != data.cend(); ++it) { `````` Lynch, Vickie committed Mar 05, 2018 140 141 `````` Zscore.push_back(fabs((static_cast(*it) - weightedMean) / std::sqrt(weightedVariance))); `````` Lynch, Vickie committed Feb 21, 2018 142 143 144 `````` } return Zscore; } `````` Whitfield, Ross committed Dec 16, 2014 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 ``````/** * There are enough special cases in determining the modified Z score where it * useful to * put it in a single function. */ template std::vector getModifiedZscore(const vector &data, const bool sorted) { if (data.size() < 3) { std::vector Zscore(data.size(), 0.); return Zscore; } std::vector MADvec; double tmp; size_t num_data = data.size(); // cache since it is frequently used double median = getMedian(data, num_data, sorted); `````` Hahn, Steven committed Jan 06, 2016 161 `````` for (auto it = data.cbegin(); it != data.cend(); ++it) { `````` Whitfield, Ross committed Dec 16, 2014 162 163 164 165 166 167 168 169 170 171 `````` tmp = static_cast(*it); MADvec.push_back(fabs(tmp - median)); } double MAD = getMedian(MADvec, num_data, sorted); if (MAD == 0.) { std::vector Zscore(data.size(), 0.); return Zscore; } MADvec.clear(); std::vector Zscore; `````` Hahn, Steven committed Jan 06, 2016 172 `````` for (auto it = data.begin(); it != data.end(); ++it) { `````` Whitfield, Ross committed Dec 16, 2014 173 174 175 176 177 178 179 180 181 `````` tmp = static_cast(*it); Zscore.push_back(0.6745 * fabs((tmp - median) / MAD)); } return Zscore; } /** * Determine the statistics for a vector of data. If it is sorted then let the * function know so it won't make a copy of the data for determining the median. `````` Martyn Gigg committed Sep 02, 2015 182 183 `````` * @param data Data points whose statistics are to be evaluated * @param flags A set of flags to control the computation of the stats `````` Whitfield, Ross committed Dec 16, 2014 184 185 `````` */ template `````` Martyn Gigg committed Sep 02, 2015 186 ``````Statistics getStatistics(const vector &data, const unsigned int flags) { `````` Hahn, Steven committed Feb 06, 2016 187 `````` Statistics statistics = getNanStatistics(); `````` Whitfield, Ross committed Dec 16, 2014 188 `````` size_t num_data = data.size(); // cache since it is frequently used `````` Martyn Gigg committed Sep 02, 2015 189 `````` if (num_data == 0) { // don't do anything `````` Hahn, Steven committed Feb 06, 2016 190 `````` return statistics; `````` Whitfield, Ross committed Dec 16, 2014 191 `````` } `````` Martyn Gigg committed Sep 02, 2015 192 193 194 `````` // calculate the mean if this or the stddev is requested const bool stddev = ((flags & StatOptions::UncorrectedStdDev) || (flags & StatOptions::CorrectedStdDev)); `````` Hahn, Steven committed Feb 06, 2016 195 196 `````` if (stddev) { using namespace boost::accumulators; `````` Lynch, Vickie committed Feb 22, 2018 197 `````` accumulator_set> acc; `````` Hahn, Steven committed Feb 06, 2016 198 `````` for (auto &value : data) { `````` Hahn, Steven committed Feb 06, 2016 199 `````` acc(static_cast(value)); `````` Martyn Gigg committed Sep 02, 2015 200 `````` } `````` Hahn, Steven committed Feb 06, 2016 201 202 203 `````` statistics.minimum = min(acc); statistics.maximum = max(acc); statistics.mean = mean(acc); `````` Hahn, Steven committed Feb 06, 2016 204 205 206 207 208 209 `````` double var = variance(acc); if (flags & StatOptions::CorrectedStdDev) { double ndofs = static_cast(data.size()); var *= ndofs / (ndofs - 1.0); } `````` Hahn, Steven committed Feb 06, 2016 210 `````` statistics.standard_deviation = std::sqrt(var); `````` Hahn, Steven committed Feb 06, 2016 211 212 213 `````` } else if (flags & StatOptions::Mean) { using namespace boost::accumulators; `````` Lynch, Vickie committed Feb 22, 2018 214 `````` accumulator_set> acc; `````` Hahn, Steven committed Feb 06, 2016 215 `````` for (auto &value : data) { `````` Hahn, Steven committed Feb 06, 2016 216 `````` acc(static_cast(value)); `````` Hahn, Steven committed Feb 06, 2016 217 `````` } `````` Hahn, Steven committed Feb 06, 2016 218 `````` statistics.mean = mean(acc); `````` Martyn Gigg committed Sep 02, 2015 219 `````` } `````` Hahn, Steven committed Feb 06, 2016 220 `````` `````` Martyn Gigg committed Sep 02, 2015 221 222 `````` // calculate the median if requested if (flags & StatOptions::Median) { `````` Hahn, Steven committed Feb 06, 2016 223 224 `````` statistics.median = getMedian(data, num_data, flags & StatOptions::SortedData); `````` Whitfield, Ross committed Dec 16, 2014 225 `````` } `````` Hahn, Steven committed Feb 06, 2016 226 `````` `````` Hahn, Steven committed Feb 06, 2016 227 `````` return statistics; `````` Whitfield, Ross committed Dec 16, 2014 228 229 230 231 232 ``````} /// Getting statistics of a string array should just give a bunch of NaNs template <> DLLExport Statistics `````` Martyn Gigg committed Sep 02, 2015 233 234 ``````getStatistics(const vector &data, const unsigned int flags) { UNUSED_ARG(flags); `````` Whitfield, Ross committed Dec 16, 2014 235 236 237 238 239 240 241 `````` UNUSED_ARG(data); return getNanStatistics(); } /// Getting statistics of a boolean array should just give a bunch of NaNs template <> DLLExport Statistics `````` Martyn Gigg committed Sep 02, 2015 242 243 ``````getStatistics(const vector &data, const unsigned int flags) { UNUSED_ARG(flags); `````` Whitfield, Ross committed Dec 16, 2014 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 `````` UNUSED_ARG(data); return getNanStatistics(); } /** Return the Rwp of a diffraction pattern data * @param obsI :: array of observed intensity values * @param calI :: array of calculated intensity values; * @param obsE :: array of error of the observed data; * @return :: RFactor including Rp and Rwp * */ Rfactor getRFactor(const std::vector &obsI, const std::vector &calI, const std::vector &obsE) { // 1. Check if (obsI.size() != calI.size() || obsI.size() != obsE.size()) { std::stringstream errss; errss << "GetRFactor() Input Error! Observed Intensity (" << obsI.size() << "), Calculated Intensity (" << calI.size() << ") and Observed Error (" << obsE.size() << ") have different number of elements."; throw std::runtime_error(errss.str()); } `````` Hahn, Steven committed Mar 01, 2016 267 `````` if (obsI.empty()) { `````` Whitfield, Ross committed Dec 16, 2014 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 `````` throw std::runtime_error("getRFactor(): the input arrays are empty."); } double sumnom = 0; double sumdenom = 0; double sumrpnom = 0; double sumrpdenom = 0; size_t numpts = obsI.size(); for (size_t i = 0; i < numpts; ++i) { double cal_i = calI[i]; double obs_i = obsI[i]; double sigma = obsE[i]; double weight = 1.0 / (sigma * sigma); double diff = obs_i - cal_i; if (weight == weight && weight <= DBL_MAX) { // If weight is not NaN. sumrpnom += fabs(diff); sumrpdenom += fabs(obs_i); double tempnom = weight * diff * diff; double tempden = weight * obs_i * obs_i; sumnom += tempnom; sumdenom += tempden; if (tempnom != tempnom || tempden != tempden) { std::cout << "***** Error! ****** Data indexed " << i << " is NaN. " << "i = " << i << ": cal = " << calI[i] << ", obs = " << obs_i << ", weight = " << weight << ". \n"; `````` Campbell, Stuart committed Mar 30, 2011 299 300 `````` } } `````` Whitfield, Ross committed Dec 16, 2014 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 `````` } Rfactor rfactor(0., 0.); rfactor.Rp = (sumrpnom / sumrpdenom); rfactor.Rwp = std::sqrt(sumnom / sumdenom); if (rfactor.Rwp != rfactor.Rwp) std::cout << "Rwp is NaN. Denominator = " << sumnom << "; Nominator = " << sumdenom << ". \n"; return rfactor; } /** * This will calculate the first n-moments (inclusive) about the origin. For *example * if maxMoment=2 then this will return 3 values: 0th (total weight), 1st *(mean), 2nd (deviation). * * @param x The independent values * @param y The dependent values * @param maxMoment The number of moments to calculate * @returns The first n-moments. */ template std::vector getMomentsAboutOrigin(const std::vector &x, const std::vector &y, const int maxMoment) { // densities have the same number of x and y bool isDensity(x.size() == y.size()); // if it isn't a density then check for histogram if ((!isDensity) && (x.size() != y.size() + 1)) { std::stringstream msg; msg << "length of x (" << x.size() << ") and y (" << y.size() << ")do not match"; throw std::out_of_range(msg.str()); } // initialize a result vector with all zeros std::vector result(maxMoment + 1, 0.); // cache the maximum index size_t numPoints = y.size(); if (isDensity) numPoints = x.size() - 1; // densities are calculated using Newton's method for numerical integration `````` Martyn Gigg committed Sep 02, 2015 349 350 `````` // as backwards as it sounds, the outer loop should be the points rather // than `````` Whitfield, Ross committed Dec 16, 2014 351 352 353 354 355 356 357 358 359 `````` // the moments for (size_t j = 0; j < numPoints; ++j) { // reduce item lookup - and central x for histogram const double xVal = .5 * static_cast(x[j] + x[j + 1]); // this variable will be (x^n)*y double temp = static_cast(y[j]); // correct for histogram if (isDensity) { const double xDelta = static_cast(x[j + 1] - x[j]); temp = .5 * (temp + static_cast(y[j + 1])) * xDelta; `````` Campbell, Stuart committed Mar 30, 2011 360 361 `````` } `````` Whitfield, Ross committed Dec 16, 2014 362 363 364 365 366 `````` // accumulate the moments result[0] += temp; for (size_t i = 1; i < result.size(); ++i) { temp *= xVal; result[i] += temp; `````` Gigg, Martyn Anthony committed Jun 20, 2012 367 `````` } `````` Whitfield, Ross committed Dec 16, 2014 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 `````` } return result; } /** * This will calculate the first n-moments (inclusive) about the mean (1st *moment). For example * if maxMoment=2 then this will return 3 values: 0th (total weight), 1st *(mean), 2nd (deviation). * * @param x The independent values * @param y The dependent values * @param maxMoment The number of moments to calculate * @returns The first n-moments. */ template std::vector getMomentsAboutMean(const std::vector &x, const std::vector &y, const int maxMoment) { // get the zeroth (integrated value) and first moment (mean) std::vector momentsAboutOrigin = getMomentsAboutOrigin(x, y, 1); const double mean = momentsAboutOrigin[1]; // initialize a result vector with all zeros std::vector result(maxMoment + 1, 0.); result[0] = momentsAboutOrigin[0]; // escape early if we need to if (maxMoment == 0) return result; // densities have the same number of x and y bool isDensity(x.size() == y.size()); // cache the maximum index size_t numPoints = y.size(); if (isDensity) numPoints = x.size() - 1; // densities are calculated using Newton's method for numerical integration `````` Martyn Gigg committed Sep 02, 2015 409 410 `````` // as backwards as it sounds, the outer loop should be the points rather // than `````` Whitfield, Ross committed Dec 16, 2014 411 412 413 414 415 416 417 418 419 420 421 422 423 424 `````` // the moments for (size_t j = 0; j < numPoints; ++j) { // central x in histogram with a change of variables - and just change for // density const double xVal = .5 * static_cast(x[j] + x[j + 1]) - mean; // change of variables // this variable will be (x^n)*y double temp; if (isDensity) { const double xDelta = static_cast(x[j + 1] - x[j]); temp = xVal * .5 * static_cast(y[j] + y[j + 1]) * xDelta; } else { temp = xVal * static_cast(y[j]); `````` Peterson, Peter committed Sep 09, 2013 425 426 `````` } `````` Whitfield, Ross committed Dec 16, 2014 427 428 429 430 431 `````` // accumulate the moment result[1] += temp; for (size_t i = 2; i < result.size(); ++i) { temp *= xVal; result[i] += temp; `````` Peterson, Peter committed Sep 09, 2013 432 `````` } `````` Whitfield, Ross committed Dec 16, 2014 433 434 435 436 437 438 439 440 441 `````` } return result; } // -------------------------- Macro to instantiation concrete types // -------------------------------- #define INSTANTIATE(TYPE) \ template MANTID_KERNEL_DLL Statistics \ `````` Martyn Gigg committed Sep 02, 2015 442 `````` getStatistics(const vector &, const unsigned int); \ `````` Whitfield, Ross committed Dec 16, 2014 443 `````` template MANTID_KERNEL_DLL std::vector getZscore( \ `````` Whitfield, Ross committed Oct 05, 2015 444 `````` const vector &); \ `````` Lynch, Vickie committed Feb 22, 2018 445 446 `````` template MANTID_KERNEL_DLL std::vector getWeightedZscore( \ const vector &, const vector &); \ `````` Whitfield, Ross committed Dec 16, 2014 447 448 449 450 451 452 453 454 455 456 457 `````` template MANTID_KERNEL_DLL std::vector getModifiedZscore( \ const vector &, const bool); \ template MANTID_KERNEL_DLL std::vector getMomentsAboutOrigin( \ const std::vector &x, const std::vector &y, \ const int maxMoment); \ template MANTID_KERNEL_DLL std::vector getMomentsAboutMean( \ const std::vector &x, const std::vector &y, \ const int maxMoment); // --------------------------- Concrete instantiations // --------------------------------------------- `````` Harry Jeffery committed Mar 19, 2015 458 459 460 461 462 463 464 465 ``````INSTANTIATE(float) INSTANTIATE(double) INSTANTIATE(int) INSTANTIATE(long) INSTANTIATE(long long) INSTANTIATE(unsigned int) INSTANTIATE(unsigned long) INSTANTIATE(unsigned long long) `````` Whitfield, Ross committed Dec 16, 2014 466 467 `````` } // namespace Kernel `````` 468 ``} // namespace Mantid``