SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
elemental_profile.cpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
4
9
10#include "elemental_profile.h"
11#include <set>
12#include "numericparsing.h"
13#include <iostream>
14#include "Utilities.h"
15#include <QStringList>
16#include <QFile>
17
18
19// =============================================================================
20// CONSTRUCTION AND ASSIGNMENT
21// =============================================================================
22
36 : map<string, double>(),
37 Interface(),
40{
41 // All initialization done in initializer list
42 // Empty body is fine - demonstrates proper C++ style
43}
44
45
63 : map<string, double>(other), // Copy base class (element concentrations)
64 Interface(other), // Copy Interface base class
67{
68 // All copying done in initializer list - efficient and exception-safe
69}
70
71
72/*/
73*@brief Copy assignment operator
74*
75* Assigns the contents of another profile to this one, replacing all
76* existing data.Handles self - assignment safely.
77*
78*@param other Profile to assign from
79* @return Reference to * this for chaining(e.g., a = b = c)
80*
81* @post* this contains copy of other's data
82* @post Previous contents of * this are replaced
83* @post Self - assignment(a = a) is safe
84*
85*@note Assignment order is important : Interface first, then members,
86* then base class to ensure proper cleanup if exceptions occur
87*/
89{
90 // Check for self-assignment (important for performance and correctness)
91 if (this == &other) {
92 return *this;
93 }
94
95 // Assign in proper order:
96 // 1. Interface base class
98
99 // 2. Member variables
102
103 // 3. map base class (element concentrations)
104 // Done last because it might throw, and we want other data copied first
105 map<string, double>::operator=(other);
106
107 return *this;
108}
109
151 const map<string, element_information>* element_info,
152 bool keep_isotope_bases) const
153{
154 // If no metadata provided, return complete copy
155 if (element_info == nullptr) {
156 return *this;
157 }
158
159 // Create filtered profile
160 Elemental_Profile filtered_profile;
161
162 // Copy analysis inclusion flag
163 filtered_profile.included_in_analysis_ = this->included_in_analysis_;
164
165 // With keep_isotope_bases (the datasets fingerprinting uses), the base
166 // elements of included isotopes are kept even when they are not tracers:
167 // an isotope's delta value is turned into a concentration with its base
168 // element's (e.g. delta 13C with TOC, the organic matter constituent).
169 // The tools that test or select tracers leave them out.
170 std::set<string> isotope_bases;
171 if (keep_isotope_bases)
172 for (const auto& [name, info] : *element_info)
173 if (info.Role == element_information::role::isotope && info.include_in_analysis && !info.base_element.empty())
174 isotope_bases.insert(info.base_element);
175
176 // Iterate through all elements in current profile
177 for (const auto& element_entry : *this) {
178 const string& element_name = element_entry.first;
179 const double concentration = element_entry.second;
180
181 // Check if element exists in metadata
182 auto info_iter = element_info->find(element_name);
183 if (info_iter == element_info->end()) {
184 // Element not in metadata - skip it
185 continue;
186 }
187
188 const element_information& info = info_iter->second;
189
190 // Apply inclusion criteria
191 bool should_include = (info.include_in_analysis &&
195 isotope_bases.count(element_name) > 0;
196
197 if (should_include) {
198 // Add element to filtered profile
199 filtered_profile[element_name] = concentration;
200
201 // Preserve marked status if element was marked
202 auto marked_iter = marked_elements_.find(element_name);
203 if (marked_iter != marked_elements_.end() && marked_iter->second) {
204 filtered_profile.marked_elements_[element_name] = true;
205 }
206 }
207 }
208
209 return filtered_profile;
210}
211
259 bool exclude_elements,
260 bool apply_corrections,
261 const vector<double>& reference_om_size,
262 const MultipleLinearRegressionSet* regression_models,
263 const map<string, element_information>* element_info) const
264{
265 // Start with current profile
266 Elemental_Profile result = *this;
267
268 // Step 1: Apply OM/size corrections if requested
269 if (apply_corrections) {
270 if (regression_models == nullptr) {
271 // Log warning or throw exception in production code
272 std::cerr << "Warning: apply_corrections=true but regression_models is null. "
273 << "Skipping corrections." << std::endl;
274 }
275 else {
277 reference_om_size,
278 regression_models,
279 element_info
280 );
281 }
282 }
283
284 // Step 2: Filter elements if requested
285 if (exclude_elements) {
286 if (element_info == nullptr) {
287 // Log warning or throw exception in production code
288 std::cerr << "Warning: exclude_elements=true but element_info is null. "
289 << "Skipping filtering." << std::endl;
290 }
291 else {
292 result = result.CreateAnalysisProfile(element_info);
293 }
294 }
295
296 return result;
297}
298
349 const map<string, element_information>* element_info,
350 bool include_isotopes) const
351{
352 // Validate input - element_info is required
353 if (element_info == nullptr) {
354 // For now, log error and return empty profile
355 // Future: throw std::invalid_argument("element_info cannot be null")
356 std::cerr << "Error: ExtractChemicalElements called with null element_info. "
357 << "Returning empty profile." << std::endl;
358 return Elemental_Profile();
359 }
360
361 Elemental_Profile extracted_profile;
362
363 // Iterate through all elements in current profile
364 for (const auto& [element_name, concentration] : *this) {
365
366 // Check if element exists in metadata
367 auto info_iter = element_info->find(element_name);
368 if (info_iter == element_info->end()) {
369 // Element not in metadata - skip it
370 // Could log warning: std::cerr << "Warning: Element '" << element_name
371 // << "' not found in metadata. Skipping.\n";
372 continue;
373 }
374
375 const element_information& info = info_iter->second;
376
377 // Check if element should be included based on role
378 bool should_include = false;
379
381 // Always include chemical elements
382 should_include = true;
383 }
384 else if (info.Role == element_information::role::isotope) {
385 // Include isotopes only if requested
386 should_include = include_isotopes;
387 }
388 // All other roles (organic_carbon, particle_size, do_not_include) are excluded
389
390 if (should_include) {
391 extracted_profile[element_name] = concentration;
392 }
393 }
394
395 return extracted_profile;
396}
397
440 const vector<string>& element_names) const
441{
442 Elemental_Profile extracted_profile;
443
444 // Reserve space if we expect most elements to exist (optimization)
445 // Note: Can't reserve in map, but this shows intent
446
447 // Iterate through requested elements
448 for (const string& element_name : element_names) {
449 // Check if element exists in current profile
450 auto it = find(element_name);
451 if (it != end()) {
452 // Element exists - add to extracted profile
453 extracted_profile[element_name] = it->second;
454 }
455 // Element doesn't exist - silently skip
456 }
457
458 return extracted_profile;
459}
460
468double Elemental_Profile::GetValue(const string& element_name) const
469{
470 auto it = find(element_name);
471 if (it == end()) {
472 throw std::out_of_range(
473 "Element '" + element_name + "' does not exist in profile"
474 );
475 }
476 return it->second;
477}
478
479
502 bool Elemental_Profile::SetValue(const string& element_name, double value)
503{
504 auto it = find(element_name);
505 if (it == end()) {
506 return false;
507 }
508
509 it->second = value;
510 return true;
511}
512
525 bool Elemental_Profile::SetMarked(const string& element_name, bool marked)
526 {
527 if (find(element_name) == end()) {
528 return false;
529 }
530
531 marked_elements_[element_name] = marked;
532 return true;
533 }
534
543 bool Elemental_Profile::IsMarked(const string& element_name) const
544 {
545 if (find(element_name) == end()) {
546 return false;
547 }
548
549 auto it = marked_elements_.find(element_name);
550 return (it != marked_elements_.end() && it->second);
551 }
552
553
570 bool Elemental_Profile::AppendElement(const string& element_name, double value)
571 {
572 if (find(element_name) != end()) {
573 return false;
574 }
575
576 (*this)[element_name] = value;
577 marked_elements_[element_name] = false;
578 return true;
579 }
580
593 vector<double> Elemental_Profile::GetAllValues() const
594 {
595 vector<double> values;
596 values.reserve(size());
597
598 for (const auto& [element_name, concentration] : *this) {
599 values.push_back(concentration);
600 }
601
602 return values;
603 }
604
618 {
619 string output;
620
621 for (const auto& [element_name, concentration] : *this) {
622 output += element_name + ":" + aquiutils::numbertostring(concentration) + "\n";
623 }
624
625 return output;
626 }
627
651 {
652 QTableWidget* table = new QTableWidget();
653 table->setEditTriggers(QAbstractItemView::NoEditTriggers);
654 table->setColumnCount(1);
655 table->setRowCount(size());
656
657 QStringList headers;
658 QStringList element_names;
659
660 int row = 0;
661 for (const auto& [element_name, concentration] : *this) {
662 element_names << QString::fromStdString(element_name);
663 table->setItem(row, 0, new QTableWidgetItem(QString::number(concentration)));
664
665 // Highlight values outside limits if enabled
667 (concentration > highlimit || concentration < lowlimit)) {
668 table->item(row, 0)->setForeground(QColor(Qt::red));
669 }
670
671 row++;
672 }
673
674 headers << YAxisLabel();
675 table->setHorizontalHeaderLabels(headers);
676 table->setVerticalHeaderLabels(element_names);
677
678 return table;
679 }
680
693 {
694 QJsonObject json_object;
695 QJsonObject element_contents;
696
697 json_object["Include"] = IsIncludedInAnalysis();
698
699 for (const auto& [element_name, concentration] : *this) {
700 element_contents[QString::fromStdString(element_name)] = concentration;
701 }
702
703 json_object["Element Contents"] = element_contents;
704 json_object["XAxisLabel"] = XAxisLabel();
705 json_object["YAxisLabel"] = YAxisLabel();
706
707 return json_object;
708 }
709
725 bool Elemental_Profile::ReadFromJsonObject(const QJsonObject& json_object)
726 {
727 QString error;
728 return ReadFromJsonObject(json_object, error);
729 }
730
731 bool Elemental_Profile::ReadFromJsonObject(const QJsonObject& json_object, QString& error)
732 {
733 clear();
734
735 // Each value must be a finite number. (toDouble() turned a missing or
736 // non-numeric value, including a NaN saved as null, into 0.)
737 auto read_values = [&](const QJsonObject& values, bool skip_labels) {
738 for (const QString& key : values.keys()) {
739 if (skip_labels && (key == "XAxisLabel" || key == "YAxisLabel"))
740 continue;
741 double value = 0;
742 QString reason;
743 if (!parseNumericJson(values[key], value, reason)) {
744 error = QStringLiteral("constituent '%1': %2").arg(key, reason);
745 return false;
746 }
747 (*this)[key.toStdString()] = value;
748 }
749 return true;
750 };
751
752 if (json_object.contains("Include")) {
753 // Full format with metadata
754 SetIncludedInAnalysis(json_object["Include"].toBool());
755
756 if (!read_values(json_object["Element Contents"].toObject(), false))
757 return false;
758 }
759 else {
760 // Legacy format - elements directly in root
761 if (!read_values(json_object, true))
762 return false;
763 }
764
765 if (json_object.contains("XAxisLabel")) {
766 SetXAxisLabel(json_object["XAxisLabel"].toString());
767 }
768
769 if (json_object.contains("YAxisLabel")) {
770 SetYAxisLabel(json_object["YAxisLabel"].toString()); // Fixed: was SetXAxisLabel
771 }
772
773 return true;
774 }
775
776
791 bool Elemental_Profile::Read(const QStringList& string_list)
792 {
793 clear();
794
795 for (const QString& line : string_list) {
796 QStringList parts = line.split(":");
797 if (parts.size() > 1) {
798 double value = 0;
799 QString reason;
800 if (!parseNumericCell(parts[1], value, reason))
801 return false;
802 AppendElement(parts[0].toStdString(), value);
803 }
804 }
805
806 return true;
807 }
808
821 {
822 file->write(QString::fromStdString(ToString()).toUtf8());
823 return true;
824 }
825
836 {
837 if (empty()) {
838 return -1e12;
839 }
840
841 double max_value = -1e12;
842 for (const auto& [element_name, concentration] : *this) {
843 if (concentration > max_value) {
844 max_value = concentration;
845 }
846 }
847
848 return max_value;
849 }
850
861 {
862 if (empty()) {
863 return 1e12;
864 }
865
866 double min_value = 1e12;
867 for (const auto& [element_name, concentration] : *this) {
868 if (concentration < min_value) {
869 min_value = concentration;
870 }
871 }
872
873 return min_value;
874 }
875
882 {
883 vector<string> names;
884 names.reserve(size());
885
886 for (const auto& [element_name, concentration] : *this) {
887 names.push_back(element_name);
888 }
889
890 return names;
891 }
892
899 bool Elemental_Profile::Contains(const string& element_name) const
900 {
901 return (find(element_name) != end());
902 }
903
904
921 const vector<double>& reference_om_size,
922 const MultipleLinearRegressionSet* regression_models,
923 const map<string, element_information>* element_info) const
924 {
925 Elemental_Profile corrected_profile;
926
927 for (const auto& [element_name, concentration] : *this) {
928 const element_information& info = element_info->at(element_name);
929
930 // Organic carbon and particle size are not corrected. They are kept,
931 // unchanged, so that a later filter can keep the organic matter
932 // constituent when it is an isotope's base element (TOC for delta
933 // 13C); they used to be dropped here.
936 corrected_profile[element_name] = concentration;
937 continue;
938 }
939
940 // Start with original concentration
941 corrected_profile[element_name] = concentration;
942
943 // Apply corrections if regression model exists for this element
944 if (regression_models->count(element_name) == 0) {
945 continue;
946 }
947
948 const MultipleLinearRegression* mlr = &regression_models->at(element_name);
949 const auto& var_names = mlr->GetIndependentVariableNames();
950 const auto& coefficients = mlr->CoefficientsIntercept();
951 bool is_linear = (mlr->Equation() == regression_form::linear);
952
953 // Apply first correction (typically organic matter)
954 if (mlr->Effective(0) && var_names[0] != element_name) {
955 double reference = reference_om_size[0];
956 double measured = this->at(var_names[0]);
957
958 if (is_linear) {
959 corrected_profile[element_name] += (reference - measured) * coefficients[1];
960 }
961 else {
962 corrected_profile[element_name] *= pow(reference / measured, coefficients[1]);
963 }
964 }
965
966 // Apply second correction (typically particle size) if available
967 if (var_names.size() > 1 && mlr->Effective(1) && var_names[1] != element_name) {
968 double reference = reference_om_size[1];
969 double measured = this->at(var_names[1]);
970
971 if (is_linear) {
972 corrected_profile[element_name] += (reference - measured) * coefficients[2];
973 }
974 else {
975 corrected_profile[element_name] *= pow(reference / measured, coefficients[2]);
976 }
977 }
978
979 // Warn about negative corrected values (except for isotopes)
980 if (corrected_profile[element_name] < 0 &&
982 std::cerr << "Warning: Corrected value for " << element_name
983 << " is negative: " << corrected_profile[element_name] << std::endl;
984 }
985 }
986
987 return corrected_profile;
988 }
989
990
1006 {
1007 if (size() != weights.getsize()) {
1008 return -999;
1009 }
1010
1011 double sum = 0.0;
1012 int index = 0;
1013
1014 for (const auto& [element_name, concentration] : *this) {
1015 sum += concentration * weights[index];
1016 index++;
1017 }
1018
1019 return sum;
1020 }
1021
1035 {
1036 CMBVector sorted_result;
1037 vector<string> processed_elements;
1038
1039 for (size_t i = 0; i < size(); i++) {
1040 double target_value = ascending ? 1e6 : -1e6;
1041 string target_element;
1042
1043 for (const auto& [element_name, concentration] : *this) {
1044 // Skip already processed elements
1045 if (lookup(processed_elements, element_name) != -1) {
1046 continue;
1047 }
1048
1049 // Find min (ascending) or max (descending)
1050 bool is_better = ascending ? (concentration < target_value)
1051 : (concentration > target_value);
1052
1053 if (is_better) {
1054 target_element = element_name;
1055 target_value = concentration;
1056 }
1057 }
1058
1059 processed_elements.push_back(target_element);
1060 sorted_result.append(target_element, target_value);
1061 }
1062
1063 return sorted_result;
1064 }
1065
1078 vector<string> Elemental_Profile::SelectTopElements(int n, bool ascending) const
1079 {
1080 CMBVector sorted = SortByConcentration(ascending);
1081 vector<string> top_elements;
1082
1083 for (int i = 0; i < n && i < sorted.num; i++) {
1084 top_elements.push_back(sorted.Label(i));
1085 }
1086
1087 return top_elements;
1088 }
Vector class with string labels for Chemical Mass Balance analysis.
Definition cmbvector.h:20
void append(const string &label, const double &val)
Appends a labeled element to the vector.
string Label(int i) const
Gets label at specified index.
Definition cmbvector.h:121
Elemental_Profile & operator=(const Elemental_Profile &other)
Copy assignment operator.
Elemental_Profile ExtractChemicalElements(const map< string, element_information > *elementinfo, bool include_isotopes=false) const
Extract chemical elements only (exclude isotopes, metadata).
Elemental_Profile ExtractElements(const vector< string > &element_names) const
Extract subset of specified elements.
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.
bool IsMarked(const string &name) const
Check if element is marked.
map< string, bool > marked_elements_
Map tracking marked elements for quality control.
double GetMaximum() const
Get maximum concentration value.
vector< string > GetElementNames() const
Get list of all element names.
double CalculateDotProduct(const CMBVector &weights) const
Calculate dot product with weight vector.
CMBVector SortByConcentration(bool ascending=true) const
Sort elements by concentration value.
bool included_in_analysis_
Whether profile should be included in analysis.
double GetMinimum() const
Get minimum concentration value.
vector< double > GetAllValues() const
Get all concentration values as vector.
bool SetMarked(const string &name, bool marked)
Set marked status for an element.
QTableWidget * ToTable() override
Create Qt table widget representation.
Elemental_Profile CreateAnalysisProfile(const map< string, element_information > *elementinfo=nullptr, bool keep_isotope_bases=false) const
Create profile with only analyzed elements.
void SetIncludedInAnalysis(bool included)
Set analysis inclusion status.
Elemental_Profile CreateCorrectedProfile(bool exclude_elements, bool apply_corrections, const vector< double > &reference_om_size, const MultipleLinearRegressionSet *regression_models=nullptr, const map< string, element_information > *elementinfo=nullptr) const
Create corrected profile with filtering and corrections.
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.
vector< string > SelectTopElements(int n, bool ascending=true) const
Select top N elements by concentration.
Elemental_Profile()
Default constructor - creates empty profile.
string ToString() const override
Convert profile to string representation.
bool writetofile(QFile *file) override
Write profile to file.
bool ReadFromJsonObject(const QJsonObject &json) override
Deserialize from JSON object.
QJsonObject toJsonObject() const override
Serialize to JSON object.
bool IsIncludedInAnalysis() const
Check if profile is included in analysis.
bool SetValue(const string &name, double val)
Set concentration value for existing element.
bool Read(const QStringList &string_list) override
Read profile from string list.
bool Contains(const string &name) const
Check if element exists in profile.
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.
QString XAxisLabel() const
Get the X-axis label.
Definition interface.h:290
bool SetXAxisLabel(const QString &label)
Set the X-axis label.
Definition interface.h:310
QString YAxisLabel() const
Get the Y-axis label.
Definition interface.h:301
bool highlightoutsideoflimit
Flag indicating whether to highlight values outside defined limits.
Definition interface.h:224
bool SetYAxisLabel(const QString &label)
Set the Y-axis label.
Definition interface.h:320
double highlimit
Upper threshold for value highlighting (when enabled).
Definition interface.h:215
Elemental concentration profile for sediment source fingerprinting.
bool parseNumericJson(const QJsonValue &value, double &out, QString &error)
Parses a project-file value as a finite number.
bool parseNumericCell(const QString &text, double &out, QString &error)
Parses text as a finite number.
The one place where data values entering SedSAT3 are checked.
Metadata describing an element's role and properties in analysis.
enum element_information::role Role
@ element
Standard chemical element concentration.
@ isotope
Isotopic ratio (e.g., 206Pb/207Pb).
@ organic_carbon
Organic carbon content.
@ particle_size
Particle size distribution parameter.
@ do_not_include
Exclude from all analyses.
bool include_in_analysis
Whether to include in statistical analyses.