7#include <gsl/gsl_statistics_double.h>
42 map<string, Elemental_Profile>::operator=(other);
58 bool exclude_elements,
60 const vector<double>& om_size,
61 const map<string, element_information>* elementinfo)
const
65 for (
const auto& [sample_name, profile] : *
this)
68 if (exclude_samples && !profile.IsIncludedInAnalysis()) {
76 profile.CreateCorrectedProfile(exclude_elements, omnsizecorrect, om_size, &
mlr_vs_om_size_, elementinfo)
82 profile.CreateCorrectedProfile(exclude_elements,
false, om_size,
nullptr, elementinfo)
92 const map<string, element_information>* elementinfo,
97 for (
const auto& [sample_name, profile] : *
this)
99 out.
AppendProfile(sample_name, profile.ExtractChemicalElements(elementinfo, isotopes));
106 const vector<string>& element_list)
const
110 for (
const auto& [sample_name, profile] : *
this)
112 out.
AppendProfile(sample_name, profile.ExtractElements(element_list));
119 bool applyomsizecorrection,
120 const vector<double>& om_size,
121 map<string, element_information>* elementinfo)
125 if (applyomsizecorrection)
131 for (
auto& [sample_name, profile] : *
this)
134 if (profile.IsIncludedInAnalysis() && !sample_name.empty())
146 const vector<string>& samples_to_eliminate,
147 map<string, element_information>* elementinfo)
const
151 for (
const auto& [sample_name, profile] : *
this)
154 if (profile.IsIncludedInAnalysis() && lookup(samples_to_eliminate, sample_name) == -1)
171 for (
auto& [sample_name, profile] : *
this)
174 for (
const auto& [element_name, concentration] : profile)
186 map<string, element_information>* elementinfo)
191 std::cerr <<
"Profile '" +
name +
"' already exists!" << std::endl;
200 for (
const auto& [element_name, concentration] :
operator[](
name))
205 return &operator[](
name);
210 map<string, element_information>* elementinfo)
213 for (
const auto& [sample_name, profile] : profiles)
224 vector<string> sample_names;
225 sample_names.reserve(size());
227 for (
const auto& [sample_name, profile] : *
this)
229 sample_names.push_back(sample_name);
247 out +=
"Element name\t";
248 for (
const auto& [sample_name, profile] : *
this)
250 out += sample_name +
"\t";
255 for (
const string& element : element_names)
258 for (
const auto& [sample_name, profile] : *
this)
260 out +=
"\t" + aquiutils::numbertostring(profile.at(element));
274 file->write(QString::fromStdString(
ToString()).toUtf8());
280 QJsonObject json_object;
286 for (
auto& [sample_name, profile] : *
this)
289 if (!sample_name.empty())
291 json_object[QString::fromStdString(sample_name)] = profile.toJsonObject();
308 for (
const QString& key : jsonobject.keys())
317 QString profile_error;
320 error = QStringLiteral(
"sample '%1', %2").arg(key, profile_error);
344 for (
const auto& [sample_name, profile] : *
this)
346 if (!profile.Contains(element_name)) {
357 return vector<string>();
361 vector<string> element_names;
363 element_names.reserve(first_profile.size());
365 for (
const auto& [element_name, concentration] : first_profile)
367 element_names.push_back(element_name);
370 return element_names;
375 if (count(
name) == 0)
377 std::cerr <<
"Sample '" +
name +
"' does not exist!" << std::endl;
381 return &operator[](
name);
386 if (index >= size()) {
392 std::advance(it, index);
399 if (count(
name) == 0)
401 std::cerr <<
"Sample '" +
name +
"' does not exist!" << std::endl;
410 if (index >= size()) {
416 std::advance(it, index);
425 vector<double> concentrations;
428 if (empty() || begin()->second.count(element_name) == 0) {
429 return concentrations;
432 concentrations.reserve(size());
434 for (
const auto& [sample_name, profile] : *
this)
436 concentrations.push_back(profile.at(element_name));
439 return concentrations;
445 if (count(sample_name) == 0) {
446 return vector<double>();
450 return at(sample_name).GetAllValues();
459 double maximum = -std::numeric_limits<double>::max();
461 for (
const auto& [sample_name, profile] : *
this)
463 double profile_max = profile.GetMaximum();
464 if (profile_max > maximum) {
465 maximum = profile_max;
478 double minimum = std::numeric_limits<double>::max();
480 for (
const auto& [sample_name, profile] : *
this)
482 double profile_min = profile.GetMinimum();
483 if (profile_min < minimum) {
484 minimum = profile_min;
496 const double& p_value_threshold)
501 for (
const string& element : element_names)
504 models[element].SetDependentVariableName(element);
511 const string& element,
515 const double& p_value_threshold)
523 vector<vector<double>> independents;
524 vector<string> independent_var_names;
528 independent_var_names.push_back(om);
533 independent_var_names.push_back(d);
540 model.
Regress(independents, dependent, independent_var_names);
549 const double& p_value_threshold)
579 CMBMatrix covariance_matrix(element_names.size());
585 for (
size_t i = 0; i < element_names.size(); i++)
588 covariance_matrix.
SetRowLabel(i, element_names[i]);
592 for (
size_t i = 0; i < data_matrix->size2; i++)
594 for (
size_t j = i; j < data_matrix->size2; j++)
596 gsl_vector_view col_i = gsl_matrix_column(data_matrix, i);
597 gsl_vector_view col_j = gsl_matrix_column(data_matrix, j);
600 double cov = gsl_stats_covariance(
601 col_i.vector.data, col_i.vector.stride,
602 col_j.vector.data, col_j.vector.stride,
607 double adjusted_cov = cov * (col_i.vector.size - 1) / col_i.vector.size;
610 covariance_matrix[i][j] = adjusted_cov;
611 covariance_matrix[j][i] = adjusted_cov;
615 gsl_matrix_free(data_matrix);
616 return covariance_matrix;
622 CMBMatrix correlation_matrix(element_names.size());
628 for (
size_t i = 0; i < element_names.size(); i++)
631 correlation_matrix.
SetRowLabel(i, element_names[i]);
635 for (
size_t i = 0; i < data_matrix->size2; i++)
637 for (
size_t j = i; j < data_matrix->size2; j++)
639 gsl_vector_view col_i = gsl_matrix_column(data_matrix, i);
640 gsl_vector_view col_j = gsl_matrix_column(data_matrix, j);
642 double corr = gsl_stats_correlation(
643 col_i.vector.data, col_i.vector.stride,
644 col_j.vector.data, col_j.vector.stride,
649 correlation_matrix[i][j] = corr;
650 correlation_matrix[j][i] = corr;
654 gsl_matrix_free(data_matrix);
655 return correlation_matrix;
663 gsl_matrix*
matrix = gsl_matrix_alloc(size(), element_names.size());
667 for (
const auto& [sample_name, profile] : *
this)
670 for (
const auto& [element_name, concentration] : profile)
672 gsl_matrix_set(
matrix, row, col, concentration);
686 CMBVector ks_statistics(element_names.size());
689 for (
size_t i = 0; i < element_names.size(); i++)
692 CalculateKolmogorovSmirnovStatistic(dist_type);
695 return ks_statistics;
699 const vector<string>& element_order)
const
702 vector<string> element_names = element_order.empty() ?
705 CVector means(element_names.size());
707 for (
size_t i = 0; i < element_names.size(); i++)
719 QTableWidget* table =
new QTableWidget();
720 table->setEditTriggers(QAbstractItemView::NoEditTriggers);
725 table->setRowCount(element_names.size());
726 table->setColumnCount(size());
729 QStringList row_headers;
730 for (
const string& element : element_names)
732 row_headers << QString::fromStdString(element);
734 table->setVerticalHeaderLabels(row_headers);
737 QStringList column_headers;
740 for (
const auto& [sample_name, profile] : *
this)
743 column_headers << QString::fromStdString(sample_name);
746 for (
size_t row = 0; row < element_names.size(); row++)
748 double concentration = profile.GetValue(element_names[row]);
749 table->setItem(row, col,
new QTableWidgetItem(QString::number(concentration)));
756 table->item(row, col)->setForeground(QColor(Qt::red));
764 table->setHorizontalHeaderLabels(column_headers);
771 const vector<double>& om_size,
772 map<string, element_information>* elementinfo)
776 for (
auto& [sample_name, profile] : *
this)
779 if (profile.IsIncludedInAnalysis() && !sample_name.empty())
784 corrected_set.
AppendProfile(sample_name, corrected_profile, elementinfo);
788 return corrected_set;
794 vector<string> elements;
798 elements.push_back(element_name);
810 lambda_values[i] =
distribution.FindOptimalBoxCoxParameter(-5.0, 5.0, 10);
811 lambda_values.
SetLabel(i, element_name);
815 return lambda_values;
820 const double& lowerlimit,
821 const double& upperlimit)
827 CMBMatrix outlier_magnitude(begin()->second.size(), size());
830 vector<double> means;
832 vector<bool> transformable;
843 transformable.push_back(
distribution.CanBoxCoxTransform());
848 size_t sample_idx = 0;
849 for (
auto& [sample_name, profile] : *
this)
851 profile.ClearNotes();
852 outlier_magnitude.
SetRowLabel(sample_idx, sample_name);
854 size_t element_idx = 0;
855 for (
const auto& [element_name, concentration] : profile)
863 double lambda = lambdas[element_idx];
864 double transformed_value = transformable[element_idx] ?
868 double z_score = (transformed_value - means[element_idx]) / stds[element_idx];
869 outlier_magnitude[sample_idx][element_idx] = z_score;
872 if (upperlimit != lowerlimit)
874 if (z_score > upperlimit || z_score < lowerlimit)
876 profile.AppendtoNotes(element_name +
" was detected as outlier");
887 return outlier_magnitude;
895 CMBVector lambdas = (lambda_vals ==
nullptr) ?
910 size_t sample_idx = 0;
911 for (
auto& [sample_name, profile] : transformed)
913 profile[element_name] = transformed_values[sample_idx];
932 for (
const auto& [sample_name, profile] : *
this)
934 matrix.SetRowLabel(row, sample_name);
937 for (
const auto& [element_name, concentration] : profile)
939 matrix[row][col] = concentration;
940 matrix.SetColumnLabel(col, element_name);
953 const vector<string>& element_names)
const
955 vector<string> elements_with_negative_values;
957 for (
const string& element : element_names)
961 elements_with_negative_values.push_back(element);
965 return elements_with_negative_values;
974 for (
const auto& [sample_name, profile] : *
this)
977 CMBVector sorted = profile.SortByConcentration();
979 for (
int i = 0; i < n && i < sorted.num; i++)
981 string element_name = sorted.
Label(i);
982 double concentration = sorted[i];
985 if (aggregated.count(element_name) == 0)
991 aggregated[element_name] = std::min(concentration, aggregated[element_name]);
1005 for (
const auto& [sample_name, profile] : *
this)
1007 dot_products[i] = profile.CalculateDotProduct(v);
1008 dot_products.
SetLabel(i, sample_name);
1012 return dot_products;
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.
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.
string Label(int i) const
Gets label at specified index.
Manages a collection of concentration measurements with statistical analysis.
double CalculateMean() const
Calculate arithmetic mean.
static double BoxCoxTransformValue(double x, double lambda)
Box-Cox transform of a single positive value.
ConcentrationSet ApplyBoxCoxTransform(double lambda, bool normalize) const
Apply Box-Cox transformation.
double CalculateStdDev(double mean_value=-999) const
Calculate standard deviation.
Represents a parametric probability distribution for uncertainty quantification.
gsl_matrix * CopyToGSLMatrix() const
Convert to GSL matrix for statistical functions.
CMBMatrix ToMatrix() const
Convert to matrix format (samples × elements).
ConcentrationSet * GetElementDistribution(const string &element_name)
Get distribution for a specific element (mutable).
bool writetofile(QFile *file) override
Write object data to a file.
Elemental_Profile_Set CreateCorrectedSet(bool exclude_samples, bool exclude_elements, bool omnsizecorrect, const vector< double > &om_size, const map< string, element_information > *elementinfo=nullptr) const
Create corrected and filtered subset.
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).
CMBVector CalculateKolmogorovSmirnovStatistics(distribution_type dist_type)
Calculate Kolmogorov-Smirnov statistics for all elements.
vector< double > GetAllConcentrationsFor(const string &element_name)
Get all concentration values for a specific element across samples.
ResultItem GetRegressionsAsResult()
Get regressions wrapped in ResultItem for display.
Elemental_Profile SelectTopElementsAggregate(int n) const
Select top N elements across all samples (aggregate minimum).
void UpdateElementDistributions()
Rebuild element distributions from all profiles.
Elemental_Profile_Set & operator=(const Elemental_Profile_Set &other)
vector< string > GetElementNames() const
Get all element names (from first profile).
bool SetContributionSoftmax(const double &value)
Set softmax-transformed contribution.
MultipleLinearRegressionSet * GetRegressionModels()
Get internal regression model set.
double GetMinimum() const
Get minimum concentration across all elements and samples.
vector< double > GetConcentrationsForSample(const string &sample_name) const
Get all element concentrations for a specific sample.
CMBVector CalculateDotProduct(const CVector &v) const
Calculate dot product of each profile with weight vector.
Elemental_Profile * GetProfile(const string &name)
Get profile by sample name (mutable).
bool ReadFromJsonObject(const QJsonObject &jsonobject) override
Deserialize object from JSON format.
bool Read(const QStringList &strlist) override
Parse object data from a string list.
MultipleLinearRegression BuildRegressionModel(const string &element, const string &om, const string &d, regression_form form=regression_form::linear, const double &p_value_threshold=0.05)
Build MLR model for single element vs OM and particle size.
CMBMatrix CalculateCovarianceMatrix()
Calculate covariance matrix across elements.
bool SetContribution(const double &value)
Set contribution value for this source.
double GetMaximum() const
Get maximum concentration across all elements and samples.
Elemental_Profile_Set ExtractElements(const vector< string > &element_list) const
Create subset with only specified elements.
Elemental_Profile_Set CopyIncludedInAnalysis(bool applyomsizecorrection, const vector< double > &om_size, map< string, element_information > *elementinfo=nullptr)
Copy only samples marked for inclusion in analysis.
bool ContainsElement(const string &element_name) const
Check if an element exists in ALL profiles.
MultipleLinearRegressionSet mlr_vs_om_size_
MLR models for OM/size corrections.
QJsonObject toJsonObject() const override
Serialize object to JSON format.
string ToString() const override
Convert object to string representation.
CMBVector CalculateBoxCoxParameters()
Calculate optimal Box-Cox lambda for each element.
double contribution_softmax_
Softmax-transformed contribution.
QTableWidget * ToTable() override
Create a Qt table widget representation of the data.
vector< string > ElementsNotBoxCoxTransformable() const
Elements with a zero or negative value, which Box-Cox leaves untransformed.
CVector CalculateElementMeans(const vector< string > &element_order=vector< string >()) const
Calculate mean concentration for each element.
Distribution * GetFittedDistribution(const string &element_name)
Get fitted distribution for an element (from data, for likelihood).
Elemental_Profile_Set ApplyOrganicMatterAndSizeCorrections(const vector< double > &om_size, map< string, element_information > *elementinfo=nullptr)
Apply OM and particle size corrections to all profiles.
CMBMatrix CalculateCorrelationMatrix()
Calculate correlation matrix across elements.
map< string, ConcentrationSet > element_distributions_
Concentration distributions for each element.
CMBMatrix DetectOutliers(const double &lowerlimit=0, const double &upperlimit=0)
Detect outliers using Box-Cox transformation and standardization.
Elemental_Profile_Set EliminateSamples(const vector< string > &samples_to_eliminate, map< string, element_information > *elementinfo) const
Create subset excluding specified samples.
MultipleLinearRegressionSet BuildRegressionModels(const string &om, const string &d, regression_form form=regression_form::linear, const double &p_value_threshold=0.05)
Build MLR models for all elements vs OM and particle size.
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).
bool outlierdone_
Flag indicating outlier analysis performed.
double contribution_
Source contribution (for CMB).
Elemental_Profile_Set ApplyBoxCoxTransform(CMBVector *lambda_vals=nullptr)
Apply Box-Cox transformation to all profiles.
vector< string > CheckForNegativeValues(const vector< string > &element_names) const
Check for elements with negative values.
void AppendProfiles(const Elemental_Profile_Set &profiles, map< string, element_information > *elementinfo)
Add multiple profiles from another set.
Elemental_Profile_Set ExtractChemicalElements(const map< string, element_information > *elementinfo, bool isotopes) const
Create subset with only chemical elements (and optionally isotopes).
Container for elemental concentration data of a single sediment sample.
Elemental_Profile ApplyOrganicMatterAndSizeCorrections(const vector< double > &reference_om_size, const MultipleLinearRegressionSet *regression_models, const map< string, element_information > *elementinfo=nullptr) const
Apply organic matter and particle size corrections.
Elemental_Profile CreateAnalysisProfile(const map< string, element_information > *elementinfo=nullptr, bool keep_isotope_bases=false) const
Create profile with only analyzed elements.
bool AppendElement(const string &name, double val=0.0)
Add new element to profile.
bool ReadFromJsonObject(const QJsonObject &json) override
Deserialize from JSON object.
double lowlimit
Lower threshold for value highlighting (when enabled).
Interface()
Default constructor.
Interface & operator=(const Interface &intf)
Assignment operator.
bool highlightoutsideoflimit
Flag indicating whether to highlight values outside defined limits.
double highlimit
Upper threshold for value highlighting (when enabled).
void SetDependentVariableName(const string &name)
double Regress(const vector< vector< double > > &independent, const vector< double > &dependent, const vector< string > &indep_vars_names)
void SetPValueThreshold(const double &p)
void SetEquation(regression_form form)
void SetResult(Interface *_result)
void SetType(const result_type &_type)
distribution_type
Enumeration of probability distribution types supported in SedSat3.
The one place where data values entering SedSAT3 are checked.