SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
concentrationset.cpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
4#include "concentrationset.h"
5#include "numericparsing.h"
6#include <limits>
7#include "math.h"
8#include "Utilities.h"
9#include <gsl/gsl_cdf.h>
10#include <gsl/gsl_randist.h>
11
12// ========== Construction and Assignment ==========
13
20
27
34
36{
37 if (this == &other) {
38 return *this;
39 }
40
41 vector<double>::operator=(other);
44
45 return *this;
46}
47
48// ========== Data Management ==========
49
51{
52 push_back(value);
53}
54
56{
57 insert(end(), other.begin(), other.end());
58}
59
61{
62 if (other != nullptr) {
63 insert(end(), other->begin(), other->end());
64 }
65}
66
67// ========== Basic Statistics ==========
68
70{
71 if (empty()) {
72 return 0.0;
73 }
74
75 double sum = 0.0;
76 for (const double value : *this) {
77 sum += value;
78 }
79
80 return sum / static_cast<double>(size());
81}
82
83double ConcentrationSet::CalculateStdDev(double mean_value) const
84{
85 if (size() <= 1) {
86 return 0.0;
87 }
88
89 if (mean_value == -999) {
90 mean_value = CalculateMean();
91 }
92
93 double sum = 0.0;
94 for (const double value : *this) {
95 sum += pow(value - mean_value, 2);
96 }
97
98 return sqrt(sum / static_cast<double>(size() - 1));
99}
100
101double ConcentrationSet::CalculateStdDevLog(double mean_value) const
102{
103 if (size() <= 1) {
104 return 0.0;
105 }
106
107 if (mean_value == -999) {
108 mean_value = CalculateMeanLog();
109 }
110
111 double sum = 0.0;
112 for (const double value : *this) {
113 sum += pow(log(value) - mean_value, 2);
114 }
115
116 return sqrt(sum / static_cast<double>(size() - 1));
117}
118
119double ConcentrationSet::CalculateSSE(double mean_value) const
120{
121 if (mean_value == -999) {
122 mean_value = CalculateMean();
123 }
124
125 double sum = 0.0;
126 for (const double value : *this) {
127 sum += pow(value - mean_value, 2);
128 }
129
130 return sum;
131}
132
133double ConcentrationSet::CalculateSSELog(double mean_value) const
134{
135 if (mean_value == -999) {
136 mean_value = CalculateMeanLog();
137 }
138
139 double sum = 0.0;
140 for (const double value : *this) {
141 sum += pow(log(value) - mean_value, 2);
142 }
143
144 return sum;
145}
146
148{
149 if (empty()) {
150 return 0.0;
151 }
152
153 double sum = 0.0;
154 for (const double value : *this) {
155 sum += log(value);
156 }
157
158 return sum / static_cast<double>(size());
159}
160
162{
163 double sum = 0.0;
164 for (const double value : *this) {
165 sum += pow(value, power);
166 }
167
168 return sum;
169}
170
172{
173 double sum = 0.0;
174 for (const double value : *this) {
175 sum += pow(log(value), power);
176 }
177
178 return sum;
179}
180
182{
183 ConcentrationSet transformed(size());
184
185 for (size_t i = 0; i < size(); i++) {
186 transformed[i] = log(at(i));
187 }
188
189 return transformed;
190}
191
193{
194 return aquiutils::Min(*this);
195}
196
198{
199 return aquiutils::Max(*this);
200}
201
202// ========== Distribution Fitting ==========
203
205 distribution_type dist_type)
206{
207 vector<double> parameters;
208
209 // Use fitted distribution type if none specified
210 if (dist_type == distribution_type::none) {
211 dist_type = fitted_distribution_.distribution;
212 }
213 else {
214 fitted_distribution_.SetType(dist_type);
215 estimated_distribution_.SetType(dist_type);
216 }
217
218 // Store data statistics
219 fitted_distribution_.SetDataMean(CalculateMean());
221
222 // Calculate distribution parameters based on type
223 if (dist_type == distribution_type::normal) {
224 parameters.push_back(CalculateMean());
225 parameters.push_back(CalculateStdDev());
226 }
227 else if (dist_type == distribution_type::lognormal) {
228 parameters.push_back(CalculateMeanLog());
229 parameters.push_back(CalculateStdDevLog());
230 }
231
232 // CRITICAL: Set the parameters on fitted distribution
233 fitted_distribution_.parameters = parameters;
234
235 return parameters;
236}
237
239 const vector<double>& params,
240 distribution_type dist_type) const
241{
242 double log_likelihood = 0.0;
243
244 // Use fitted distribution if no parameters provided
245 if (params.empty() && dist_type == distribution_type::none) {
246 for (const double value : *this) {
247 log_likelihood += log(fitted_distribution_.Eval(value));
248 }
249 }
250 // Use provided parameters and distribution type
251 else if (!params.empty() && dist_type != distribution_type::none) {
252 Distribution dist;
253 dist.parameters = params;
254 dist.distribution = dist_type;
255
256 for (const double value : *this) {
257 log_likelihood += log(dist.Eval(value));
258 }
259 }
260
261 return log_likelihood;
262}
263
265{
266 // Lognormal requires all positive values
267 if (GetMinimum() <= 0) {
269 }
270
271 // For positive data, always use lognormal (based on user's original intent)
273}
274
275// ========== Goodness-of-Fit Testing ==========
276
278{
279 return size() >= 2 && GetMinimum() < GetMaximum();
280}
281
283{
284 vector<double> sorted_data = QSort(*this);
285 CMBTimeSeries cdf;
286
287 double probability_increment = 1.0 / static_cast<double>(sorted_data.size());
288
289 for (size_t i = 0; i < sorted_data.size(); i++) {
290 double cumulative_probability = (static_cast<double>(i) + 0.5) * probability_increment;
291 cdf.append(sorted_data[i], cumulative_probability);
292 }
293
294 return cdf;
295}
296
298{
299 CMBTimeSeriesSet comparison;
300
301 // Add empirical CDF
302 comparison.append(CreateDataCDF(), "Observed");
303
304 // A zero-width range would never end the loop below
305 if (!CanFitDistribution())
306 return comparison;
307
308 // Generate fitted CDF
309 CMBTimeSeries fitted_cdf;
310 double x_min = comparison[0].mint();
311 double x_max = comparison[0].maxt();
312 double step_size = (x_max - x_min) / 50.0;
313
314 for (double x = x_min; x <= x_max; x += step_size) {
315 double cumulative_prob = 0.0;
316
317 if (dist_type == distribution_type::normal) {
318 cumulative_prob = gsl_cdf_gaussian_P(x - CalculateMean(), CalculateStdDev());
319 }
320 else if (dist_type == distribution_type::lognormal) {
321 if (x > 0) {
322 cumulative_prob = gsl_cdf_lognormal_P(x, CalculateMeanLog(), CalculateStdDevLog());
323 }
324 }
325
326 fitted_cdf.append(x, cumulative_prob);
327 }
328
329 comparison.append(fitted_cdf, "Fitted");
330 comparison.append(comparison[0] - comparison[1], "Error");
331
332 return comparison;
333}
334
336{
337 CMBTimeSeriesSet result;
338
339 // Add empirical CDF
340 result.append(CreateDataCDF(), "Observed");
341
342 // A zero-width range would never end the loop below
343 if (!CanFitDistribution())
344 return result;
345
346 // Get distribution parameters
347 vector<double> parameters;
348 if (dist_type == distribution_type::normal) {
349 parameters.push_back(CalculateMean());
350 parameters.push_back(CalculateStdDev());
351 }
352 else if (dist_type == distribution_type::lognormal) {
353 parameters.push_back(CalculateMeanLog());
354 parameters.push_back(CalculateStdDevLog());
355 }
356
357 // Generate fitted PDF
358 CMBTimeSeries fitted_pdf;
359 double x_min = result[0].mint();
360 double x_max = result[0].maxt();
361 double step_size = (x_max - x_min) / 50.0;
362
363 for (double x = x_min; x <= x_max; x += step_size) {
364 fitted_pdf.append(x, Distribution::Eval(x, parameters, dist_type));
365 }
366
367 // Draw the observed values at half the height of the fitted PDF.
368 // (Assigning the number to the series itself, as this used to do,
369 // converted it through TimeSeries(size_t) and replaced the series with
370 // an unnamed empty one, so the later lookup of "Observed" threw.)
371 const double observed_height = fitted_pdf.maxC() / 2.0;
372 for (auto& point : result["Observed"])
373 point.c = observed_height;
374 result.append(fitted_pdf, "Fitted");
375
376 return result;
377}
378
380 distribution_type dist_type) const
381{
382 CMBTimeSeriesSet observed_fitted = CreateCDFComparison(dist_type);
383
384 // No fitted CDF for fewer than two values or constant data
385 if (!observed_fitted.Contains("Error"))
386 return std::numeric_limits<double>::quiet_NaN();
387
388 // K-S statistic is maximum absolute difference between CDFs
389 double max_positive_diff = fabs(observed_fitted[2].maxC());
390 double max_negative_diff = fabs(observed_fitted[2].minC());
391
392 return std::max(max_positive_diff, max_negative_diff);
393}
394
395// ========== Transformations ==========
396
397double ConcentrationSet::BoxCoxTransformValue(double x, double lambda)
398{
399 // lambda == 0 is the log limit. Near 0, (x^lambda - 1) cancels and loses
400 // digits (the old code switched to log x below 1e-5, an approximation off
401 // by about lambda (log x)^2 / 2), so expm1 is used there. Elsewhere the
402 // formula is unchanged, which keeps optimal lambdas from moving by
403 // round-off: the Kolmogorov-Smirnov grid search is sensitive to it.
404 if (lambda == 0.0)
405 return std::log(x);
406 if (std::fabs(lambda) < 0.01)
407 return std::expm1(lambda * std::log(x)) / lambda;
408 return (std::pow(x, lambda) - 1.0) / lambda;
409}
410
412{
413 return !empty() && GetMinimum() > 0;
414}
415
417{
418 if (!CanBoxCoxTransform())
419 return std::numeric_limits<double>::quiet_NaN();
420
421 ConcentrationSet transformed = ApplyBoxCoxTransform(lambda, true);
422
423 double transformed_mean = transformed.CalculateMean();
424 double std_dev = CalculateStdDev();
425
426 // The variance term used to be accumulated with a negative sign, so its
427 // log was always NaN. (This function has no callers.)
428 double variance_term = 0.0;
429 double jacobian_term = 0.0;
430
431 for (size_t i = 0; i < size(); i++) {
432 variance_term += 1.0 / static_cast<double>(size()) *
433 pow(transformed[i] - transformed_mean, 2);
434 jacobian_term += (lambda - 1.0) * log(at(i) / std_dev);
435 }
436
437 return -static_cast<double>(size()) / 2.0 * log(variance_term) + jacobian_term;
438}
439
441 double lambda,
442 bool normalize) const
443{
444 // Scale data by standard deviation if normalizing
445 ConcentrationSet scaled(size());
446 double std_dev = normalize ? CalculateStdDev() : 1.0;
447
448 for (size_t i = 0; i < size(); i++) {
449 scaled[i] = at(i) / std_dev;
450 }
451
452 // Box-Cox is undefined for zero or negative values (log(0), 0^lambda for
453 // lambda < 0): leave the data untransformed. This used to test only for
454 // negative values, so a zero produced -inf or inf.
455 if (!CanBoxCoxTransform()) {
456 return scaled;
457 }
458
459 ConcentrationSet transformed(size());
460
461 for (size_t i = 0; i < size(); i++) {
462 transformed[i] = BoxCoxTransformValue(scaled[i], lambda);
463 }
464
465 return transformed;
466}
467
469 double min_lambda,
470 double max_lambda,
471 int n_intervals) const
472{
473 // Cannot transform zero or negative values or constant data
474 if (!CanBoxCoxTransform() || GetMinimum() == GetMaximum()) {
475 return 1.0;
476 }
477
478 // Imported data is always finite (numericparsing.h); this guards
479 // values produced by a correction
480 if (!AllFinite(*this)) {
481 std::cerr << "Warning: non-finite value in concentration data" << std::endl;
482 return 1.0;
483 }
484
485 // Base case: range is sufficiently small
486 if (fabs(min_lambda - max_lambda) < 1e-6) {
487 return (min_lambda + max_lambda) / 2.0;
488 }
489
490 // Evaluate K-S statistic at multiple lambda values
491 vector<double> ks_statistics;
492 double lambda_step = (max_lambda - min_lambda) / static_cast<double>(n_intervals);
493
494 for (double lambda = min_lambda; lambda <= max_lambda; lambda += lambda_step) {
495 ConcentrationSet transformed = ApplyBoxCoxTransform(lambda, true);
496 double ks_stat = transformed.CalculateKolmogorovSmirnovStatistic(
498 );
499 ks_statistics.push_back(ks_stat);
500 }
501
502 // Find index of minimum K-S statistic
503 int min_index = aquiutils::MinElement(ks_statistics);
504
505 // Recursively refine search around minimum
506 int lower_index = std::max(min_index - 1, 0);
507 int upper_index = std::min(min_index + 1, static_cast<int>(ks_statistics.size() - 1));
508
509 double refined_min = min_lambda + lower_index * lambda_step;
510 double refined_max = min_lambda + upper_index * lambda_step;
511
512 return FindOptimalBoxCoxParameter(refined_min, refined_max, n_intervals);
513}
514
515// ========== Utility Functions ==========
516
517vector<unsigned int> ConcentrationSet::CalculateRanks() const
518{
519 return aquiutils::Rank(*this);
520}
521
Collection of time series with labels and observed values.
Time series data container with Interface support.
double CalculateSSE(double mean_value=-999) const
Calculate sum of squared errors from mean.
ConcentrationSet CreateLogTransformed() const
Create log-transformed copy.
double CalculateMean() const
Calculate arithmetic mean.
double CalculateLogLikelihood(const vector< double > &params=vector< double >(), distribution_type dist_type=distribution_type::none) const
Calculate log-likelihood of data given distribution parameters.
CMBTimeSeriesSet CreateCDFComparison(distribution_type dist_type) const
Create comparison of empirical vs fitted CDF.
double CalculateStdDevLog(double mean_value=-999) const
Calculate standard deviation of log-transformed values.
vector< double > EstimateDistributionParameters(distribution_type dist_type=distribution_type::none)
Estimate distribution parameters from data.
Distribution estimated_distribution_
Distribution being optimized (e.g., in MCMC).
CMBTimeSeries CreateDataCDF() const
Create empirical CDF from data.
double CalculateMeanLog() const
Calculate mean of log-transformed values.
double CalculateBoxCoxLogLikelihood(double lambda) const
Box-Cox profile log-likelihood for given lambda.
double CalculateNormLog(double power=2.0) const
Calculate sum of log-transformed values raised to a power.
double CalculateKolmogorovSmirnovStatistic(distribution_type dist_type) const
Calculate Kolmogorov-Smirnov statistic.
bool CanBoxCoxTransform() const
Whether the Box-Cox transformation applies: all values positive.
vector< unsigned int > CalculateRanks() const
Calculate ranks of values (1 = smallest).
double GetMaximum() const
Get maximum value.
static double BoxCoxTransformValue(double x, double lambda)
Box-Cox transform of a single positive value.
distribution_type SelectBestDistribution()
Select best-fitting distribution (normal vs lognormal).
bool CanFitDistribution() const
Whether a distribution can be fitted to the data.
void AppendSet(const ConcentrationSet &other)
Append all values from another set.
double GetMinimum() const
Get minimum value.
double FindOptimalBoxCoxParameter(double min_lambda, double max_lambda, int n_intervals) const
Find optimal Box-Cox lambda parameter.
ConcentrationSet ApplyBoxCoxTransform(double lambda, bool normalize) const
Apply Box-Cox transformation.
double CalculateNorm(double power=2.0) const
Calculate sum of values raised to a power.
void AppendValue(double value)
Append a single concentration value.
CMBTimeSeriesSet CreateFittedDistribution(distribution_type dist_type) const
Create fitted distribution visualization.
ConcentrationSet & operator=(const ConcentrationSet &other)
double CalculateSSELog(double mean_value=-999) const
Calculate sum of squared errors from log mean.
double CalculateStdDev(double mean_value=-999) const
Calculate standard deviation.
Distribution fitted_distribution_
Distribution fitted to observed data.
Represents a parametric probability distribution for uncertainty quantification.
double Eval(const double &x) const
Evaluate probability density function at a given value.
vector< double > parameters
Distribution parameters vector.
distribution_type distribution
The type of probability distribution.
distribution_type
Enumeration of probability distribution types supported in SedSat3.
@ none
No distribution assigned (uninitialized state).
@ lognormal
Lognormal distribution: ln(x) ~ N(μ, σ²), for strictly positive variables.
@ normal
Normal (Gaussian) distribution: p(x) = N(μ, σ²).
The one place where data values entering SedSAT3 are checked.
bool AllFinite(const std::vector< double > &values)
Whether every value is finite. Data imported through the functions above always is.