SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
elemental_profile_set.cpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
5#include "numericparsing.h"
6#include <iostream>
7#include <gsl/gsl_statistics_double.h>
8#include <QFile>
9
10// ========== Construction and Assignment ==========
11
22
33
35{
36 // Check for self-assignment
37 if (this == &other) {
38 return *this;
39 }
40
41 // Copy base classes
42 map<string, Elemental_Profile>::operator=(other);
44
45 // Copy member variables
51
52 return *this;
53}
54// ========== Data Extraction and Filtering ==========
55
57 bool exclude_samples,
58 bool exclude_elements,
59 bool omnsizecorrect,
60 const vector<double>& om_size,
61 const map<string, element_information>* elementinfo) const
62{
64
65 for (const auto& [sample_name, profile] : *this)
66 {
67 // Skip excluded samples if requested
68 if (exclude_samples && !profile.IsIncludedInAnalysis()) {
69 continue;
70 }
71
72 // Apply corrections based on whether MLR models exist
73 if (!mlr_vs_om_size_.empty()) {
74 out.AppendProfile(
75 sample_name,
76 profile.CreateCorrectedProfile(exclude_elements, omnsizecorrect, om_size, &mlr_vs_om_size_, elementinfo)
77 );
78 }
79 else {
80 out.AppendProfile(
81 sample_name,
82 profile.CreateCorrectedProfile(exclude_elements, false, om_size, nullptr, elementinfo)
83 );
84 }
85 }
86
88 return out;
89}
90
92 const map<string, element_information>* elementinfo,
93 bool isotopes) const
94{
96
97 for (const auto& [sample_name, profile] : *this)
98 {
99 out.AppendProfile(sample_name, profile.ExtractChemicalElements(elementinfo, isotopes));
100 }
101
102 return out;
103}
104
106 const vector<string>& element_list) const
107{
109
110 for (const auto& [sample_name, profile] : *this)
111 {
112 out.AppendProfile(sample_name, profile.ExtractElements(element_list));
113 }
114
115 return out;
116}
117
119 bool applyomsizecorrection,
120 const vector<double>& om_size,
121 map<string, element_information>* elementinfo)
122{
124
125 if (applyomsizecorrection)
126 {
127 out = ApplyOrganicMatterAndSizeCorrections(om_size, elementinfo);
128 }
129 else
130 {
131 for (auto& [sample_name, profile] : *this)
132 {
133 // Include only samples marked for analysis with non-empty names
134 if (profile.IsIncludedInAnalysis() && !sample_name.empty())
135 {
136 out.AppendProfile(sample_name, profile, elementinfo);
137 }
138 }
139 }
140
142 return out;
143}
144
146 const vector<string>& samples_to_eliminate,
147 map<string, element_information>* elementinfo) const
148{
150
151 for (const auto& [sample_name, profile] : *this)
152 {
153 // Include sample if it's marked for analysis AND not in elimination list
154 if (profile.IsIncludedInAnalysis() && lookup(samples_to_eliminate, sample_name) == -1)
155 {
156 out.AppendProfile(sample_name, profile, elementinfo);
157 }
158 }
159
161 return out;
162}
163
164// ========== Data Management ==========
165
167{
169
170 // Iterate through each sample profile
171 for (auto& [sample_name, profile] : *this)
172 {
173 // Iterate through each element in the profile
174 for (const auto& [element_name, concentration] : profile)
175 {
176 element_distributions_[element_name].AppendValue(concentration);
177 }
178 }
179}
180
181// ========== Data Management ==========
182
184 const string& name,
185 const Elemental_Profile& profile,
186 map<string, element_information>* elementinfo)
187{
188 // Check if profile with this name already exists
189 if (count(name) > 0)
190 {
191 std::cerr << "Profile '" + name + "' already exists!" << std::endl;
192 return nullptr;
193 }
194
195 // Add the profile (filtered by elementinfo if provided, keeping the base
196 // elements of the included isotopes, which fingerprinting needs)
197 operator[](name) = profile.CreateAnalysisProfile(elementinfo, true);
198
199 // Update element distributions: one value per constituent kept above
200 for (const auto& [element_name, concentration] : operator[](name))
201 {
202 element_distributions_[element_name].AppendValue(concentration);
203 }
204
205 return &operator[](name);
206}
207
209 const Elemental_Profile_Set& profiles,
210 map<string, element_information>* elementinfo)
211{
212 // Add each profile from the source set
213 for (const auto& [sample_name, profile] : profiles)
214 {
215 AppendProfile(sample_name, profile, elementinfo);
216 }
217
218 // Rebuild distributions after adding all profiles
220}
221
223{
224 vector<string> sample_names;
225 sample_names.reserve(size()); // Pre-allocate for efficiency
226
227 for (const auto& [sample_name, profile] : *this)
228 {
229 sample_names.push_back(sample_name);
230 }
231
232 return sample_names;
233}
234
235// ========== Serialization ==========
236
238{
239 if (empty()) {
240 return string();
241 }
242
243 string out;
244 vector<string> element_names = GetElementNames();
245
246 // Header row: "Element name" followed by sample names
247 out += "Element name\t";
248 for (const auto& [sample_name, profile] : *this)
249 {
250 out += sample_name + "\t";
251 }
252 out += "\n";
253
254 // Data rows: element name followed by concentrations for each sample
255 for (const string& element : element_names)
256 {
257 out += element;
258 for (const auto& [sample_name, profile] : *this)
259 {
260 out += "\t" + aquiutils::numbertostring(profile.at(element));
261 }
262 out += "\n";
263 }
264
265 return out;
266}
267
269{
270 if (!file) {
271 return false;
272 }
273
274 file->write(QString::fromStdString(ToString()).toUtf8());
275 return true; // Fixed: was returning 0 (false)
276}
277
279{
280 QJsonObject json_object;
281
282 if (empty()) {
283 return json_object;
284 }
285
286 for (auto& [sample_name, profile] : *this)
287 {
288 // Only include samples with non-empty names
289 if (!sample_name.empty())
290 {
291 json_object[QString::fromStdString(sample_name)] = profile.toJsonObject();
292 }
293 }
294
295 return json_object;
296}
297
298bool Elemental_Profile_Set::ReadFromJsonObject(const QJsonObject& jsonobject)
299{
300 QString error;
301 return ReadFromJsonObject(jsonobject, error);
302}
303
304bool Elemental_Profile_Set::ReadFromJsonObject(const QJsonObject& jsonobject, QString& error)
305{
306 clear();
307
308 for (const QString& key : jsonobject.keys())
309 {
310 if (key.isEmpty()) {
311 continue;
312 }
313
314 // A profile with a refused value stops the load; it used to be
315 // dropped without a word
316 Elemental_Profile elemental_profile;
317 QString profile_error;
318 if (!elemental_profile.ReadFromJsonObject(jsonobject[key].toObject(), profile_error))
319 {
320 error = QStringLiteral("sample '%1', %2").arg(key, profile_error);
321 return false;
322 }
323 AppendProfile(key.toStdString(), elemental_profile);
324 }
325
326 return true;
327}
328bool Elemental_Profile_Set::Read(const QStringList &/*strlist*/)
329{
330
331
332 return true;
333}
334
335// ========== Data Access ==========
336
337bool Elemental_Profile_Set::ContainsElement(const string& element_name) const
338{
339 if (empty()) {
340 return false;
341 }
342
343 // Element must exist in all profiles
344 for (const auto& [sample_name, profile] : *this)
345 {
346 if (!profile.Contains(element_name)) {
347 return false;
348 }
349 }
350
351 return true;
352}
353
355{
356 if (empty()) {
357 return vector<string>();
358 }
359
360 // Get element names from the first profile
361 vector<string> element_names;
362 const Elemental_Profile& first_profile = begin()->second;
363 element_names.reserve(first_profile.size());
364
365 for (const auto& [element_name, concentration] : first_profile)
366 {
367 element_names.push_back(element_name);
368 }
369
370 return element_names;
371}
372
374{
375 if (count(name) == 0)
376 {
377 std::cerr << "Sample '" + name + "' does not exist!" << std::endl;
378 return nullptr;
379 }
380
381 return &operator[](name);
382}
383
385{
386 if (index >= size()) {
387 return nullptr;
388 }
389
390 // Advance iterator to the requested index
391 auto it = begin();
392 std::advance(it, index);
393
394 return &it->second;
395}
396
398{
399 if (count(name) == 0)
400 {
401 std::cerr << "Sample '" + name + "' does not exist!" << std::endl;
402 return Elemental_Profile();
403 }
404
405 return at(name);
406}
407
409{
410 if (index >= size()) {
411 return Elemental_Profile();
412 }
413
414 // Advance iterator to the requested index
415 auto it = begin();
416 std::advance(it, index);
417
418 return it->second;
419}
420
421// ========== Data Access (continued) ==========
422
423vector<double> Elemental_Profile_Set::GetAllConcentrationsFor(const string& element_name)
424{
425 vector<double> concentrations;
426
427 // Check if element exists in first profile
428 if (empty() || begin()->second.count(element_name) == 0) {
429 return concentrations;
430 }
431
432 concentrations.reserve(size());
433
434 for (const auto& [sample_name, profile] : *this)
435 {
436 concentrations.push_back(profile.at(element_name));
437 }
438
439 return concentrations;
440}
441
442vector<double> Elemental_Profile_Set::GetConcentrationsForSample(const string& sample_name) const
443{
444 // Check if sample exists
445 if (count(sample_name) == 0) {
446 return vector<double>();
447 }
448
449 // Use at() to get const reference (no copy)
450 return at(sample_name).GetAllValues();
451}
452
454{
455 if (empty()) {
456 return 0.0;
457 }
458
459 double maximum = -std::numeric_limits<double>::max();
460
461 for (const auto& [sample_name, profile] : *this)
462 {
463 double profile_max = profile.GetMaximum();
464 if (profile_max > maximum) {
465 maximum = profile_max;
466 }
467 }
468
469 return maximum;
470}
471
473{
474 if (empty()) {
475 return 0.0;
476 }
477
478 double minimum = std::numeric_limits<double>::max();
479
480 for (const auto& [sample_name, profile] : *this)
481 {
482 double profile_min = profile.GetMinimum();
483 if (profile_min < minimum) {
484 minimum = profile_min;
485 }
486 }
487
488 return minimum;
489}
490// ========== Regression Models (OM/Size Corrections) ==========
491
493 const string& om,
494 const string& d,
495 regression_form form,
496 const double& p_value_threshold)
497{
499 vector<string> element_names = GetElementNames();
500
501 for (const string& element : element_names)
502 {
503 models[element] = BuildRegressionModel(element, om, d, form, p_value_threshold);
504 models[element].SetDependentVariableName(element);
505 }
506
507 return models;
508}
509
511 const string& element,
512 const string& om,
513 const string& d,
514 regression_form form,
515 const double& p_value_threshold)
516{
518
519 // Get dependent variable (element concentrations)
520 vector<double> dependent = GetAllConcentrationsFor(element);
521
522 // Build independent variables (OM and/or particle size)
523 vector<vector<double>> independents;
524 vector<string> independent_var_names;
525
526 if (!om.empty()) {
527 independents.push_back(GetAllConcentrationsFor(om));
528 independent_var_names.push_back(om);
529 }
530
531 if (!d.empty()) {
532 independents.push_back(GetAllConcentrationsFor(d));
533 independent_var_names.push_back(d);
534 }
535
536 // Configure and run regression
537 model.SetPValueThreshold(p_value_threshold);
538 model.SetEquation(form);
539 model.SetDependentVariableName(element);
540 model.Regress(independents, dependent, independent_var_names);
541
542 return model;
543}
544
546 const string& om,
547 const string& d,
548 regression_form form,
549 const double& p_value_threshold)
550{
551 mlr_vs_om_size_ = BuildRegressionModels(om, d, form, p_value_threshold);
552}
553
560
568
573
574// ========== Statistical Analysis ==========
575
577{
578 vector<string> element_names = GetElementNames();
579 CMBMatrix covariance_matrix(element_names.size());
580
581 // Convert to GSL matrix for statistics calculations
582 gsl_matrix* data_matrix = CopyToGSLMatrix();
583
584 // Set matrix labels
585 for (size_t i = 0; i < element_names.size(); i++)
586 {
587 covariance_matrix.SetColumnLabel(i, element_names[i]);
588 covariance_matrix.SetRowLabel(i, element_names[i]);
589 }
590
591 // Calculate covariance for each element pair
592 for (size_t i = 0; i < data_matrix->size2; i++)
593 {
594 for (size_t j = i; j < data_matrix->size2; j++)
595 {
596 gsl_vector_view col_i = gsl_matrix_column(data_matrix, i);
597 gsl_vector_view col_j = gsl_matrix_column(data_matrix, j);
598
599 // GSL uses n-1 denominator, but we want n denominator for consistency
600 double cov = gsl_stats_covariance(
601 col_i.vector.data, col_i.vector.stride,
602 col_j.vector.data, col_j.vector.stride,
603 col_i.vector.size
604 );
605
606 // Adjust from n-1 to n denominator
607 double adjusted_cov = cov * (col_i.vector.size - 1) / col_i.vector.size;
608
609 // Matrix is symmetric
610 covariance_matrix[i][j] = adjusted_cov;
611 covariance_matrix[j][i] = adjusted_cov;
612 }
613 }
614
615 gsl_matrix_free(data_matrix);
616 return covariance_matrix;
617}
618
620{
621 vector<string> element_names = GetElementNames();
622 CMBMatrix correlation_matrix(element_names.size());
623
624 // Convert to GSL matrix for statistics calculations
625 gsl_matrix* data_matrix = CopyToGSLMatrix();
626
627 // Set matrix labels
628 for (size_t i = 0; i < element_names.size(); i++)
629 {
630 correlation_matrix.SetColumnLabel(i, element_names[i]);
631 correlation_matrix.SetRowLabel(i, element_names[i]);
632 }
633
634 // Calculate correlation for each element pair
635 for (size_t i = 0; i < data_matrix->size2; i++)
636 {
637 for (size_t j = i; j < data_matrix->size2; j++)
638 {
639 gsl_vector_view col_i = gsl_matrix_column(data_matrix, i);
640 gsl_vector_view col_j = gsl_matrix_column(data_matrix, j);
641
642 double corr = gsl_stats_correlation(
643 col_i.vector.data, col_i.vector.stride,
644 col_j.vector.data, col_j.vector.stride,
645 col_i.vector.size
646 );
647
648 // Matrix is symmetric
649 correlation_matrix[i][j] = corr;
650 correlation_matrix[j][i] = corr;
651 }
652 }
653
654 gsl_matrix_free(data_matrix);
655 return correlation_matrix;
656}
657
659{
660 vector<string> element_names = GetElementNames();
661
662 // Allocate matrix: rows = samples, columns = elements
663 gsl_matrix* matrix = gsl_matrix_alloc(size(), element_names.size());
664
665 // Fill matrix with concentration data
666 size_t row = 0;
667 for (const auto& [sample_name, profile] : *this)
668 {
669 size_t col = 0;
670 for (const auto& [element_name, concentration] : profile)
671 {
672 gsl_matrix_set(matrix, row, col, concentration);
673 col++;
674 }
675 row++;
676 }
677
678 return matrix;
679}
680// ========== Statistical Analysis (continued) ==========
681
683 distribution_type dist_type)
684{
685 vector<string> element_names = GetElementNames();
686 CMBVector ks_statistics(element_names.size());
687 ks_statistics.SetLabels(element_names);
688
689 for (size_t i = 0; i < element_names.size(); i++)
690 {
691 ks_statistics[i] = GetElementDistribution(element_names[i])->
692 CalculateKolmogorovSmirnovStatistic(dist_type);
693 }
694
695 return ks_statistics;
696}
697
699 const vector<string>& element_order) const
700{
701 // Use provided element order, or get all elements if not specified
702 vector<string> element_names = element_order.empty() ?
703 GetElementNames() : element_order;
704
705 CVector means(element_names.size());
706
707 for (size_t i = 0; i < element_names.size(); i++)
708 {
709 means[i] = element_distributions_.at(element_names[i]).CalculateMean();
710 }
711
712 return means;
713}
714
715// ========== Serialization (continued) ==========
716
718{
719 QTableWidget* table = new QTableWidget();
720 table->setEditTriggers(QAbstractItemView::NoEditTriggers);
721
722 vector<string> element_names = GetElementNames();
723
724 // Set table dimensions: rows = elements, columns = samples
725 table->setRowCount(element_names.size());
726 table->setColumnCount(size());
727
728 // Build row headers (element names)
729 QStringList row_headers;
730 for (const string& element : element_names)
731 {
732 row_headers << QString::fromStdString(element);
733 }
734 table->setVerticalHeaderLabels(row_headers);
735
736 // Fill table with concentration data
737 QStringList column_headers;
738 int col = 0;
739
740 for (const auto& [sample_name, profile] : *this)
741 {
742 // Add column header (sample name)
743 column_headers << QString::fromStdString(sample_name);
744
745 // Fill column with element concentrations
746 for (size_t row = 0; row < element_names.size(); row++)
747 {
748 double concentration = profile.GetValue(element_names[row]);
749 table->setItem(row, col, new QTableWidgetItem(QString::number(concentration)));
750
751 // Highlight values outside limits if enabled
753 {
754 if (concentration > highlimit || concentration < lowlimit)
755 {
756 table->item(row, col)->setForeground(QColor(Qt::red));
757 }
758 }
759 }
760
761 col++;
762 }
763
764 table->setHorizontalHeaderLabels(column_headers);
765
766 return table;
767}
768// ========== Regression Models (continued) ==========
769
771 const vector<double>& om_size,
772 map<string, element_information>* elementinfo)
773{
774 Elemental_Profile_Set corrected_set;
775
776 for (auto& [sample_name, profile] : *this)
777 {
778 // Only include samples marked for analysis with non-empty names
779 if (profile.IsIncludedInAnalysis() && !sample_name.empty())
780 {
781 Elemental_Profile corrected_profile =
782 profile.ApplyOrganicMatterAndSizeCorrections(om_size, &mlr_vs_om_size_, elementinfo);
783
784 corrected_set.AppendProfile(sample_name, corrected_profile, elementinfo);
785 }
786 }
787
788 return corrected_set;
789}
790// ========== Box-Cox Transformations ==========
791
793{
794 vector<string> elements;
795 for (const auto& [element_name, distribution] : element_distributions_)
796 {
797 if (!distribution.CanBoxCoxTransform())
798 elements.push_back(element_name);
799 }
800 return elements;
801}
802
804{
805 CMBVector lambda_values(element_distributions_.size());
806
807 size_t i = 0;
808 for (auto& [element_name, distribution] : element_distributions_)
809 {
810 lambda_values[i] = distribution.FindOptimalBoxCoxParameter(-5.0, 5.0, 10);
811 lambda_values.SetLabel(i, element_name);
812 i++;
813 }
814
815 return lambda_values;
816}
817// ========== Outlier Detection ==========
818
820 const double& lowerlimit,
821 const double& upperlimit)
822{
823 // Calculate optimal Box-Cox parameters for each element
825
826 // Initialize output matrix: rows = samples, columns = elements
827 CMBMatrix outlier_magnitude(begin()->second.size(), size());
828
829 // Calculate means and standard deviations of Box-Cox transformed distributions
830 vector<double> means;
831 vector<double> stds;
832 vector<bool> transformable;
833 means.reserve(element_distributions_.size());
834 stds.reserve(element_distributions_.size());
835 transformable.reserve(element_distributions_.size());
836
837 size_t elem_idx = 0;
838 for (auto& [element_name, distribution] : element_distributions_)
839 {
840 ConcentrationSet transformed = distribution.ApplyBoxCoxTransform(lambdas[elem_idx], false);
841 means.push_back(transformed.CalculateMean());
842 stds.push_back(transformed.CalculateStdDev());
843 transformable.push_back(distribution.CanBoxCoxTransform());
844 elem_idx++;
845 }
846
847 // Calculate standardized outlier magnitude for each sample
848 size_t sample_idx = 0;
849 for (auto& [sample_name, profile] : *this)
850 {
851 profile.ClearNotes();
852 outlier_magnitude.SetRowLabel(sample_idx, sample_name);
853
854 size_t element_idx = 0;
855 for (const auto& [element_name, concentration] : profile)
856 {
857 outlier_magnitude.SetColumnLabel(element_idx, element_name);
858
859 // Apply the same Box-Cox transformation the means and standard
860 // deviations were computed with. (This used its own formula, which
861 // turned untransformed values x into x - 1 for constituents with
862 // zero or negative values, shifting their scores by 1/std.)
863 double lambda = lambdas[element_idx];
864 double transformed_value = transformable[element_idx] ?
865 ConcentrationSet::BoxCoxTransformValue(concentration, lambda) : concentration;
866
867 // Calculate standardized score
868 double z_score = (transformed_value - means[element_idx]) / stds[element_idx];
869 outlier_magnitude[sample_idx][element_idx] = z_score;
870
871 // Flag outliers if thresholds are set
872 if (upperlimit != lowerlimit)
873 {
874 if (z_score > upperlimit || z_score < lowerlimit)
875 {
876 profile.AppendtoNotes(element_name + " was detected as outlier");
877 }
878 }
879
880 element_idx++;
881 }
882
883 sample_idx++;
884 }
885
886 outlierdone_ = true;
887 return outlier_magnitude;
888}
889
890// ========== Box-Cox Transformations (continued) ==========
891
893{
894 // Use provided lambdas or calculate optimal ones
895 CMBVector lambdas = (lambda_vals == nullptr) ?
896 CalculateBoxCoxParameters() : *lambda_vals;
897
898 // Create copy of this set to transform
899 Elemental_Profile_Set transformed(*this);
900
901 // Apply Box-Cox transformation to each element across all samples
902 size_t elem_idx = 0;
903 for (auto& [element_name, distribution] : element_distributions_)
904 {
905 // Transform all values for this element
906 ConcentrationSet transformed_values =
907 distribution.ApplyBoxCoxTransform(lambdas[elem_idx], false);
908
909 // Update each profile with transformed value
910 size_t sample_idx = 0;
911 for (auto& [sample_name, profile] : transformed)
912 {
913 profile[element_name] = transformed_values[sample_idx];
914 sample_idx++;
915 }
916
917 elem_idx++;
918 }
919
920 return transformed;
921}
922
924{
925 vector<string> element_names = GetElementNames();
926
927 // Initialize matrix: rows = samples, columns = elements
928 CMBMatrix matrix(size(), element_names.size());
929
930 // Fill matrix with concentration data
931 size_t row = 0;
932 for (const auto& [sample_name, profile] : *this)
933 {
934 matrix.SetRowLabel(row, sample_name);
935
936 size_t col = 0;
937 for (const auto& [element_name, concentration] : profile)
938 {
939 matrix[row][col] = concentration;
940 matrix.SetColumnLabel(col, element_name);
941 col++;
942 }
943
944 row++;
945 }
946
947 return matrix;
948}
949
950// ========== Outlier Detection (continued) ==========
951
953 const vector<string>& element_names) const
954{
955 vector<string> elements_with_negative_values;
956
957 for (const string& element : element_names)
958 {
959 if (GetElementDistribution(element).GetMinimum() <= 0)
960 {
961 elements_with_negative_values.push_back(element);
962 }
963 }
964
965 return elements_with_negative_values;
966}
967
968// ========== Utility Functions (continued) ==========
969
971{
972 Elemental_Profile aggregated;
973
974 for (const auto& [sample_name, profile] : *this)
975 {
976 // Get top n elements from this profile sorted by concentration
977 CMBVector sorted = profile.SortByConcentration();
978
979 for (int i = 0; i < n && i < sorted.num; i++)
980 {
981 string element_name = sorted.Label(i);
982 double concentration = sorted[i];
983
984 // Add element if not present, or keep minimum concentration if already present
985 if (aggregated.count(element_name) == 0)
986 {
987 aggregated.AppendElement(element_name, concentration);
988 }
989 else
990 {
991 aggregated[element_name] = std::min(concentration, aggregated[element_name]);
992 }
993 }
994 }
995
996 return aggregated;
997}
998// ========== Utility Functions (continued) ==========
999
1001{
1002 CMBVector dot_products(size());
1003
1004 size_t i = 0;
1005 for (const auto& [sample_name, profile] : *this)
1006 {
1007 dot_products[i] = profile.CalculateDotProduct(v);
1008 dot_products.SetLabel(i, sample_name);
1009 i++;
1010 }
1011
1012 return dot_products;
1013}
1014
1015// Add this to elemental_profile_set.cpp
1016
1018{
1019 if (element_distributions_.count(element_name) > 0) {
1020 return &element_distributions_[element_name];
1021 }
1022 return nullptr;
1023}
1024
1026{
1027 return element_distributions_.at(element_name);
1028}
1029
1031{
1033 return true;
1034}
1035
1037{
1038 if (element_distributions_.count(element_name) > 0)
1039 return element_distributions_[element_name].GetEstimatedDistribution();
1040 else
1041 return nullptr;
1042}
1043
1045{
1046 if (element_distributions_.count(element_name) > 0)
1047 return element_distributions_[element_name].GetFittedDistribution();
1048 else
1049 return nullptr;
1050}
1051
1053{
1054 contribution_ = x;
1055 return true;
1056}
Matrix class with labeled rows and columns for Chemical Mass Balance analysis.
Definition cmbmatrix.h:22
void SetRowLabel(int i, const string &label)
Sets row label at specified index.
Definition cmbmatrix.h:121
void SetColumnLabel(int i, const string &label)
Sets column label at specified index.
Definition cmbmatrix.h:114
Vector class with string labels for Chemical Mass Balance analysis.
Definition cmbvector.h:20
void SetLabels(const vector< string > &label)
Sets all element labels at once.
Definition cmbvector.h:154
void SetLabel(int i, const string &label)
Sets label at specified index.
Definition cmbvector.h:148
string Label(int i) const
Gets label at specified index.
Definition cmbvector.h:121
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).
Definition interface.h:214
Interface()
Default constructor.
Definition interface.cpp:6
Interface & operator=(const Interface &intf)
Assignment operator.
bool highlightoutsideoflimit
Flag indicating whether to highlight values outside defined limits.
Definition interface.h:224
double highlimit
Upper threshold for value highlighting (when enabled).
Definition interface.h:215
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)
Definition resultitem.h:21
void SetType(const result_type &_type)
Definition resultitem.h:26
distribution_type
Enumeration of probability distribution types supported in SedSat3.
The one place where data values entering SedSAT3 are checked.