13#include "NormalDist.h"
14#include "qjsondocument.h"
16#include <gsl/gsl_cdf.h>
51 options_[
"Outlier deviation threshold"] = 3.0;
91 map<string, Elemental_Profile_Set>::operator=(other);
121 const string& target,
123 map<string, element_information>* elementinfo)
129 vector<double> om_size;
138 for (
auto& [group_name, profile_set] : *
this)
141 bool apply_corrections = (group_name !=
target_group_) && omnsizecorrect;
148 for (
const auto& [sample_name, profile] : profile_set)
149 if (!sample_name.empty())
152 corrected[group_name] = targets;
155 corrected[group_name] = profile_set.CopyIncludedInAnalysis(
173 std::set<string> isotope_bases;
176 isotope_bases.insert(elem_info.base_element);
179 if ((elem_info.include_in_analysis &&
183 isotope_bases.count(element_name) > 0)
221 bool exclude_samples,
222 bool exclude_elements,
224 const string& target)
const
231 info.include_in_analysis = is_tracer && (!exclude_elements || info.include_in_analysis);
238 if (!exclude_elements) {
246 if (elem_info.include_in_analysis &&
259 bool exclude_samples,
260 bool exclude_elements,
262 const string& target)
const
268 if (!target.empty()) {
276 vector<double> om_size;
292 for (
const auto& [group_name, profile_set] : *
this)
297 corrected[group_name] = profile_set.CreateCorrectedSet(
308 corrected[group_name] = profile_set.CreateCorrectedSet(
338 for (
const auto& [group_name, profile_set] : *
this)
361 for (
const auto& [group_name, profile_set] : *
this)
365 extracted[group_name] = profile_set.ExtractElements(element_list);
420 std::cerr <<
"Sample set '" +
name +
"' already exists!" << std::endl;
427 return &operator[](
name);
433 if (count(
name) == 0) {
437 return &operator[](
name);
443 (count(group_name) > 0) ? &at(group_name) :
nullptr;
449 return vector<string>();
454 vector<string> group_names;
455 group_names.reserve(size());
457 for (
const auto& [group_name, profile_set] : *
this)
459 group_names.push_back(group_name);
468 return vector<string>();
473 if (first_group.empty()) {
474 return vector<string>();
479 vector<string> element_names;
480 element_names.reserve(first_sample.size());
482 for (
const auto& [element_name, concentration] : first_sample)
484 element_names.push_back(element_name);
487 return element_names;
491 const vector<vector<string>>& indicators)
const
495 extracted.
values.reserve(indicators.size());
498 for (
const auto& indicator : indicators)
500 const string& group_name = indicator[0];
501 const string& sample_name = indicator[1];
504 (count(group_name) > 0) ? &at(group_name) :
nullptr;
509 extracted.
values.push_back(concentrations);
518 const vector<vector<string>>& indicators)
const
522 for (
const auto& indicator : indicators)
524 const string& group_name = indicator[0];
525 const string& sample_name = indicator[1];
528 (count(group_name) > 0) ? &at(group_name) :
nullptr;
530 if (group && group->count(sample_name) > 0)
534 extracted.
AppendProfile(group_name +
"-" + sample_name, profile);
541 const string& element,
542 const string& group)
const
548 (count(group) > 0) ? &at(group) :
nullptr;
554 extracted.
values.reserve(profile_set->size());
557 for (
const auto& [sample_name, profile] : *profile_set)
559 extracted.
values.push_back(profile.GetValue(element));
572 for (
auto& [group_name, profile_set] : *
this)
575 profile_set.UpdateElementDistributions();
578 for (
const string& element : element_names)
581 profile_set.GetElementDistribution(element)
589 map<string, vector<double>> extracted;
592 for (
const string& group_name : group_names)
595 extracted[group_name] = group_data.
values;
606 for (
const string& element : element_names)
614 for (
auto& [group_name, profile_set] : *
this)
655 for (
const string& element : element_names)
657 if (ElementInfo ==
nullptr)
739bool FittedParametersAvailable(
const Distribution* fitted,
741 const string& element_name,
742 const string& group_name)
744 if (fitted !=
nullptr && fitted->
parameters.size() >= needed)
747 std::cerr <<
"InitializeParametersAndObservations: no fitted distribution for '"
748 << element_name <<
"' in group '" << group_name
749 <<
"'. Build the distributions with PopulateElementDistributions() "
750 "and AssignAllDistributions() before initializing." << std::endl;
757 const string& targetsamplename,
767 std::cerr <<
"Data has not been loaded!" << std::endl;
783 for (
auto& [group_name, profile_set] : *
this)
788 p.
SetName(group_name +
"_contribution");
801 for (
auto& [group_name, profile_set] : *
this)
817 if (elem_info.include_in_analysis)
835 for (
auto& [group_name, profile_set] : *
this)
840 *profile_set.GetEstimatedDistribution(element_name) =
841 *profile_set.GetFittedDistribution(element_name);
852 for (
auto& [group_name, profile_set] : *
this)
856 *profile_set.GetEstimatedDistribution(element_name) =
857 *profile_set.GetFittedDistribution(element_name);
872 for (
auto& [group_name, profile_set] : *
this)
877 p.
SetName(group_name +
"_" + element_name +
"_mu");
884 Distribution* estimated = profile_set.GetEstimatedDistribution(element_name);
885 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
887 if (estimated ==
nullptr ||
888 !FittedParametersAvailable(fitted, 1, element_name, group_name))
910 for (
auto& [group_name, profile_set] : *
this)
915 p.
SetName(group_name +
"_" + element_name +
"_mu");
918 Distribution* estimated = profile_set.GetEstimatedDistribution(element_name);
919 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
921 if (estimated ==
nullptr ||
922 !FittedParametersAvailable(fitted, 1, element_name, group_name))
944 for (
auto& [group_name, profile_set] : *
this)
949 p.
SetName(group_name +
"_" + element_name +
"_sigma");
953 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
955 if (!FittedParametersAvailable(fitted, 2, element_name, group_name))
958 double lower = std::max(fitted->
parameters[1] * 0.8, 0.001);
959 double upper = std::max(fitted->
parameters[1] / 0.8, 2.0);
973 for (
auto& [group_name, profile_set] : *
this)
978 p.
SetName(group_name +
"_" + element_name +
"_sigma");
982 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
984 if (!FittedParametersAvailable(fitted, 2, element_name, group_name))
987 double lower = std::max(fitted->
parameters[1] * 0.8, 0.001);
988 double upper = std::max(fitted->
parameters[1] / 0.8, 2.0);
1004 error_param.
SetName(
"Error STDev");
1015 obs.
SetName(targetsamplename +
"_" + element_name);
1023 error_param_isotope.
SetName(
"Error STDev for isotopes");
1025 error_param_isotope.
SetRange(0.01, 0.1);
1034 obs.
SetName(targetsamplename +
"_" + element_name);
1047 CVector contributions(size()-1);
1048 for (
unsigned long int i=0; i<size()-2; i++)
1052 contributions[size()-2] = 1 - contributions.sum();
1053 return contributions;
1067 double logLikelihood = 0;
1068 for (
unsigned int element_counter=0; element_counter<
element_order_.size(); element_counter++)
1075 for (map<string,Elemental_Profile>::iterator sample = this_source_group->begin(); sample!=this_source_group->end(); sample++)
1082 return logLikelihood;
1094 return observed_data;
1109 return observed_data;
1122 return observed_data;
1134 CVector predicted_concentrations =
PredictTarget(param_mode);
1138 if (predicted_concentrations.min() <= 0)
1145 const double num_elements = predicted_concentrations.num;
1148 CVector log_residuals = predicted_concentrations.Log() - observed_concentrations.Log();
1149 const double sum_squared_residuals = pow(log_residuals.norm2(), 2);
1150 const double variance_term = 2.0 * pow(
error_stdev_, 2);
1152 double log_likelihood = -normalization_term - (sum_squared_residuals / variance_term);
1154 return log_likelihood;
1170 const double num_isotopes = predicted_deltas.num;
1173 CVector residuals = predicted_deltas - observed_deltas;
1174 const double sum_squared_residuals = pow(residuals.norm2(), 2);
1177 double log_likelihood = -normalization_term - (sum_squared_residuals / variance_term);
1179 return log_likelihood;
1190 if (!predicted_concentrations.is_finite())
1201 CVector elemental_residuals = predicted_concentrations.Log() - observed_concentrations.Log();
1204 CVector isotopic_residuals = predicted_deltas - observed_deltas;
1207 CVector combined_residuals = elemental_residuals;
1208 combined_residuals.append(isotopic_residuals);
1218 return combined_residuals;
1224 CVector_arma predicted_concentrations =
PredictTarget().vec;
1233 CVector_arma elemental_residuals = predicted_concentrations.Log() - observed_concentrations.Log();
1236 CVector_arma isotopic_residuals = predicted_deltas - observed_deltas;
1239 CVector_arma combined_residuals = elemental_residuals;
1240 combined_residuals.append(isotopic_residuals);
1242 return combined_residuals;
1249 const size_t num_parameters = num_sources - 1;
1252 CMatrix_arma jacobian(num_parameters, num_residuals);
1259 for (
unsigned int i = 0; i < num_parameters; i++)
1262 const double epsilon = (0.5 - base_contributions[i]) * 1e-6;
1269 jacobian.setcol(i, (perturbed_residuals - base_residuals) / epsilon);
1281 const size_t num_parameters = num_sources - 1;
1284 CMatrix jacobian(num_parameters, num_residuals);
1291 for (
unsigned int i = 0; i < num_parameters; i++)
1294 const double epsilon = (0.5 - base_contributions[i]) * 1e-3;
1301 jacobian.setrow(i, (perturbed_residuals - base_residuals) / epsilon);
1315 CMatrix jacobian(num_sources, num_residuals);
1322 for (
unsigned int i = 0; i < num_sources; i++)
1325 const double epsilon = -sign(base_softmax_params[i]) * 1e-3;
1328 CVector perturbed_params = base_softmax_params;
1329 perturbed_params[i] += epsilon;
1335 jacobian.setrow(i, (perturbed_residuals - base_residuals) / epsilon);
1351 CMatrix jacobian_transpose_jacobian = jacobian * Transpose(jacobian);
1354 jacobian_transpose_jacobian.ScaleDiagonal(1.0 + lambda);
1357 CVector jacobian_times_residuals = jacobian * residuals;
1360 if (det(jacobian_transpose_jacobian) <= 1e-6)
1363 const size_t matrix_size = jacobian_transpose_jacobian.getnumcols();
1364 CMatrix identity = CMatrix::Diag(matrix_size);
1365 jacobian_transpose_jacobian += lambda * identity;
1369 CVector parameter_update = jacobian_times_residuals / jacobian_transpose_jacobian;
1371 return parameter_update;
1381 CMatrix jacobian_transpose_jacobian = jacobian * Transpose(jacobian);
1384 jacobian_transpose_jacobian.ScaleDiagonal(1.0 + lambda);
1387 CVector jacobian_times_residuals = jacobian * residuals;
1390 if (det(jacobian_transpose_jacobian) <= 1e-6)
1393 const size_t matrix_size = jacobian_transpose_jacobian.getnumcols();
1394 CMatrix identity = CMatrix::Diag(matrix_size);
1395 jacobian_transpose_jacobian += lambda * identity;
1399 CVector parameter_update = jacobian_times_residuals / jacobian_transpose_jacobian;
1401 return parameter_update;
1417 const double tolerance = 1e-10;
1418 const int max_iterations = 1000;
1419 const double improvement_threshold = 0.8;
1420 const double lambda_decrease_factor = 1.2;
1421 const double lambda_increase_factor = 1.2;
1422 const double lambda_no_update_factor = 5.0;
1425 double lambda = 1.0;
1427 double previous_error = 1000.0;
1428 double initial_param_change = 10000.0;
1429 double current_param_change = 10000.0;
1433 while (current_error > tolerance &&
1434 current_param_change > tolerance &&
1435 iteration < max_iterations)
1438 CVector current_params;
1444 previous_error = current_error;
1447 CVector parameter_update;
1454 if (parameter_update.num == 0)
1456 lambda *= lambda_no_update_factor;
1461 current_param_change = parameter_update.norm2();
1463 initial_param_change = current_param_change;
1466 CVector updated_params = current_params - parameter_update;
1474 current_error = residuals.norm2();
1477 if (current_error < previous_error * improvement_threshold)
1480 lambda /= lambda_decrease_factor;
1482 else if (current_error > previous_error)
1485 lambda *= lambda_increase_factor;
1493 current_error = previous_error;
1500 rtw_->AppendPoint(iteration, current_error);
1501 rtw_->SetXRange(0, iteration);
1502 rtw_->SetProgress(1.0 - current_param_change / initial_param_change);
1513 rtw_->SetProgress(1.0);
1525 CVector predicted_concentrations = source_mean_matrix * contribution_vector;
1533 return predicted_concentrations;
1541 CVector predicted_isotope_concentrations = source_isotope_matrix * contribution_vector;
1543 return predicted_isotope_concentrations;
1556 double predicted_corresponding_element_concentration = 0;
1558 predicted_corresponding_element_concentration += contributions[source_idx] *
1560 double ratio = C[i]/predicted_corresponding_element_concentration;
1562 C[i] = (ratio/standard_ratio-1.0)*1000.0;
1580 double source_data_log_likelihood = 0.0;
1581 double element_observation_log_likelihood = 0.0;
1582 double isotope_observation_log_likelihood = 0.0;
1605 double total_log_likelihood = source_data_log_likelihood +
1606 element_observation_log_likelihood +
1607 isotope_observation_log_likelihood +
1608 contribution_log_prior;
1610 return total_log_likelihood;
1620 CMatrix source_means(num_elements, num_sources);
1623 for (
size_t element_idx = 0; element_idx < num_elements; element_idx++)
1627 for (
size_t source_idx = 0; source_idx < num_sources; source_idx++)
1639 source_means[element_idx][source_idx] = element_dist->
Mean();
1643 source_means[element_idx][source_idx] = element_dist->
DataMean();
1648 return source_means;
1657 const bool is_tracer = lookup(
element_order_, base_element) != -1;
1672 CMatrix source_isotope_means(num_isotopes, num_sources);
1675 for (
size_t isotope_idx = 0; isotope_idx < num_isotopes; isotope_idx++)
1679 const string& base_element = isotope_info.
base_element;
1682 for (
size_t source_idx = 0; source_idx < num_sources; source_idx++)
1691 double mean_delta = NAN;
1692 const double mean_base_concentration =
IsotopeBaseMean(source_group, base_element, param_mode);
1696 mean_delta = isotope_dist->
Mean();
1700 mean_delta = isotope_dist->
DataMean();
1705 double delta_ratio = (mean_delta / 1000.0) + 1.0;
1706 double absolute_isotope_concentration = delta_ratio * standard_ratio * mean_base_concentration;
1708 source_isotope_means[isotope_idx][source_idx] = absolute_isotope_concentration;
1712 return source_isotope_means;
1718 const size_t num_contributions = include_all ?
1722 CVector contributions(num_contributions);
1725 for (
size_t source_idx = 0; source_idx < num_contributions; source_idx++)
1732 return contributions;
1738 CVector softmax_parameters(num_sources);
1741 for (
size_t source_idx = 0; source_idx < num_sources; source_idx++)
1748 return softmax_parameters;
1766 double constrained_contribution = 1.0 - sum_of_independent;
1781 for (
size_t i = 0; i < static_cast<size_t>(contributions.num); i++)
1787 if (contributions.min() < 0.0) {
1788 std::cerr <<
"Warning: Negative contribution detected in SetContribution()" << std::endl;
1789 std::cerr <<
" Min value: " << contributions.min() << std::endl;
1796 double denominator = 0.0;
1797 for (
size_t i = 0; i < static_cast<size_t>(softmax_params.num); i++)
1799 denominator += exp(softmax_params[i]);
1803 for (
size_t i = 0; i < static_cast<size_t>(softmax_params.num); i++)
1805 double softmax_param = softmax_params.at(i);
1806 double contribution = exp(softmax_param) / denominator;
1815 if (resulting_contributions.min() < -1e-12) {
1816 std::cerr <<
"Warning: Invalid contributions after softmax transformation" << std::endl;
1817 std::cerr <<
" Min contribution: " << resulting_contributions.min() << std::endl;
1818 std::cerr <<
" This should not happen with softmax - check for numerical issues" << std::endl;
1823 size_t element_index,
1824 size_t source_index)
1830 const size_t num_contribution_params = size() - 1;
1831 const size_t element_mu_base_index = num_contribution_params;
1835 const size_t parameter_index = element_mu_base_index +
1841 std::cerr <<
"Error: Parameter index out of bounds in GetElementDistributionMuParameter" << std::endl;
1849 size_t element_index,
1850 size_t source_index)
1857 const size_t num_contribution_params = size() - 1;
1859 const size_t element_sigma_base_index = num_contribution_params + num_element_mu_params;
1862 const size_t parameter_index = element_sigma_base_index +
1868 std::cerr <<
"Error: Parameter index out of bounds in GetElementDistributionSigmaParameter" << std::endl;
1876 size_t element_index,
1877 size_t source_index)
1881 if (mu_param ==
nullptr) {
1882 std::cerr <<
"Warning: Unable to retrieve μ parameter for element "
1883 << element_index <<
", source " << source_index << std::endl;
1887 return mu_param->
Value();
1891 size_t element_index,
1892 size_t source_index)
1896 if (sigma_param ==
nullptr) {
1897 std::cerr <<
"Warning: Unable to retrieve σ parameter for element "
1898 << element_index <<
", source " << source_index << std::endl;
1902 return sigma_param->
Value();
1913 const bool estimating_contributions =
1915 const bool estimating_profiles =
1922 const size_t num_element_sigma_params = num_element_mu_params;
1923 const size_t num_isotope_sigma_params = num_isotope_mu_params;
1929 if (estimating_contributions && index < num_contribution_params)
1943 size_t element_mu_start = num_contribution_params;
1944 size_t element_mu_end = element_mu_start + num_element_mu_params;
1946 if (estimating_profiles &&
1948 index >= element_mu_start && index < element_mu_end)
1950 size_t offset = index - element_mu_start;
1961 size_t isotope_mu_start = element_mu_end;
1962 size_t isotope_mu_end = isotope_mu_start + num_isotope_mu_params;
1964 if (estimating_profiles &&
1966 index >= isotope_mu_start && index < isotope_mu_end)
1968 size_t offset = index - isotope_mu_start;
1979 size_t element_sigma_start = isotope_mu_end;
1980 size_t element_sigma_end = element_sigma_start + num_element_sigma_params;
1982 if (estimating_profiles &&
1984 index >= element_sigma_start && index < element_sigma_end)
1987 std::cerr <<
"Error: Element σ parameter cannot be negative (value = "
1988 << value <<
")" << std::endl;
1992 size_t offset = index - element_sigma_start;
2003 size_t isotope_sigma_start = element_sigma_end;
2004 size_t isotope_sigma_end = isotope_sigma_start + num_isotope_sigma_params;
2006 if (estimating_profiles &&
2008 index >= isotope_sigma_start && index < isotope_sigma_end)
2011 std::cerr <<
"Error: Isotope σ parameter cannot be negative (value = "
2012 << value <<
")" << std::endl;
2016 size_t offset = index - isotope_sigma_start;
2027 size_t error_element_index = isotope_sigma_end;
2029 if (estimating_contributions && index == error_element_index)
2032 std::cerr <<
"Error: Element error std dev cannot be negative (value = "
2033 << value <<
")" << std::endl;
2042 size_t error_isotope_index = error_element_index + 1;
2044 if (estimating_contributions && index == error_isotope_index)
2047 std::cerr <<
"Error: Isotope error std dev cannot be negative (value = "
2048 << value <<
")" << std::endl;
2057 std::cerr <<
"Warning: Parameter index " << index <<
" not recognized" << std::endl;
2068 bool all_successful =
true;
2071 for (
size_t i = 0; i < static_cast<size_t>(values.num); i++)
2074 all_successful &= success;
2079 return all_successful;
2092 return parameter_values;
2097 CVector gradient(parameters.num);
2098 CVector perturbed_params = parameters;
2105 for (
size_t i = 0; i < static_cast<size_t>(parameters.num); i++)
2115 gradient[i] = (perturbed_log_likelihood - baseline_log_likelihood) /
epsilon_;
2118 perturbed_params[i] = parameters[i];
2122 return gradient / gradient.norm2();
2132 CVector gradient_direction =
Gradient(current_params, est_mode);
2135 CVector candidate_step1 = current_params +
distance_coeff_ * gradient_direction;
2139 CVector candidate_step2 = current_params + 2.0 *
distance_coeff_ * gradient_direction;
2144 std::cout <<
"Distance Coefficient: " <<
distance_coeff_ << std::endl;
2152 if (likelihood_step2 > likelihood_step1 && likelihood_step2 > baseline_likelihood)
2156 return candidate_step2;
2160 else if (likelihood_step1 > likelihood_step2 && likelihood_step1 > baseline_likelihood)
2164 return candidate_step1;
2170 const int max_backtrack_iterations = 5;
2171 int backtrack_count = 0;
2174 while (baseline_likelihood >= likelihood_step1 && backtrack_count < max_backtrack_iterations)
2178 candidate_step1 = current_params +
distance_coeff_ * gradient_direction;
2185 if (backtrack_count < max_backtrack_iterations)
2189 return candidate_step1;
2194 std::cerr <<
"Warning: No improvement found after " << max_backtrack_iterations
2195 <<
" backtracking iterations" << std::endl;
2197 return current_params;
2231 elem_info.include_in_analysis)
2242 vector<string> problems;
2248 const string& base = isotope_info.base_element;
2251 problems.push_back(
"Isotope '" + isotope_name +
"' has no base element.");
2253 problems.push_back(
"The base element '" + base +
"' of isotope '" + isotope_name +
"' is not in the data.");
2259 problems.push_back(
"The base element '" + base +
"' of isotope '" + isotope_name +
"' is not marked as an element or as organic carbon.");
2260 else if (!base_info->second.include_in_analysis)
2261 problems.push_back(
"The base element '" + base +
"' of isotope '" + isotope_name +
"' is excluded from the analysis.");
2286 elem_info.include_in_analysis)
2296 elem_info.include_in_analysis)
2322 vector<string> source_names;
2325 for (
const auto& [group_name, profile_set] : *
this)
2329 source_names.push_back(group_name);
2333 return source_names;
2339 for (
auto& [group_name, profile_set] : *
this)
2342 for (
const auto& [profile_name, profile] : profile_set)
2344 if (profile_name == sample_name)
2347 return profile_set.GetProfile(profile_name);
2365 for (
size_t i = 0; i < source_order.size(); i++)
2367 (*contributions)[source_order[i]] = contribution_values[i];
2371 result.
SetName(
"Contributions");
2384 CVector predicted_concentrations =
PredictTarget(param_mode);
2388 for (
size_t i = 0; i < element_names.size(); i++)
2390 predicted_profile->
AppendElement(element_names[i], predicted_concentrations[i]);
2394 result.
SetName(
"Modeled Elemental Profile");
2404 CVector predicted_values(num_observations);
2407 for (
size_t i = 0; i < num_observations; i++)
2412 return predicted_values;
2425 for (
size_t i = 0; i < isotope_names.size(); i++)
2427 predicted_isotopes->
AppendElement(isotope_names[i], predicted_delta_values[i]);
2431 result.
SetName(
"Modeled Elemental Profile for Isotopes");
2456 result.
SetName(
"Observed vs Modeled Elemental Profile");
2465 vector<ResultItem> mlr_results;
2468 for (
auto& [group_name, profile_set] : *
this)
2471 ResultItem regression_result = profile_set.GetRegressionsAsResult();
2475 regression_result.
SetName(
"OM & Size MLR for " + group_name);
2477 mlr_results.push_back(regression_result);
2501 result.
SetName(
"Observed vs Modeled Elemental Profile for Isotopes");
2518 for (
size_t i = 0; i < element_names.size(); i++)
2520 observed_profile->
AppendElement(element_names[i], observed_concentrations[i]);
2524 result.
SetName(
"Observed Elemental Profile");
2541 for (
size_t i = 0; i < isotope_names.size(); i++)
2543 observed_isotopes->
AppendElement(isotope_names[i], observed_delta_values[i]);
2547 result.
SetName(
"Observed Elemental Profile for Isotopes");
2558 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2563 for (
unsigned int element_counter = 0; element_counter <
element_order_.size(); element_counter++)
2572 resitem.
SetName(
"Calculated mean elemental contents");
2582 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2587 for (
unsigned int element_counter = 0; element_counter <
element_order_.size(); element_counter++)
2599 resitem.
SetName(
"Calculated elemental contents standard deviations");
2608 vector<ResultItem> source_profile_results;
2611 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2618 result_item.
SetName(
"Elemental Profiles for " + it->first);
2626 *profile_set = it->second;
2629 source_profile_results.push_back(result_item);
2633 return source_profile_results;
2641 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2646 for (
unsigned int element_counter = 0; element_counter <
element_order_.size(); element_counter++)
2655 resitem.
SetName(
"Calculated mu parameter of elemental contents");
2665 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2670 for (
unsigned int element_counter = 0; element_counter <
element_order_.size(); element_counter++)
2679 resitem.
SetName(
"Infered mu parameter elemental contents");
2689 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2694 for (
unsigned int element_counter = 0; element_counter <
element_order_.size(); element_counter++)
2696 double sigma = it->second.GetElementDistribution(
element_order_[element_counter])->GetEstimatedSigma();
2697 double mu = it->second.GetElementDistribution(
element_order_[element_counter])->GetEstimatedMu();
2705 resitem.
SetName(
"Infered mean of elemental contents");
2715 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2720 for (
unsigned int element_counter = 0; element_counter <
element_order_.size(); element_counter++)
2722 double sigma = it->second.GetElementDistribution(
element_order_[element_counter])->GetEstimatedSigma();
2730 resitem.
SetName(
"Infered sigma parameter");
2740 QJsonArray tools_used_json_array;
2745 tools_used_json_array.append(QString::fromStdString(*it));
2748 return tools_used_json_array;
2753 QJsonObject json_object;
2756 for (QMap<QString, double>::const_iterator it =
options_.cbegin(); it !=
options_.cend(); it++)
2758 json_object[it.key()] = it.value();
2776 foreach (
const QJsonValue& value, jsonarray)
2790 for (
const QString& key : jsonobject.keys())
2793 elem_info.
Role =
Role(jsonobject[key].toObject()[
"Role"].toString());
2794 elem_info.
standard_ratio = jsonobject[key].toObject()[
"Standard Ratio"].toDouble();
2795 elem_info.
base_element = jsonobject[key].toObject()[
"Base Element"].toString().toStdString();
2797 elem_info.
notes = jsonobject[key].toObject()[
"Notes"].toString().toStdString();
2817 for (
const QString& key : jsonobject.keys())
2823 error = QStringLiteral(
"group '%1', %2").arg(key, set_error);
2835 for (
const QString& key : jsonobject.keys())
2837 options_[key] = jsonobject[key].toDouble();
2845 QJsonObject json_object;
2848 for (map<string, Elemental_Profile_Set>::const_iterator it = cbegin(); it != cend(); it++)
2850 json_object[QString::fromStdString(it->first)] = it->second.toJsonObject();
2859 file->write(
"***\n");
2860 file->write(
"Elemental Profiles\n");
2863 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2865 file->write(
"**\n");
2866 file->write(QString::fromStdString(it->first +
"\n").toUtf8());
2867 it->second.writetofile(file);
2886 QJsonParseError parse_error;
2887 QJsonDocument document = QJsonDocument::fromJson(fil->readAll(), &parse_error);
2888 if (document.isNull())
2890 load_error_ = QStringLiteral(
"The file is not valid JSON (%1).").arg(parse_error.errorString());
2893 QJsonObject jsondoc = document.object();
2899 load_error_ = QStringLiteral(
"Invalid data value in %1.").arg(data_error);
2906 target_group_ = jsondoc[
"Target Group"].toString().toStdString();
2913 QJsonObject json_object;
2918 QJsonObject elem_info_json_obj;
2919 elem_info_json_obj[
"Role"] =
Role(it->second.Role);
2920 elem_info_json_obj[
"Standard Ratio"] = it->second.standard_ratio;
2921 elem_info_json_obj[
"Base Element"] = QString::fromStdString(it->second.base_element);
2922 elem_info_json_obj[
"Include"] = it->second.include_in_analysis;
2923 elem_info_json_obj[
"Notes"] = QString::fromStdString(it->second.notes);
2925 json_object[QString::fromStdString(it->first)] = elem_info_json_obj;
2935 return "DoNotInclude";
2941 return "ParticleSize";
2946 return "DoNotInclude";
2952 if (role_string ==
"DoNotInclude")
2954 else if (role_string ==
"Element")
2956 else if (role_string ==
"Isotope")
2958 else if (role_string ==
"ParticleSize")
2960 else if (role_string ==
"OM")
2969 const string& particle_size,
2971 const double& p_value_threshold)
2979 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2981 it->second.SetRegressionModels(om, particle_size, form, p_value_threshold);
2989 for (
auto& [group_name, profile_set] : *
this)
2992 if (models ==
nullptr)
3010 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3015 it->second.DetectOutliers(lower_threshold, upper_threshold);
3025 const size_t num_sources = size() - 1;
3032 for (map<string, Elemental_Profile_Set>::iterator source = begin(); source != end(); source++)
3074 if (eigen_vector.
size() == 0)
3141 for (map<string, Elemental_Profile_Set>::const_iterator source_group = cbegin(); source_group != cend(); source_group++)
3146 count += source_group->second.size();
3156 CMBVector discriminant_scores(
operator[](source_group).size());
3159 size_t sample_index = 0;
3160 for (map<string, Elemental_Profile>::iterator sample =
operator[](source_group).begin();
3161 sample != operator[](source_group).end();
3165 discriminant_scores[sample_index] = sample->second.CalculateDotProduct(eigenvector);
3166 discriminant_scores.
SetLabel(sample_index, sample->first);
3171 return discriminant_scores;
3179 for (map<string, Elemental_Profile_Set>::iterator profile_set = begin();
3180 profile_set != end();
3184 if (profile_set->first != excluded_source && profile_set->first !=
target_group_)
3187 for (map<string, Elemental_Profile>::iterator profile = profile_set->second.begin();
3188 profile != profile_set->second.end();
3191 combined_sources.
AppendProfile(profile->first, profile->second);
3196 return combined_sources;
3203 const size_t num_elements = element_names.size();
3205 CMBVector bracket_test_results(num_elements);
3209 false,
false, correct_based_on_om_n_size, target_sample);
3211 for (
size_t i = 0; i < num_elements; i++)
3213 bracket_test_results.
SetLabel(i, element_names[i]);
3216 double source_minimum = std::numeric_limits<double>::infinity();
3217 double source_maximum = -std::numeric_limits<double>::infinity();
3218 for (map<string, Elemental_Profile_Set>::iterator it = corrected_data.begin();
3219 it != corrected_data.end();
3224 source_maximum = max(source_maximum, it->second.GetElementDistribution(element_names[i])->GetMaximum());
3225 source_minimum = min(source_minimum, it->second.GetElementDistribution(element_names[i])->GetMinimum());
3229 const double margin = tolerance * (source_maximum - source_minimum);
3230 const double target_concentration = corrected_data.at(
target_group_)
3231 .GetProfile(target_sample)->at(element_names[i]);
3232 const bool exceeds_max = target_concentration > source_maximum + margin;
3233 const bool below_min = target_concentration < source_minimum - margin;
3236 bracket_test_results[i] = (exceeds_max || below_min) ? 1.0 : 0.0;
3242 element_names[i] +
" value is higher than the maximum of the sources");
3247 element_names[i] +
" value is lower than the minimum of the sources");
3251 return bracket_test_results;
3256 bool correct_based_on_om_n_size,
3257 bool exclude_elements,
3258 bool exclude_samples,
3264 const size_t num_elements =
CountElements(exclude_elements);
3265 CMBMatrix bracket_results(num_target_samples, num_elements);
3268 size_t sample_index = 0;
3269 for (map<string, Elemental_Profile>::iterator sample = at(
target_group_).begin();
3275 if (correct_based_on_om_n_size)
3278 exclude_samples, exclude_elements,
true, sample->first);
3283 exclude_samples, exclude_elements,
false);
3291 for (
size_t element_index = 0; element_index < element_names.size(); element_index++)
3293 bracket_results[element_index][sample_index] = bracket_vector.
valueAt(element_index);
3294 bracket_results.
SetRowLabel(element_index, element_names[element_index]);
3301 return bracket_results;
3315 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3320 if (calculate_optimal_lambda)
3323 transformed_data[it->first] = it->second.ApplyBoxCoxTransform(&lambda_parameters);
3328 transformed_data[it->first] = it->second.ApplyBoxCoxTransform();
3337 return transformed_data;
3342 map<string, ConcentrationSet> element_concentrations;
3346 for (
size_t i = 0; i < element_names.size(); i++)
3351 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3357 for (map<string, Elemental_Profile>::iterator sample = it->second.begin();
3358 sample != it->second.end();
3361 concentration_set.
AppendValue(sample->second[element_names[i]]);
3366 element_concentrations[element_names[i]] = concentration_set;
3369 return element_concentrations;
3379 CMBVector lambda_parameters(element_names.size());
3381 for (
size_t i = 0; i < element_names.size(); i++)
3385 lambda_parameters[i] = concentration_sets[element_names[i]].FindOptimalBoxCoxParameter(-5, 5, 10);
3389 lambda_parameters.
SetLabels(element_names);
3391 return lambda_parameters;
3399 for (
size_t i = 0; i < element_names.size(); i++)
3402 ConcentrationSet concentration_set1 = *at(source1).GetElementDistribution(element_names[i]);
3403 ConcentrationSet concentration_set2 = *at(source2).GetElementDistribution(element_names[i]);
3406 double std1 = NAN, std2 = NAN, mean1 = NAN, mean2 = NAN;
3426 if (concentration_set1.size() < 2 || concentration_set2.size() < 2)
3433 double standard_error = sqrt(pow(std1, 2) / concentration_set1.size() +
3434 pow(std2, 2) / concentration_set2.size());
3435 double t_statistic = (mean1 - mean2) / standard_error;
3438 size_t degrees_of_freedom = concentration_set1.size() + concentration_set2.size() - 2;
3439 double p_value_upper = gsl_cdf_tdist_Q(t_statistic, degrees_of_freedom);
3440 double p_value_lower = gsl_cdf_tdist_P(t_statistic, degrees_of_freedom);
3443 p_value_upper = min(p_value_upper, 1.0 - p_value_upper);
3444 p_value_lower = min(p_value_lower, 1.0 - p_value_lower);
3445 double p_value = p_value_upper + p_value_lower;
3459 for (
size_t i = 0; i < element_names.size(); i++)
3462 ConcentrationSet concentration_set1 = *at(source1).GetElementDistribution(element_names[i]);
3463 ConcentrationSet concentration_set2 = *at(source2).GetElementDistribution(element_names[i]);
3466 double std1 = NAN, std2 = NAN, mean1 = NAN, mean2 = NAN;
3485 double diff_power = 2.0 * fabs(mean1 - mean2) / (std1 + std2);
3487 differentiation_powers.
AppendElement(element_names[i], diff_power);
3490 return differentiation_powers;
3498 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != prev(end()); it++)
3502 for (map<string, Elemental_Profile_Set>::iterator it2 = next(it); it2 != end(); it2++)
3507 all_pairs.
AppendProfile(it->first +
" and " + it2->first, diff_power);
3522 for (
size_t i = 0; i < element_names.size(); i++)
3525 ConcentrationSet concentration_set1 = *at(source1).GetElementDistribution(element_names[i]);
3526 ConcentrationSet concentration_set2 = *at(source2).GetElementDistribution(element_names[i]);
3530 combined_set.
AppendSet(concentration_set2);
3534 size_t n1 = concentration_set1.size();
3535 int set1_below_limit = aquiutils::CountLessThan(ranks, n1, n1,
false);
3536 int set1_above_limit = aquiutils::CountGreaterThan(ranks, n1, n1,
false);
3537 int set2_below_limit = aquiutils::CountLessThan(ranks, n1, n1,
true);
3538 int set2_above_limit = aquiutils::CountGreaterThan(ranks, n1, n1,
true);
3541 double set1_fraction = double(set1_below_limit + set2_above_limit) / double(combined_set.size());
3542 double set2_fraction = double(set1_above_limit + set2_below_limit) / double(combined_set.size());
3545 double classification_percentage = max(set1_fraction, set2_fraction);
3547 classification_percentages.
AppendElement(element_names[i], classification_percentage);
3550 return classification_percentages;
3558 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != prev(end()); it++)
3562 for (map<string, Elemental_Profile_Set>::iterator it2 = next(it); it2 != end(); it2++)
3567 all_pairs.
AppendProfile(it->first +
" and " + it2->first, diff_power_pct);
3581 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != prev(end()); it++)
3585 for (map<string, Elemental_Profile_Set>::iterator it2 = next(it); it2 != end(); it2++)
3590 all_pairs.
AppendProfile(it->first +
" and " + it2->first, p_values);
3601 vector<string> error_messages;
3610 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3614 vector<string> negative_elements = it->second.CheckForNegativeValues(
element_order_);
3617 for (
size_t i = 0; i < negative_elements.size(); i++)
3619 error_messages.push_back(
"There are zero or negative values for element '" +
3620 negative_elements[i] +
"' in sample group '" +
3625 return error_messages;
3633 const double round_off = -1e-9;
3635 vector<string> error_messages;
3639 for (
size_t i = 0; i < source_names.size() && i <
static_cast<size_t>(contributions.num); i++)
3641 if (contributions[
static_cast<int>(i)] < round_off)
3643 error_messages.push_back(source_names[i] +
": " +
3644 aquiutils::numbertostring(contributions[
static_cast<int>(i)]));
3648 return error_messages;
3658 it->second.include_in_analysis = include_in_analysis;
3664 double weighted_sum = 0.0;
3665 double total_count = 0.0;
3668 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3673 ConcentrationSet* element_dist = it->second.GetElementDistribution(element);
3674 size_t sample_count = element_dist->size();
3679 weighted_sum += element_dist->
CalculateMean() * sample_count;
3687 total_count += sample_count;
3692 return weighted_sum / total_count;
3700 for (map<string, Elemental_Profile_Set>::const_iterator it = begin(); it != end(); it++)
3712 return combined_sources;
3718 CMBVector p_values(element_names.size());
3722 for (
size_t i = 0; i < element_names.size(); i++)
3725 p_values[i] = anova_result.
p_value;
3748 double sum_between = 0.0;
3749 double sum_within = 0.0;
3751 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
3752 source_group != end();
3757 ConcentrationSet* group_data = source_group->second.GetElementDistribution(element);
3759 size_t group_size = group_data->size();
3762 sum_between += pow(group_mean - grand_mean, 2) * group_size;
3769 anova.
SSB = sum_between;
3770 anova.
SSW = sum_within;
3778 size_t total_size = all_element_data->size();
3779 anova.
SST = pow(total_std_log, 2) * (total_size - 1);
3783 double sum_between = 0.0;
3784 double sum_within = 0.0;
3786 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
3787 source_group != end();
3792 ConcentrationSet* group_data = source_group->second.GetElementDistribution(element);
3794 size_t group_size = group_data->size();
3797 sum_between += pow(group_mean_log - grand_mean_log, 2) * group_size;
3804 anova.
SSB = sum_between;
3805 anova.
SSW = sum_within;
3809 size_t num_groups = this->size() - 1;
3810 size_t total_samples = all_element_data->size();
3813 size_t df_between = num_groups - 1;
3814 size_t df_within = total_samples - num_groups;
3817 anova.
MSB = anova.
SSB / double(df_between);
3818 anova.
MSW = anova.
SSW / double(df_within);
3821 anova.
F = anova.
MSB / anova.
MSW;
3824 anova.
p_value = gsl_cdf_fdist_Q(anova.
F, df_between, total_samples);
3839 element->second.include_in_analysis =
false;
3843 for (
size_t i = 0; i < elements.size(); i++)
3860 for (map<string, Elemental_Profile_Set>::const_iterator it = cbegin(); it != cend(); it++)
3865 reduced_dataset[it->first] = it->second.EliminateSamples(
3871 reduced_dataset[it->first] = it->second;
3885 return reduced_dataset;
3891 for (map<string, Elemental_Profile_Set>::const_iterator it = cbegin(); it != cend(); it++)
3893 if (it->second.count(sample_name) == 1)
3895 return it->second.at(sample_name);
3912 new_target_group.
AppendProfile(source_sample_name, target_profile);
3925 return modified_dataset;
3929 const double& percentage,
3930 unsigned int num_iterations,
3931 const string& target_sample,
3946 contribution_time_series.setname(source_idx,
samplesetsorder_[source_idx]);
3950 for (
size_t iteration = 0; iteration < num_iterations; iteration++)
3959 rtw_->SetProgress(
double(iteration) /
double(num_iterations));
3976 return contribution_time_series;
3981 const double& percentage,
3982 unsigned int num_iterations,
3983 const string& target_sample,
4002 for (
size_t iteration = 0; iteration < num_iterations; iteration++)
4011 rtw_->SetProgress(
double(iteration) /
double(num_iterations));
4030 results->
SetName(
"Error Analysis for target sample '" + target_sample +
"' (random seed " + std::to_string(seed) +
")");
4031 contributions_result.
SetName(
"Error Analysis");
4032 contributions_result.
SetResult(contributions);
4038 if (num_iterations < 101)
4052 results->
Append(contributions_result);
4058 *distributions = contributions->distribution(100, 0, -1);
4061 distributions_result.
SetName(
"Posterior Distributions");
4065 distributions_result.
SetResult(distributions);
4066 results->
Append(distributions_result);
4076 double percentile_2_5 = contributions->at(i).percentile(0.025);
4077 double percentile_97_5 = contributions->at(i).percentile(0.975);
4078 double mean_contribution = contributions->at(i).mean();
4079 double median_contribution = contributions->at(i).percentile(0.5);
4084 interval.
SetMean(mean_contribution);
4085 interval.
SetMedian(median_contribution);
4087 (*credible_intervals)[contributions->getSeriesName(i)] = interval;
4091 intervals_result.
SetName(
"Source Contribution Credible Intervals");
4095 intervals_result.
SetResult(credible_intervals);
4101 results->
Append(intervals_result);
4107 const string& source_group,
4109 bool apply_om_size_correction)
4126 size_t valid_sample_count = 0;
4127 for (map<string, Elemental_Profile>::iterator sample = at(source_group).begin();
4128 sample != at(source_group).end();
4131 if (sample->first.empty() || !sample->second.IsIncludedInAnalysis())
4137 test_dataset[source_group].GetProfile(sample->first)->SetIncludedInAnalysis(
false);
4150 if (negative_elements.size() == 0)
4160 rtw_->SetProgress(
double(valid_sample_count) /
double(at(source_group).size()));
4175 validation_results.
SetLabel(valid_sample_count, sample->first);
4176 valid_sample_count++;
4181 for (
size_t i = 0; i < negative_elements.size(); i++)
4188 return validation_results;
4193 bool apply_om_size_correction,
4194 map<
string, vector<string>>& negative_elements)
4209 size_t valid_sample_count = 0;
4210 for (map<string, Elemental_Profile>::iterator sample = at(
target_group_).begin();
4216 if (sample->first !=
"" && sample->second.IsIncludedInAnalysis())
4225 if (negative_elements[sample->first].size() == 0)
4233 rtw_->SetProgress(
double(valid_sample_count) /
double(at(
target_group_).size()));
4234 rtw_->SetLabel(QString::fromStdString(sample->first));
4242 contribution_results.
SetLabel(valid_sample_count, sample->first);
4243 valid_sample_count++;
4251 rtw_->SetProgress(1.0);
4254 return contribution_results;
4260 vector<string> all_sample_names;
4263 for (map<string, Elemental_Profile_Set>::const_iterator profile_set = cbegin();
4264 profile_set != cend();
4271 for (map<string, Elemental_Profile>::const_iterator profile = profile_set->second.cbegin();
4272 profile != profile_set->second.cend();
4275 all_sample_names.push_back(profile->first);
4280 return all_sample_names;
4287 vector<string> selected_samples;
4290 for (
size_t i = 0; i < all_samples.size(); i++)
4293 double random_value = stream.
Uniform();
4296 if (random_value < percentage)
4298 selected_samples.push_back(all_samples[i]);
4302 return selected_samples;
4306 const string& target_sample,
4307 map<string, string> arguments,
4310 const string& working_folder)
4316 if (progress_window ==
nullptr)
4317 progress_window = &discarded_progress;
4324 std::uint64_t seed = 0;
4327 results.
SetError(
"The random seed '" + arguments[
"Random seed"] +
"' is not a whole number.");
4331 results.
SetName(
"MCMC results for '" + target_sample +
"' (random seed " + std::to_string(seed) +
")");
4334 bool apply_om_size_correction = (arguments[
"Apply size and organic matter correction"] ==
"true");
4341 if (negative_elements.size() > 0)
4344 results.
SetError(
"Negative elemental content in ");
4345 for (
size_t i = 0; i < negative_elements.size(); i++)
4356 mcmc->
Model = &corrected_data;
4359 progress_window->
SetTitle(
"Acceptance Rate", 0);
4360 progress_window->
SetTitle(
"Perturbation Factor", 1);
4361 progress_window->
SetTitle(
"Log posterior value", 2);
4365 progress_window->
Start();
4371 mcmc->
SetProperty(
"number_of_samples", arguments[
"Number of samples"]);
4372 mcmc->
SetProperty(
"number_of_chains", arguments[
"Number of chains"]);
4373 mcmc->
SetProperty(
"number_of_burnout_samples", arguments[
"Samples to be discarded (burnout)"]);
4374 mcmc->
SetProperty(
"dissolve_chains", arguments[
"Dissolve Chains"]);
4376 mcmc->
SetProperty(
"covariance_proposal", arguments[
"Correlated proposal"]);
4384 if (!QString::fromStdString(arguments[
"Samples File Name"]).contains(
"/"))
4386 output_path = working_folder +
"/";
4390 int num_chains = QString::fromStdString(arguments[
"Number of chains"]).toInt();
4391 int num_samples = QString::fromStdString(arguments[
"Number of samples"]).toInt();
4392 mcmc->
step(num_chains, num_samples, output_path + arguments[
"Samples File Name"],
4397 size_t last_source_idx = source_names.size() - 1;
4399 source_names[last_source_idx] +
"_contribution");
4405 mcmc_samples_result.
SetName(
"MCMC samples");
4407 results.
Append(mcmc_samples_result);
4410 int burnin_samples = QString::fromStdString(arguments[
"Samples to be discarded (burnout)"]).toInt();
4415 *posterior_distributions =
mcmc_samples->distribution(100, burnin_samples);
4417 posterior_distributions_result.
SetName(
"Posterior Distributions");
4421 posterior_distributions_result.
SetResult(posterior_distributions);
4422 results.
Append(posterior_distributions_result);
4427 for (
size_t i = 0; i < corrected_data.
GetSourceOrder().size(); i++)
4432 double percentile_2_5 =
mcmc_samples->at(i).percentile(0.025, burnin_samples);
4433 double percentile_97_5 =
mcmc_samples->at(i).percentile(0.975, burnin_samples);
4435 double median_contribution =
mcmc_samples->at(i).percentile(0.5, burnin_samples);
4439 interval.
SetMean(mean_contribution);
4440 interval.
SetMedian(median_contribution);
4442 (*contribution_credible_intervals)[
mcmc_samples->getSeriesName(i)] = interval;
4446 contribution_intervals_result.
SetName(
"Source Contribution Credible Intervals");
4450 contribution_intervals_result.
SetResult(contribution_credible_intervals);
4452 contribution_intervals_result.
setYAxisTitle(
"Contribution");
4455 results.
Append(contribution_intervals_result);
4459 vector<string> element_names = corrected_data.
ElementOrder();
4460 vector<string> isotope_names = corrected_data.
IsotopeOrder();
4461 vector<string> all_constituent_names = element_names;
4462 all_constituent_names.insert(all_constituent_names.end(), isotope_names.begin(), isotope_names.end());
4465 for (
size_t i = 0; i < predicted_samples.size(); i++)
4467 predicted_samples.setname(i, all_constituent_names[i]);
4472 for (
size_t i = 0; i < predicted_samples.size(); i++)
4477 predicted_elements.append(predicted_samples[i], predicted_samples.getSeriesName(i));
4483 *predicted_element_distributions = predicted_elements.distribution(100, burnin_samples);
4486 for (
size_t i = 0; i < predicted_elements.size(); i++)
4492 predicted_elements_result.
SetName(
"Posterior Predicted Constituents");
4496 predicted_elements_result.
SetResult(predicted_element_distributions);
4497 results.
Append(predicted_elements_result);
4503 vector<double> percentile_2_5_all = predicted_samples.percentile(0.025, burnin_samples);
4504 vector<double> percentile_97_5_all = predicted_samples.percentile(0.975, burnin_samples);
4505 vector<double> mean_all = predicted_samples.mean(burnin_samples);
4506 vector<double> median_all = predicted_samples.percentile(0.5, burnin_samples);
4508 for (
size_t i = 0; i < predicted_element_distributions->size(); i++)
4513 interval.
SetMean(mean_all[i]);
4516 (*predicted_element_intervals)[predicted_element_distributions->getSeriesName(i)] = interval;
4517 (*predicted_element_intervals)[predicted_element_distributions->getSeriesName(i)].
SetValue(
4521 ResultItem predicted_element_intervals_result;
4522 predicted_element_intervals_result.
SetName(
"Predicted Samples Credible Intervals");
4526 predicted_element_intervals_result.
SetResult(predicted_element_intervals);
4527 predicted_element_intervals_result.
setXAxisTitle(
"Constituent");
4528 predicted_element_intervals_result.
setYAxisTitle(
"Concentration");
4530 results.
Append(predicted_element_intervals_result);
4535 for (
size_t i = 0; i < predicted_samples.size(); i++)
4540 predicted_isotopes.append(predicted_samples[i], predicted_samples.getSeriesName(i));
4545 *predicted_isotope_distributions = predicted_isotopes.distribution(100, burnin_samples);
4548 for (
size_t i = 0; i < predicted_isotopes.size(); i++)
4555 predicted_isotopes_result.
SetName(
"Posterior Predicted Isotopes");
4559 predicted_isotopes_result.
SetResult(predicted_isotope_distributions);
4560 results.
Append(predicted_isotopes_result);
4564 size_t element_offset = corrected_data.
ElementOrder().size();
4566 for (
size_t i = 0; i < predicted_isotope_distributions->size(); i++)
4569 interval.
Set(
_range::low, percentile_2_5_all[i + element_offset]);
4571 interval.
SetMean(mean_all[i + element_offset]);
4572 interval.
SetMedian(median_all[i + element_offset]);
4574 (*predicted_isotope_intervals)[predicted_isotope_distributions->getSeriesName(i)] = interval;
4575 (*predicted_isotope_intervals)[predicted_isotope_distributions->getSeriesName(i)].
SetValue(
4579 ResultItem predicted_isotope_intervals_result;
4580 predicted_isotope_intervals_result.
SetName(
"Predicted Samples Credible Intervals for Isotopes");
4584 predicted_isotope_intervals_result.
SetResult(predicted_isotope_intervals);
4585 predicted_isotope_intervals_result.
setXAxisTitle(
"Isotope");
4586 predicted_isotope_intervals_result.
setYAxisTitle(
"Delta value (per mil)");
4588 results.
Append(predicted_isotope_intervals_result);
4599 std::vector<std::vector<double>> chains(std::max(num_chains, 1));
4600 const TimeSeries<double>& series =
mcmc_samples->at(i);
4601 for (
int k = std::max(burnin_samples, 0); k < int(series.size()); k++)
4602 chains[k % std::max(num_chains, 1)].push_back(series.getValue(k));
4606 (*rhat_values)[i] = d.
rhat;
4617 rhat_result.
SetName(
"Convergence: split R-hat");
4626 results.
Append(rhat_result);
4629 ess_result.
SetName(
"Convergence: effective sample size");
4638 results.
Append(ess_result);
4645 mcmc->
Model =
nullptr;
4656 QString safe =
name;
4657 safe.replace(QStringLiteral(
": "), QStringLiteral(
" - "));
4658 for (QChar& c : safe)
4660 if (c.unicode() < 32 || QStringLiteral(
"\\/:*?\"<>|").contains(c))
4661 c = QLatin1Char(
'_');
4663 while (safe.endsWith(QLatin1Char(
'.')) || safe.endsWith(QLatin1Char(
' ')))
4665 return safe.isEmpty() ? QStringLiteral(
"_") : safe;
4669 const map<string, string>& arguments,
4672 const string& working_folder,
4673 vector<string>* failed_writes)
4679 if (progress_window ==
nullptr)
4680 progress_window = &discarded_progress;
4684 vector<string> included_targets;
4685 for (
const auto& [sample_name, profile] : at(
target_group_))
4686 if (!sample_name.empty() && profile.IsIncludedInAnalysis())
4687 included_targets.push_back(sample_name);
4688 if (included_targets.empty())
4695 const size_t num_target_samples = included_targets.size();
4697 CMBMatrix contribution_statistics(num_columns, num_target_samples);
4703 contribution_statistics.
SetColumnLabel(source_idx * 4, source_name +
"-low");
4704 contribution_statistics.
SetColumnLabel(source_idx * 4 + 1, source_name +
"-high");
4705 contribution_statistics.
SetColumnLabel(source_idx * 4 + 2, source_name +
"-median");
4706 contribution_statistics.
SetColumnLabel(source_idx * 4 + 3, source_name +
"-mean");
4710 size_t sample_counter = 0;
4711 for (
const string& sample_name : included_targets)
4714 QDir sample_dir(QString::fromStdString(working_folder) +
"/" +
4716 const bool sample_dir_ok = sample_dir.exists() || sample_dir.mkpath(
".");
4717 if (!sample_dir_ok && failed_writes !=
nullptr)
4719 failed_writes->push_back(
"could not create folder " +
4720 sample_dir.absolutePath().toStdString());
4724 contribution_statistics.
SetRowLabel(sample_counter, sample_name);
4727 progress_window->
SetLabel(QString::fromStdString(sample_name));
4733 const string sample_folder = sample_dir_ok ? sample_dir.absolutePath().toStdString() : working_folder;
4734 Results mcmc_results =
MCMC(sample_name, arguments, mcmc, progress_window, sample_folder);
4739 for (map<string, ResultItem>::iterator result_item = mcmc_results.begin();
4740 sample_dir_ok && result_item != mcmc_results.end();
4743 QString file_path = sample_dir.absolutePath() +
"/" +
4744 SafeFileName(QString::fromStdString(result_item->first)) +
".txt";
4745 QFile output_file(file_path);
4746 if (!output_file.open(QIODevice::WriteOnly | QIODevice::Text))
4748 if (failed_writes !=
nullptr)
4749 failed_writes->push_back(file_path.toStdString() +
": " +
4750 output_file.errorString().toStdString());
4753 result_item->second.Result()->writetofile(&output_file);
4754 output_file.close();
4755 if (output_file.error() != QFileDevice::NoError && failed_writes !=
nullptr)
4757 failed_writes->push_back(file_path.toStdString() +
": " +
4758 output_file.errorString().toStdString());
4764 mcmc_results.at(
"3:Source Contribution Credible Intervals").Result());
4768 const string contribution_name =
samplesetsorder_[source_idx] +
"_contribution";
4769 const Range& contribution_interval = credible_intervals->at(contribution_name);
4772 contribution_statistics[sample_counter][4 * source_idx] = contribution_interval.
Get(
_range::low);
4773 contribution_statistics[sample_counter][4 * source_idx + 1] = contribution_interval.
Get(
_range::high);
4774 contribution_statistics[sample_counter][4 * source_idx + 2] = contribution_interval.
Median();
4775 contribution_statistics[sample_counter][4 * source_idx + 3] = contribution_interval.
Mean();
4781 progress_window->
SetProgress2(
double(sample_counter) /
double(num_target_samples));
4792 return contribution_statistics;
4812 return element->first;
4829 return element->first;
4846 vector<string> groups;
4847 vector<arma::mat> data;
4848 for (
auto& [group_name, profile_set] : *
this)
4852 arma::mat values(profile_set.size(), constituents.size());
4854 for (
const auto& [sample_name, profile] : profile_set)
4856 for (
size_t j = 0; j < constituents.size(); j++)
4857 values(row, j) = profile.GetValue(constituents[j]);
4860 groups.push_back(group_name);
4861 data.push_back(values);
4864 const size_t num_groups = groups.size();
4865 CMBMatrix confusion(
int(num_groups) + 1,
int(num_groups));
4866 for (
size_t g = 0; g < num_groups; g++)
4872 if (num_groups < 2 || constituents.empty())
4875 for (
size_t g = 0; g < num_groups; g++)
4878 for (arma::uword i = 0; i < data[g].n_rows; i++)
4881 vector<arma::rowvec> means(num_groups);
4882 arma::mat scatter(constituents.size(), constituents.size(), arma::fill::zeros);
4883 double degrees_of_freedom = 0;
4884 for (
size_t h = 0; h < num_groups; h++)
4886 arma::mat values = data[h];
4889 if (values.n_rows == 0)
4891 means[h] = arma::rowvec(constituents.size());
4892 means[h].fill(arma::datum::nan);
4895 means[h] = arma::mean(values, 0);
4898 arma::mat centered = values;
4899 centered.each_row() -= means[h];
4900 scatter += centered.t() * centered;
4901 degrees_of_freedom += double(values.n_rows) - 1.0;
4903 if (degrees_of_freedom <= 0)
4907 const arma::mat inverse = arma::pinv(scatter / degrees_of_freedom);
4909 const arma::rowvec
x = data[g].row(i);
4911 double best_distance = arma::datum::inf;
4912 for (
size_t h = 0; h < num_groups; h++)
4914 if (!means[h].is_finite())
4916 const arma::rowvec d =
x - means[h];
4917 const double distance = arma::as_scalar(d * inverse * d.t());
4918 if (distance < best_distance)
4920 best_distance = distance;
4924 confusion.matr[g][best] += 1;
4929 confusion.matr[g][num_groups] = data[g].n_rows > 0 ?
4930 std::round(1000.0 *
double(correct) /
double(data[g].n_rows)) / 10.0 : 0.0;
4938 CMatrix within_group_covariance(element_names.size());
4941 int total_degrees_of_freedom = 0;
4942 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
4943 source_group != end();
4949 int group_df = source_group->second.size() - 1;
4950 within_group_covariance += group_df * source_group->second.CalculateCovarianceMatrix();
4951 total_degrees_of_freedom += group_df;
4956 return within_group_covariance / double(total_degrees_of_freedom);
4962 CMatrix between_group_covariance(element_names.size());
4968 double total_samples = 0.0;
4969 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
4970 source_group != end();
4977 CMBVector deviation = overall_mean - group_mean;
4980 size_t group_size = source_group->second.
size();
4981 for (
size_t i = 0; i < element_names.size(); i++)
4983 for (
size_t j = 0; j < element_names.size(); j++)
4985 between_group_covariance[i][j] += deviation[i] * deviation[j] * group_size;
4989 total_samples += group_size;
4994 return between_group_covariance / total_samples;
5000 CMatrix total_scatter(element_names.size());
5006 double total_samples = 0.0;
5007 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5008 source_group != end();
5014 for (map<string, Elemental_Profile>::iterator sample = source_group->second.begin();
5015 sample != source_group->second.end();
5019 for (
size_t i = 0; i < element_names.size(); i++)
5021 for (
size_t j = 0; j < element_names.size(); j++)
5023 double deviation_i = overall_mean[i] - sample->second.at(element_names[i]);
5024 double deviation_j = overall_mean[j] - sample->second.at(element_names[j]);
5025 total_scatter[i][j] += deviation_i * deviation_j;
5030 total_samples += source_group->second.size();
5035 return total_scatter / total_samples;
5043 CMatrix_arma total_cov = within_group_cov + between_group_cov;
5046 double numerator = within_group_cov.det();
5047 double denominator = total_cov.det();
5050 return fabs(numerator) / fabs(denominator);
5063 double chi_squared = -(sample_size - 1.0 - correction_factor) *
log(wilks_lambda);
5066 double degrees_of_freedom = NAN;
5079 double p_value = gsl_cdf_chisq_Q(chi_squared, degrees_of_freedom);
5092 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5093 source_group != end();
5097 CMBVector group_scores = source_group->second.CalculateDotProduct(discriminant_function);
5098 projected_scores.
Append(source_group->first, group_scores);
5101 return projected_scores;
5113 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5114 source_group != end();
5118 CMBVector group_scores = source_group->second.CalculateDotProduct(discriminant_function);
5119 projected_scores.
Append(source_group->first, group_scores);
5122 return projected_scores;
5133 for (map<string, Elemental_Profile_Set>::iterator source_group = original->begin();
5134 source_group != original->end();
5141 CMBVector group_scores = source_group->second.CalculateDotProduct(discriminant_function);
5142 projected_scores.
Append(source_group->first, group_scores);
5146 return projected_scores;
5156 CMatrix_arma inv_within_cov = inv(within_group_cov);
5159 if (inv_within_cov.getnumrows() == 0)
5165 CMatrix_arma product_matrix = inv_within_cov * between_group_cov;
5168 arma::cx_vec eigenvalues;
5169 arma::cx_mat eigenvectors;
5170 eig_gen(eigenvalues, eigenvectors, product_matrix);
5173 CVector_arma real_eigenvalues = GetReal(eigenvalues);
5174 CMatrix_arma real_eigenvectors = GetReal(eigenvectors);
5177 size_t max_eigenvalue_index = real_eigenvalues.abs_max_elems();
5178 CMBVector discriminant_function = CVector_arma(real_eigenvectors.getcol(max_eigenvalue_index));
5182 discriminant_function.
SetLabels(element_names);
5184 return discriminant_function;
5190 CMatrix_arma cov_matrix1 = at(source1).CalculateCovarianceMatrix();
5191 CMatrix_arma cov_matrix2 = at(source2).CalculateCovarianceMatrix();
5194 CVector mean_vector1 = at(source1).CalculateElementMeans();
5195 CVector mean_vector2 = at(source2).CalculateElementMeans();
5196 CVector_arma mean1 = mean_vector1;
5197 CVector_arma mean2 = mean_vector2;
5200 CMatrix_arma pooled_cov = cov_matrix1 + cov_matrix2;
5201 CVector weight_vector_arma = (mean2 - mean1) / pooled_cov;
5204 CMBVector weight_vector = weight_vector_arma;
5205 weight_vector = weight_vector / weight_vector.norm2();
5210 return weight_vector;
5216 if (count(group_name) == 0)
5223 CMBVector group_mean = at(group_name).CalculateElementMeans();
5232 CMBVector weighted_mean(element_names.size());
5235 double total_samples = 0.0;
5236 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5237 source_group != end();
5244 size_t group_size = source_group->second.size();
5247 weighted_mean += double(group_size) * group_mean;
5248 total_samples += double(group_size);
5255 return weighted_mean / total_samples;
5259 const string& source1,
5260 const string& source2)
5263 vector<CMBVector> stepwise_results(3);
5266 vector<string> selected_elements;
5269 for (
size_t step = 0; step < element_names.size(); step++)
5274 rtw_->SetProgress(
double(step + 1) /
double(element_names.size()));
5278 double best_p_value = 100.0;
5279 string best_element;
5280 double best_wilks_lambda = NAN;
5281 double best_f_test_p_value = NAN;
5284 for (
size_t j = 0; j < element_names.size(); j++)
5287 if (lookup(selected_elements, element_names[j]) == -1)
5290 vector<string> candidate_elements = selected_elements;
5291 candidate_elements.push_back(element_names[j]);
5302 return stepwise_results;
5306 if (candidate_dfa.
p_values[0] < best_p_value)
5308 best_element = element_names[j];
5309 best_p_value = candidate_dfa.
p_values[0];
5317 stepwise_results[0].append(best_element, best_p_value);
5318 stepwise_results[1].append(best_element, best_wilks_lambda);
5319 stepwise_results[2].append(best_element, best_f_test_p_value);
5322 selected_elements.push_back(best_element);
5325 return stepwise_results;
5331 vector<CMBVector> stepwise_results(3);
5334 vector<string> selected_elements;
5337 for (
size_t step = 0; step < element_names.size(); step++)
5342 rtw_->SetProgress(
double(step + 1) /
double(element_names.size()));
5346 double best_p_value = 100.0;
5347 string best_element;
5348 double best_wilks_lambda = NAN;
5349 double best_f_test_p_value = NAN;
5352 for (
size_t j = 0; j < element_names.size(); j++)
5355 if (lookup(selected_elements, element_names[j]) == -1)
5358 vector<string> candidate_elements = selected_elements;
5359 candidate_elements.push_back(element_names[j]);
5368 if (p_value < best_p_value)
5370 best_element = element_names[j];
5371 best_p_value = p_value;
5372 best_wilks_lambda = candidate_dataset.
WilksLambda();
5382 stepwise_results[0].append(best_element, best_p_value);
5383 stepwise_results[1].append(best_element, best_wilks_lambda);
5384 stepwise_results[2].append(best_element, best_f_test_p_value);
5387 selected_elements.push_back(best_element);
5390 return stepwise_results;
5396 vector<CMBVector> stepwise_results(3);
5399 vector<string> selected_elements;
5402 for (
size_t step = 0; step < element_names.size(); step++)
5407 rtw_->SetProgress(
double(step + 1) /
double(element_names.size()));
5411 double best_p_value = 100.0;
5412 string best_element;
5413 double best_wilks_lambda = NAN;
5414 double best_f_test_p_value = NAN;
5417 for (
size_t j = 0; j < element_names.size(); j++)
5420 if (lookup(selected_elements, element_names[j]) == -1)
5423 vector<string> candidate_elements = selected_elements;
5424 candidate_elements.push_back(element_names[j]);
5433 if (candidate_dfa.
p_values[0] < best_p_value)
5435 best_element = element_names[j];
5436 best_p_value = candidate_dfa.
p_values[0];
5444 stepwise_results[0].append(best_element, best_p_value);
5445 stepwise_results[1].append(best_element, best_wilks_lambda);
5446 stepwise_results[2].append(best_element, best_f_test_p_value);
5449 selected_elements.push_back(best_element);
5452 return stepwise_results;
5552 cout <<
"Sample Group '" + sample_group +
"' does not exist!" << std::endl;
5557 cout <<
"Element '" + element_name +
"' does not exist!" << std::endl;
5605 if (_omsizeconstituents.size() == 0)
5607 else if (_omsizeconstituents.size() == 1)
5609 else if (_omsizeconstituents.size() == 2)
Matrix class with labeled rows and columns for Chemical Mass Balance analysis.
void SetRowLabel(int i, const string &label)
Sets row label at specified index.
void SetColumnLabel(int i, const string &label)
Sets column label at specified index.
Collection of time series with labels and observed values.
void SetLabel(unsigned int i, const string &label)
Sets custom label for time point.
void SetObservedValue(int i, const double &value)
Sets observed value for comparison at specified index.
void Append(const string &columnlabel, const CMBVectorSet &vectorset)
Adds or replaces a vector set in the collection.
Collection of named CMBVector objects for multi-variable analysis.
void Append(const string &columnlabel, const CMBVector &vectorset)
Adds or replaces a vector in the set.
double FTest_p_value() const
Computes F-test p-value for ANOVA.
Vector class with string labels for Chemical Mass Balance analysis.
void SetLabels(const vector< string > &label)
Sets all element labels at once.
void SetLabel(int i, const string &label)
Sets label at specified index.
int size() const
Gets number of elements in vector.
double valueAt(int i) const
Gets value at specified index.
Markov Chain Monte Carlo sampler for Bayesian parameter estimation.
CMBTimeSeriesSet predicted
Model predictions as time series set.
bool SetProperty(const string &varname, const string &value)
Set MCMC properties from string key-value pairs.
bool step(int k, int chain_counter)
Perform single MCMC step for one chain.
T * Model
Pointer to the model object being calibrated.
void initialize(CMBTimeSeriesSet *results, bool random=false)
Initialize MCMC chains with starting parameter values.
void SetRandomSeed(std::uint64_t seed)
Sets the master seed for the chains' random streams.
Manages a collection of concentration measurements with statistical analysis.
double CalculateSSE(double mean_value=-999) const
Calculate sum of squared errors from mean.
double CalculateMean() const
Calculate arithmetic mean.
Distribution * GetEstimatedDistribution()
Get estimated distribution (for MCMC optimization).
void SetEstimatedSigma(double value)
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.
double CalculateMeanLog() const
Calculate mean of log-transformed values.
void SetEstimatedMu(double value)
vector< unsigned int > CalculateRanks() const
Calculate ranks of values (1 = smallest).
void AppendSet(const ConcentrationSet &other)
Append all values from another set.
Distribution * GetFittedDistribution()
Get fitted distribution (from data).
void AppendValue(double value)
Append a single concentration value.
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.
Source contribution container for Chemical Mass Balance results.
Represents a parametric probability distribution for uncertainty quantification.
vector< double > parameters
Distribution parameters vector.
double EvalLog(const double &x)
Evaluate natural logarithm of probability density.
double DataMean()
Get the stored empirical mean.
distribution_type distribution
The type of probability distribution.
void SetType(const distribution_type &typ)
Set the distribution type and resize parameters vector.
double Mean(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Calculate the mean (expected value) of the distribution.
Manages a collection of elemental profiles (samples) for source fingerprinting analysis.
ConcentrationSet * GetElementDistribution(const string &element_name)
Get distribution for a specific element (mutable).
vector< string > GetSampleNames() const
Get all sample names in the set.
Elemental_Profile * AppendProfile(const string &name, const Elemental_Profile &profile=Elemental_Profile(), map< string, element_information > *elementinfo=nullptr)
Add a new sample profile to the set.
Distribution * GetEstimatedDistribution(const string &element_name)
Get estimated distribution for an element (for MCMC optimization).
void UpdateElementDistributions()
Rebuild element distributions from all profiles.
bool SetContributionSoftmax(const double &value)
Set softmax-transformed contribution.
vector< double > GetConcentrationsForSample(const string &sample_name) const
Get all element concentrations for a specific sample.
Elemental_Profile * GetProfile(const string &name)
Get profile by sample name (mutable).
bool SetContribution(const double &value)
Set contribution value for this source.
double GetContribution() const
Get contribution value.
Distribution * GetFittedDistribution(const string &element_name)
Get fitted distribution for an element (from data, for likelihood).
double GetContributionSoftmax() const
Get softmax-transformed contribution.
void SetRegressionModels(const string &om, const string &d, regression_form form=regression_form::linear, const double &p_value_threshold=0.05)
Set regression models (build new).
void AppendProfiles(const Elemental_Profile_Set &profiles, map< string, element_information > *elementinfo)
Add multiple profiles from another set.
Container for elemental concentration data of a single sediment sample.
bool AppendElement(const string &name, double val=0.0)
Add new element to profile.
double GetValue(const string &name) const
Get element concentration by name.
void SetLimit(_range lowhigh, const double &value)
Set upper or lower limit for value highlighting.
vector< string > & GetIndependentVariableNames()
void SetEffective(int i, bool eff)
ProgressReporter that discards everything reported to it.
void SetName(const std::string &nam)
void SetPredictedValue(const double &value)
void AppendValues(const double &t, const double &val)
Represents a model parameter with prior distribution and constraints.
void SetPriorDistribution(distribution_type dist_type)
Set the type of prior probability distribution.
double Value() const
Get the current parameter value.
void SetRange(const vector< double > &rng)
Set the parameter range from a vector.
string Name() const
Get the parameter name.
void SetName(const string &nam)
Set the parameter name/identifier.
Abstract sink for progress information produced by a running analysis.
virtual void SetLabel(const QString &label)=0
Sets the free-text status label.
virtual void SetProgress2(const double &prog)=0
Sets the secondary progress fraction, where one is displayed.
virtual void Start()
Makes the reporter visible or otherwise begins reporting.
virtual void SetYAxisTitle(const QString &title, int chart=0)=0
Sets the vertical axis title of a chart.
virtual void SetProgress(const double &prog)=0
Sets the primary progress fraction.
virtual void ClearGraph(int chart=0)=0
Discards the points accumulated in a chart.
virtual void SetTitle(const QString &title, int chart=0)=0
Sets the title of a chart.
A seeded, independent stream of random numbers.
double Uniform()
Uniform on [0, 1), with 53 random bits.
double StandardNormal()
Standard normal, by the Box-Muller transform.
void Set(_range lowhigh, const double &value)
void SetValue(const double value)
void SetMedian(const double &m)
void SetMean(const double &m)
double Get(_range lowhigh) const
void SetShowGraph(bool state)
void setYAxisTitle(const string &title)
void SetXAxisMode(xaxis_mode mode)
void SetYLimit(_range highlow, const double &value)
void SetName(const string &_name)
Interface * Result() const
void SetResult(Interface *_result)
void SetShowTable(bool state)
void setXAxisTitle(const string &title)
void SetYAxisMode(yaxis_mode mode)
void SetShowAsString(bool value)
void SetType(const result_type &_type)
void Append(const ResultItem &)
void SetError(const string &_error)
void AppendError(const string &_error)
void SetName(const string &_name)
Elemental_Profile * GetElementalProfile(const string &sample_name)
Finds and retrieves an elemental profile by sample name.
QString load_error_
See LoadError().
CMatrix BetweenGroupCovarianceMatrix()
Computes between-group covariance matrix.
vector< string > IsotopesToBeUsedInCMB()
Identifies isotopes to be used in CMB analysis.
profiles_data ExtractConcentrationData(const vector< vector< string > > &indicators) const
Extract concentration data for specified samples.
Parameter * GetElementDistributionSigmaParameter(size_t element_index, size_t source_index)
Retrieves pointer to the σ (std dev) parameter for an element distribution.
void AssignAllDistributions()
Assign distributions to all elements at both dataset and group levels.
vector< string > element_order_
string GetOutputPath() const
Get the output directory path.
bool InitializeParametersAndObservations(const string &targetsamplename, estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
Initialize parameters and observations for MCMC optimization.
Elemental_Profile Sample(const string &sample_name) const
Retrieves an elemental profile by sample name.
QMap< QString, double > * GetOptions()
Retrieves pointer to the options map.
size_t ParametersCount()
Returns the number of parameters.
bool PerformRegressionVsOMAndSize(const string &om, const string &particle_size, regression_form form, const double &p_value_threshold=0.05)
Performs multiple linear regression of elements vs OM and particle size.
vector< string > size_om_order_
bool InitializeContributionsRandomlySoftmax(RandomStream &stream)
Initialize source contributions randomly (softmax transformation).
bool ReadFromFile(QFile *fil)
Loads complete dataset from a JSON file.
vector< string > NegativeContributionCheck()
Checks the solved source contributions for negative values.
vector< Parameter > & Parameters()
Retrieves reference to the parameters vector.
ResultItem GetCalculatedElementMu()
Computes μ parameters from fitted log-normal distributions for source elements.
ResultItem GetObservedElementalProfile()
Retrieves the observed elemental concentrations for the selected target sample.
bool ReadElementInformationfromJsonObject(const QJsonObject &jsonobject)
Deserializes element information metadata from a JSON object.
map< string, vector< double > > ExtractElementDataByGroup(const string &element) const
Extract concentration data for a specific element from all groups.
vector< string > IsotopesWithUnusableBaseElement() const
Lists the isotopes included in the analysis whose base element cannot be used.
Elemental_Profile_Set DifferentiationPower_Percentage(bool include_target)
Computes rank-based differentiation percentage for all source pairs.
CVector GetContributionVector(bool include_all=true)
Retrieves the current source contribution fractions.
double GetElementDistributionMuValue(size_t element_index, size_t source_index)
Retrieves the current value of the μ parameter for an element distribution.
vector< string > GetElementNames() const
Get all element names in the dataset.
SourceSinkData ExtractChemicalElements(bool isotopes) const
Extract only chemical elements (and optionally isotopes).
Observation * observation(size_t i)
Retrieves pointer to an observation by index.
SourceSinkData & operator=(const SourceSinkData &other)
Assignment operator.
Elemental_Profile_Set TheRest(const string &excluded_source)
Collects all source samples except those from a specified source group.
CMBVector ANOVA(bool use_log)
Performs one-way ANOVA for all elements across source groups.
CMBVector OptimalBoxCoxParameters()
Computes optimal Box-Cox transformation parameters for all elements.
CVector PredictTarget_Isotope(parameter_mode param_mode=parameter_mode::direct)
Predicts target sample isotopic compositions based on source contributions.
void OutlierAnalysisForAll(const double &lower_threshold=-3, const double &upper_threshold=3)
Performs outlier detection on all source groups.
bool SolveLevenberg_Marquardt(transformation trans=transformation::linear)
Solves for optimal source contributions using the Levenberg-Marquardt algorithm.
CMatrix_arma ResidualJacobian_arma()
Calculates the Jacobian matrix of residuals with respect to contributions (Armadillo).
CMBVectorSet DFA_Projected()
Projects all groups onto the discriminant function axis.
CMBMatrix DFAConfusionMatrix()
Leave-one-out confusion matrix of the source samples.
ConcentrationSet * GetElementDistribution(const string &element_name)
Retrieves pointer to element distribution at dataset level.
SourceSinkData BoxCoxTransformed(bool calculate_optimal_lambda=false)
Applies Box-Cox transformation to all source groups for normalization.
CVector OneStepLevenberg_Marquardt(double lambda)
Performs one iteration of the Levenberg-Marquardt optimization algorithm.
CMatrix ResidualJacobian_softmax()
Calculates the Jacobian using softmax parameterization of contributions.
void SetParameterEstimationMode(estimation_mode est_mode)
Sets the estimation mode for parameter optimization.
CMBVector DFA_weight_vector(const string &source1, const string &source2)
Computes discriminant weight vector for two-group comparison.
Elemental_Profile_Set * GetSampleSet(const string &name)
Get a sample set (source or target group) by name.
Elemental_Profile_Set * AppendSampleSet(const string &name, const Elemental_Profile_Set &elemental_profile_set=Elemental_Profile_Set())
Add a new sample set (source or target group) to the dataset.
void Clear()
Clear all data from the object.
double regression_p_value_threshold_
CMBVector BracketTest(const string &target_sample, bool correct_based_on_om_n_size, double tolerance=0)
Performs bracket test to check if target concentrations fall within source ranges.
CMatrix WithinGroupCovarianceMatrix()
Computes pooled within-group covariance matrix.
double LogLikelihoodModelvsMeasured(estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
Calculates the log-likelihood of the model prediction versus measured data.
CVector ObservedDataforSelectedSample_Isotope_delta(const string &SelectedTargetSample="")
Retrieves the observed isotopic data in delta notation.
Elemental_Profile t_TestPValue(const string &source1, const string &source2, bool use_log)
Computes t-test p-values for element-wise differences between two sources.
vector< Observation > observations_
Distribution * GetFittedDistribution(const string &element_name)
Get the fitted distribution for a specific element at dataset level.
double WilksLambda()
Computes Wilks' Lambda statistic for multivariate group separation.
map< string, ConcentrationSet > ExtractConcentrationSet()
Extracts concentration distributions for all elements across sources.
list< string > tools_used_
bool SetParameterValue(size_t index, double value)
Sets a parameter value and updates corresponding model components.
CVector GetParameterValue() const
Retrieves all current parameter values as a vector.
vector< string > SourceGroupNames() const
Retrieves the names of all source groups (excluding target).
bool ToolsUsed(const string &tool_name)
Checks if a specific analysis tool has been used.
vector< ResultItem > GetMLRResults()
Retrieves multiple linear regression results for all sample groups.
CVector ObservedDataforSelectedSample_Isotope(const string &SelectedTargetSample="")
Retrieves the observed isotopic data for a selected target sample.
estimation_mode parameter_estimation_mode_
bool SetOutputPath(const string &output_path)
Set the output directory path.
ResultItem GetPredictedElementalProfile_Isotope(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Generates predicted isotope delta values for the target sample.
void SetOMandSizeConstituents(const string &_omconstituent, const string &_sizeconstituent)
Sets the names of OM and particle size constituents.
bool ReadElementDatafromJsonObject(const QJsonObject &jsonobject)
Deserializes elemental profile data from a JSON object.
Elemental_Profile_Set ExtractSamplesAsProfileSet(const vector< vector< string > > &indicators) const
Extract samples as an Elemental_Profile_Set.
vector< string > isotope_order_
CVector GetContributionVectorSoftmax()
Retrieves the softmax parameters for source contributions.
void IncludeExcludeElementsBasedOn(const vector< string > &elements)
Sets element inclusion based on a specified list.
ResultItem GetPredictedElementalProfile(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Generates predicted elemental concentrations for the target sample.
CVector GetPredictedValues()
Retrieves predicted values for all observations.
QJsonObject ElementInformationToJsonObject() const
Exports element information metadata to a JSON object.
ResultItem GetCalculatedElementSigma()
Computes estimated standard deviations for all source elements.
QJsonObject OptionsToJsonObject() const
Exports analysis options/settings to a JSON object.
Parameter * parameter(size_t i)
Retrieves pointer to a parameter by index.
bool ReadToolsUsedFromJsonObject(const QJsonArray &jsonarray)
Deserializes the list of analysis tools from a JSON array.
CVector Gradient(const CVector ¶meters, estimation_mode est_mode)
Computes the normalized gradient of the log-likelihood function.
void SetContributionSoftmax(size_t source_index, double softmax_value)
Sets a single softmax parameter value.
vector< string > constituent_order_
int numberofsourcesamplesets_
SourceSinkData ReplaceSourceAsTarget(const string &source_sample_name) const
Creates a new dataset with a source sample designated as the target.
vector< string > RandomlypickSamples(const double &percentage, RandomStream &stream) const
Randomly selects a subset of source samples.
double LogPriorContributions()
Calculates the log prior probability for source contributions.
CVector ResidualVector()
Calculates the combined residual vector for elemental and isotopic predictions.
SourceSinkData CreateCorrectedAndFilteredDataset(bool exclude_samples, bool exclude_elements, bool omnsizecorrect, const string &target="") const
Create a corrected and filtered copy of the dataset.
QJsonObject ElementDataToJsonObject() const
Exports all elemental profile data to a JSON object.
vector< string > NegativeValueCheck()
Checks for zero or negative concentration values across all sources.
CMBTimeSeriesSet VerifySource(const string &source_group, bool use_softmax, bool apply_om_size_correction)
Performs leave-one-out validation on a source group.
bool SetSelectedTargetSample(const string &sample_name)
Sets the currently selected target sample for analysis.
map< string, element_information > * GetElementInformation()
Retrieves pointer to the element information map.
void AddtoToolsUsed(const string &tool)
Adds a tool name to the list of tools used in analysis.
QMap< QString, double > options_
DFA_result DiscriminantFunctionAnalysis()
Performs discriminant function analysis for all source groups.
vector< string > ElementsToBeUsedInCMB()
Identifies chemical elements to be used in CMB analysis.
map< string, ConcentrationSet > element_distributions_
vector< string > SizeOMOrder()
Retrieves the ordering of size and OM constituents.
void PopulateConstituentOrders()
Populates all element ordering vectors used throughout CMB analysis.
vector< ResultItem > GetSourceProfiles()
Retrieves elemental profiles for all source groups.
CMatrix BuildSourceMeanMatrix_Isotopes(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Builds the source mean concentration matrix for isotopes.
map< string, element_information > element_information_
void PopulateElementInformation(const map< string, element_information > *ElementInfo=nullptr)
Populate element information metadata.
Results MCMC(const string &target_sample, map< string, string > arguments, CMCMC< SourceSinkData > *mcmc, ProgressReporter *progress_window, const string &working_folder)
Performs Markov Chain Monte Carlo analysis for Bayesian source apportionment.
CMBMatrix MCMC_Batch(const map< string, string > &arguments, CMCMC< SourceSinkData > *mcmc, ProgressReporter *progress_window, const string &working_folder, vector< string > *failed_writes=nullptr)
Performs batch MCMC analysis on all target samples.
ResultItem GetCalculatedElementMeans()
Computes estimated mean concentrations for all source elements.
CMBTimeSeriesSet BootStrap(const double &percentage, unsigned int num_iterations, const string &target_sample, bool use_softmax, std::uint64_t seed=DefaultRandomSeed)
Performs bootstrap uncertainty analysis on source contributions.
Elemental_Profile_Set DifferentiationPower(bool use_log, bool include_target)
Computes differentiation power for all source pairs.
string GetParameterName(int index) const
Get the name of a parameter by its index.
double LogLikelihoodSourceElementalDistributions()
Calculates the log-likelihood of source elemental distributions.
vector< string > samplesetsorder_
double LogLikelihood(estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
Calculates the total log-likelihood for Bayesian source apportionment.
QString Role(const element_information::role &role) const
Converts element role enum to string representation.
SourceSinkData CreateTracerDataset(bool exclude_samples, bool exclude_elements, bool omnsizecorrect, const string &target="") const
As CreateCorrectedAndFilteredDataset, keeping only the tracers.
size_t ObservationsCount()
Returns the number of observations.
double IsotopeBaseMean(Elemental_Profile_Set *source_group, const string &base_element, parameter_mode param_mode)
Mean content of an isotope's base element in one source group.
CVector GradientUpdate(estimation_mode estmode=estimation_mode::elemental_profile_and_contribution)
Performs one gradient ascent step with adaptive step size.
SourceSinkData CreateCorrectedDataset(const string &target, bool omnsizecorrect, map< string, element_information > *elementinfo)
Create a corrected copy of the dataset for a specific target sample.
vector< CMBVector > StepwiseDiscriminantFunctionAnalysis()
Performs stepwise discriminant analysis across all source groups.
vector< string > GetSampleNames(const string &group_name) const
Get all sample names within a specific group.
CMBVector MeanElementalContent()
Computes weighted mean elemental concentrations across all sources.
CMatrix TotalScatterMatrix()
Computes total scatter matrix.
ResultItem GetEstimatedElementSigma()
Retrieves estimated σ parameters from Bayesian inference for source elements.
double GrandMean(const string &element, bool use_log)
Computes grand mean concentration for an element across all sources.
void IncludeExcludeAllElements(bool include_in_analysis)
Sets inclusion flag for all elements.
string FirstOMConstituent()
Retrieves the name of the first organic matter constituent.
CVector OneStepLevenberg_Marquardt_softmax(double lambda)
Performs one iteration of Levenberg-Marquardt using softmax parameterization.
CVector PredictTarget(parameter_mode param_mode=parameter_mode::direct)
Predicts target sample elemental concentrations based on source contributions.
vector< string > ElementOrder()
Retrieves the ordering of chemical elements.
vector< string > GetGroupNames() const
Get all group names in the dataset.
string SelectedTargetSample() const
Retrieves the name of the currently selected target sample.
ResultItem GetObservedvsModeledElementalProfile(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Creates a comparison of observed vs modeled elemental profiles.
vector< string > IsotopeOrder()
Retrieves the ordering of isotopes.
int CountElements(bool exclude_elements) const
Count the number of elements in the dataset.
bool InitializeContributionsRandomly(RandomStream &stream)
Initialize source contributions randomly (linear constraint).
SourceSinkData ExtractSpecificElements(const vector< string > &element_list) const
Extract specific elements from source groups.
int TotalNumberofSourceSamples() const
Counts the total number of source samples across all source groups.
Parameter * GetElementDistributionMuParameter(size_t element_index, size_t source_index)
Retrieves pointer to the μ (mean) parameter for an element distribution.
estimation_mode ParameterEstimationMode()
Retrieves the current estimation mode.
int numberofconstituents_
element_data ExtractElementConcentrations(const string &element, const string &group) const
Extract concentration data for a specific element from a group.
double DFA_P_Value()
Computes p-value for discriminant function analysis.
ResultItem GetEstimatedElementMean()
Computes actual mean concentrations from estimated log-normal parameters.
string GetTargetGroup() const
Retrieves the name of the target group.
void PopulateElementDistributions()
Populate element distributions from all groups.
Elemental_Profile_Set DifferentiationPower_P_value(bool include_target)
Computes t-test p-values for all source pairs.
CVector PredictTarget_Isotope_delta(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Predicts target sample isotopic compositions in delta notation.
ResultItem GetContribution()
Packages source contributions into a ResultItem for output.
CVector_arma ResidualVector_arma()
Calculates the combined residual vector using Armadillo vector format.
vector< string > AllSourceSampleNames() const
Retrieves names of all samples across all source groups.
string FirstSizeConstituent()
Retrieves the name of the first particle size constituent.
bool ReadOptionsfromJsonObject(const QJsonObject &jsonobject)
Deserializes analysis options from a JSON object.
string selected_target_sample_
double GetObjectiveFunctionValue()
Returns the objective function value for optimization algorithms.
CMBVector DFATransformed(const CMBVector &eigenvector, const string &source_group)
Projects samples onto a discriminant function axis.
CMBTimeSeriesSet LM_Batch(transformation transform, bool apply_om_size_correction, map< string, vector< string > > &negative_elements)
Solves CMB model for all target samples using Levenberg-Marquardt.
vector< Parameter > parameters_
SourceSinkData RandomlyEliminateSourceSamples(const double &percentage, RandomStream &stream)
Creates dataset with randomly excluded source samples for validation.
bool SetTargetGroup(const string &targroup)
Sets the target/sink group designation.
vector< string > GetSourceOrder() const
Retrieves the ordering of source groups.
vector< string > ConstituentOrder()
Retrieves the ordering of all constituents.
CVector ObservedDataforSelectedSample(const string &SelectedTargetSample="")
Retrieves the observed elemental data for a selected target sample.
ResultItem GetObservedElementalProfile_Isotope()
Retrieves the observed isotope delta values for the selected target sample.
CMatrix ResidualJacobian()
Calculates the Jacobian matrix of residuals with respect to contributions.
CMatrix BuildSourceMeanMatrix(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Builds the source mean concentration matrix for chemical elements.
CVector GetSourceContributions()
Retrieves the contributions from all sources.
double GetElementDistributionSigmaValue(size_t element_index, size_t source_index)
Retrieves the current value of the σ parameter for an element distribution.
QJsonArray ToolsUsedToJsonObject() const
Exports the list of analysis tools used to a JSON array.
double error_stdev_isotope_
Elemental_Profile_Set LumpAllProfileSets()
Combines all source samples into a single profile set.
double LogLikelihoodModelvsMeasured_Isotope(estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
Calculates the log-likelihood of model versus measured isotopic data.
bool WriteDataToFile(QFile *file)
Writes elemental profile data to a text file.
bool WriteToFile(QFile *file)
Writes dataset to a text file.
vector< string > SamplesetsOrder()
Retrieves the ordering of sample sets.
void SetContribution(size_t source_index, double contribution_value)
Sets a single source contribution value.
ResultItem GetEstimatedElementMu()
Retrieves estimated μ parameters from Bayesian inference for source elements.
CMBVector DFA_eigvector()
Computes the primary discriminant function eigenvector.
ResultItem GetObservedvsModeledElementalProfile_Isotope(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Creates a comparison of observed vs modeled isotope delta values.
vector< string > OMandSizeConstituents()
Retrieves the names of OM and particle size constituents.
SourceSinkData()
Default constructor.
void SetProgressReporter(ProgressReporter *_rtw)
Sets the progress window for displaying optimization progress.
parameter_mode
Specifies whether to use direct data statistics or fitted distribution parameters.
@ based_on_fitted_distribution
Calculate from fitted distribution parameters.
@ direct
Use empirical statistics from data.
@ dirichlet
Dirichlet distribution (treated as uniform on simplex in current implementation).
@ lognormal
Lognormal distribution: ln(x) ~ N(μ, σ²), for strictly positive variables.
@ normal
Normal (Gaussian) distribution: p(x) = N(μ, σ²).
Convergence diagnostics for MCMC chains: split R-hat and the effective sample size.
Diagnostics Diagnose(const std::vector< std::vector< double > > &chains)
Split R-hat and effective sample size of one quantity.
The one place where data values entering SedSAT3 are checked.
@ low
Lower bound of the parameter range.
@ high
Upper bound of the parameter range.
bool ParseRandomSeed(const std::string &text, std::uint64_t &seed)
Parses a user-entered seed.
constexpr std::uint64_t DefaultRandomSeed
The stream for code outside the MCMC that needs random numbers.
@ distribution_with_observed
@ predicted_concentration
static QString SafeFileName(const QString &name)
@ elemental_profile_and_contribution
@ source_elemental_profiles_based_on_source_data
CMBVectorSet eigen_vectors
CMBVectorSetSet multi_projected
vector< string > sample_names
double effective_sample_size
multi-chain ESS
vector< vector< double > > values
vector< string > element_names
vector< string > sample_names