SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
sourcesinkdata.cpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
4#include "sourcesinkdata.h"
5#include <set>
6#include <armadillo>
7#include "mcmcdiagnostics.h"
8#include "numericparsing.h"
9#include "randomstream.h"
10#include <cmath>
11#include <limits>
12#include "iostream"
13#include "NormalDist.h"
14#include "qjsondocument.h"
15#include "resultitem.h"
16#include <gsl/gsl_cdf.h>
17#include "rangeset.h"
18#include "QJsonArray"
19#include "QJsonValue"
20#include <qdir.h>
21
22
23
24// ========== Construction and Assignment ==========
25
54
82
84{
85 // Check for self-assignment
86 if (this == &other) {
87 return *this;
88 }
89
90 // Copy base class
91 map<string, Elemental_Profile_Set>::operator=(other);
92
93 // Copy all member variables
100 outputpath_ = other.outputpath_;
101 parameters_ = other.parameters_;
114 tools_used_ = other.tools_used_;
115 options_ = other.options_;
116
117 return *this;
118}
119
121 const string& target,
122 bool omnsizecorrect,
123 map<string, element_information>* elementinfo)
124{
125 SourceSinkData corrected;
127
128 // Build OM and particle size vector from target sample
129 vector<double> om_size;
130 if (!omconstituent_.empty()) {
131 om_size.push_back(at(target_group_).GetProfile(selected_target_sample_)->at(omconstituent_));
132 }
133 if (!sizeconstituent_.empty()) {
134 om_size.push_back(at(target_group_).GetProfile(selected_target_sample_)->at(sizeconstituent_));
135 }
136
137 // Copy profile sets with appropriate corrections
138 for (auto& [group_name, profile_set] : *this)
139 {
140 // Apply OM/size corrections to source groups, but not to target group
141 bool apply_corrections = (group_name != target_group_) && omnsizecorrect;
142 if (group_name == target_group_)
143 {
144 // Every target sample is kept: the analysis is run on a target
145 // sample named by the user, excluded or not (dropping excluded
146 // target samples here left the analysis without its target)
147 Elemental_Profile_Set targets;
148 for (const auto& [sample_name, profile] : profile_set)
149 if (!sample_name.empty())
150 targets.AppendProfile(sample_name, profile, elementinfo);
151 targets.SetRegressionModels(profile_set.GetRegressionModels());
152 corrected[group_name] = targets;
153 continue;
154 }
155 corrected[group_name] = profile_set.CopyIncludedInAnalysis(
156 apply_corrections,
157 om_size,
158 elementinfo
159 );
160 }
161
162 // Copy analysis settings
163 corrected.omconstituent_ = omconstituent_;
166
167 // Copy element information and distributions
168 if (elementinfo)
169 {
170 // Filter to only include elements marked for analysis, and the base
171 // elements of the included isotopes (which may be the organic matter
172 // constituent, e.g. TOC for delta 13C)
173 std::set<string> isotope_bases;
174 for (const auto& [element_name, elem_info] : element_information_)
175 if (elem_info.Role == element_information::role::isotope && elem_info.include_in_analysis)
176 isotope_bases.insert(elem_info.base_element);
177 for (const auto& [element_name, elem_info] : element_information_)
178 {
179 if ((elem_info.include_in_analysis &&
182 elem_info.Role != element_information::role::particle_size) ||
183 isotope_bases.count(element_name) > 0)
184 {
185 corrected.element_information_[element_name] = element_information_[element_name];
186 corrected.element_distributions_[element_name] = element_distributions_[element_name];
187 }
188 }
189 }
190 else
191 {
192 // Copy all element information
195 }
196
197 // Copy metadata and ordering
201 corrected.observations_ = observations_;
202 corrected.outputpath_ = outputpath_;
203 corrected.target_group_ = target_group_;
207 corrected.element_order_ = element_order_;
208 corrected.isotope_order_ = isotope_order_;
209 corrected.size_om_order_ = size_om_order_;
211 corrected.options_ = options_;
212
213 // Populate distributions for the corrected dataset
215 corrected.AssignAllDistributions();
216
217 return corrected;
218}
219
221 bool exclude_samples,
222 bool exclude_elements,
223 bool omnsizecorrect,
224 const string& target) const
225{
226 SourceSinkData tracers = *this;
227 for (auto& [name, info] : tracers.element_information_)
228 {
229 const bool is_tracer = info.Role == element_information::role::element ||
231 info.include_in_analysis = is_tracer && (!exclude_elements || info.include_in_analysis);
232 }
233 return tracers.CreateCorrectedAndFilteredDataset(exclude_samples, true, omnsizecorrect, target);
234}
235
236int SourceSinkData::CountElements(bool exclude_elements) const
237{
238 if (!exclude_elements) {
239 return element_information_.size();
240 }
241
242 int count = 0;
243 for (const auto& [element_name, elem_info] : element_information_)
244 {
245 // Include if marked for analysis AND not an excluded role
246 if (elem_info.include_in_analysis &&
250 {
251 count++;
252 }
253 }
254
255 return count;
256}
257
259 bool exclude_samples,
260 bool exclude_elements,
261 bool omnsizecorrect,
262 const string& target) const
263{
264 SourceSinkData corrected;
265 corrected.target_group_ = target_group_;
266
267 // Set target sample (use provided or keep current)
268 if (!target.empty()) {
269 corrected.selected_target_sample_ = target;
270 }
271 else {
273 }
274
275 // Build OM and particle size vector from target sample (if corrections enabled)
276 vector<double> om_size;
277 if (omnsizecorrect)
278 {
279 if (!omconstituent_.empty()) {
280 om_size.push_back(
281 at(target_group_).GetProfile(corrected.selected_target_sample_).at(omconstituent_)
282 );
283 }
284 if (!sizeconstituent_.empty()) {
285 om_size.push_back(
286 at(target_group_).GetProfile(corrected.selected_target_sample_).at(sizeconstituent_)
287 );
288 }
289 }
290
291 // Copy and correct each profile set
292 for (const auto& [group_name, profile_set] : *this)
293 {
294 if (group_name == target_group_)
295 {
296 // Target group: apply element filtering but no sample filtering or corrections
297 corrected[group_name] = profile_set.CreateCorrectedSet(
298 false, // Don't exclude samples from target
299 exclude_elements, // Apply element filtering
300 false, // Don't apply OM/size corrections to target
301 om_size,
303 );
304 }
305 else
306 {
307 // Source groups: apply all requested filtering and corrections
308 corrected[group_name] = profile_set.CreateCorrectedSet(
309 exclude_samples, // Apply sample filtering
310 exclude_elements, // Apply element filtering
311 omnsizecorrect, // Apply OM/size corrections
312 om_size,
314 );
315 }
316 }
317
318 // Copy settings and metadata
319 corrected.omconstituent_ = omconstituent_;
322 corrected.options_ = options_;
323
324 // Populate element information and distributions
327 corrected.AssignAllDistributions();
328
329 return corrected;
330}
331
333{
334 SourceSinkData extracted;
335 extracted.target_group_ = target_group_;
336
337 // Extract chemical elements from each profile set
338 for (const auto& [group_name, profile_set] : *this)
339 {
340 extracted[group_name] = profile_set.ExtractChemicalElements(&element_information_, isotopes);
341 }
342
343 // Copy settings
344 extracted.omconstituent_ = omconstituent_;
347
348 // Populate distributions for extracted elements
351 extracted.AssignAllDistributions();
352
353 return extracted;
354}
355
356SourceSinkData SourceSinkData::ExtractSpecificElements(const vector<string>& element_list) const
357{
358 SourceSinkData extracted;
359
360 // Extract specified elements from source groups only (not target)
361 for (const auto& [group_name, profile_set] : *this)
362 {
363 if (group_name != target_group_)
364 {
365 extracted[group_name] = profile_set.ExtractElements(element_list);
366 }
367 }
368
369 // Populate distributions for extracted elements
372 extracted.AssignAllDistributions();
373
374 return extracted;
375}
376
378{
379 // Clear all profile sets (base class map)
380 clear();
381
382 // Clear element data
383 element_information_.clear();
385
386 // Reset counters
390
391 // Clear MCMC/optimization data
392 observations_.clear();
393 parameters_.clear();
394
395 // Clear identifiers and paths
396 outputpath_.clear();
397 target_group_.clear();
399
400 // Clear ordering vectors
401 samplesetsorder_.clear();
402 constituent_order_.clear();
403 element_order_.clear();
404 isotope_order_.clear();
405 size_om_order_.clear();
406
407 // Clear tracking data
408 tools_used_.clear();
409
410 // Note: options_ is intentionally not cleared (preserves user settings)
411}
412
414 const string& name,
416{
417 // Check if group name already exists
418 if (count(name) > 0)
419 {
420 std::cerr << "Sample set '" + name + "' already exists!" << std::endl;
421 return nullptr;
422 }
423
424 // Add the new sample set
425 operator[](name) = elemental_profile_set;
426
427 return &operator[](name);
428}
429
430
432{
433 if (count(name) == 0) {
434 return nullptr;
435 }
436
437 return &operator[](name);
438}
439
440vector<string> SourceSinkData::GetSampleNames(const string& group_name) const
441{
442 const Elemental_Profile_Set* profile_set =
443 (count(group_name) > 0) ? &at(group_name) : nullptr;
444
445 if (profile_set) {
446 return profile_set->GetSampleNames();
447 }
448
449 return vector<string>();
450}
451
452vector<string> SourceSinkData::GetGroupNames() const
453{
454 vector<string> group_names;
455 group_names.reserve(size());
456
457 for (const auto& [group_name, profile_set] : *this)
458 {
459 group_names.push_back(group_name);
460 }
461
462 return group_names;
463}
464
466{
467 if (empty()) {
468 return vector<string>();
469 }
470
471 // Get element names from first sample of first group
472 const Elemental_Profile_Set& first_group = begin()->second;
473 if (first_group.empty()) {
474 return vector<string>();
475 }
476
477 const Elemental_Profile& first_sample = first_group.begin()->second;
478
479 vector<string> element_names;
480 element_names.reserve(first_sample.size());
481
482 for (const auto& [element_name, concentration] : first_sample)
483 {
484 element_names.push_back(element_name);
485 }
486
487 return element_names;
488}
489
491 const vector<vector<string>>& indicators) const
492{
493 profiles_data extracted;
494 extracted.element_names = GetElementNames();
495 extracted.values.reserve(indicators.size());
496 extracted.sample_names.reserve(indicators.size());
497
498 for (const auto& indicator : indicators)
499 {
500 const string& group_name = indicator[0];
501 const string& sample_name = indicator[1];
502
503 const Elemental_Profile_Set* group =
504 (count(group_name) > 0) ? &at(group_name) : nullptr;
505
506 if (group)
507 {
508 vector<double> concentrations = group->GetConcentrationsForSample(sample_name);
509 extracted.values.push_back(concentrations);
510 extracted.sample_names.push_back(sample_name);
511 }
512 }
513
514 return extracted;
515}
516
518 const vector<vector<string>>& indicators) const
519{
520 Elemental_Profile_Set extracted;
521
522 for (const auto& indicator : indicators)
523 {
524 const string& group_name = indicator[0];
525 const string& sample_name = indicator[1];
526
527 const Elemental_Profile_Set* group =
528 (count(group_name) > 0) ? &at(group_name) : nullptr;
529
530 if (group && group->count(sample_name) > 0)
531 {
532 const Elemental_Profile& profile = group->at(sample_name);
533 // Prefix with group name to ensure uniqueness
534 extracted.AppendProfile(group_name + "-" + sample_name, profile);
535 }
536 }
537
538 return extracted;
539}
541 const string& element,
542 const string& group) const
543{
544 element_data extracted;
545 extracted.group_name = group;
546
547 const Elemental_Profile_Set* profile_set =
548 (count(group) > 0) ? &at(group) : nullptr;
549
550 if (!profile_set) {
551 return extracted;
552 }
553
554 extracted.values.reserve(profile_set->size());
555 extracted.sample_names.reserve(profile_set->size());
556
557 for (const auto& [sample_name, profile] : *profile_set)
558 {
559 extracted.values.push_back(profile.GetValue(element));
560 extracted.sample_names.push_back(sample_name);
561 }
562
563 return extracted;
564}
565
567{
568 vector<string> element_names = GetElementNames();
570
571 // Update distributions within each group, then aggregate
572 for (auto& [group_name, profile_set] : *this)
573 {
574 // Build distributions within this group
575 profile_set.UpdateElementDistributions();
576
577 // Aggregate into overall distributions
578 for (const string& element : element_names)
579 {
580 element_distributions_[element].AppendSet(
581 profile_set.GetElementDistribution(element)
582 );
583 }
584 }
585}
586
587map<string, vector<double>> SourceSinkData::ExtractElementDataByGroup(const string& element) const
588{
589 map<string, vector<double>> extracted;
590 vector<string> group_names = GetGroupNames();
591
592 for (const string& group_name : group_names)
593 {
594 element_data group_data = ExtractElementConcentrations(element, group_name);
595 extracted[group_name] = group_data.values;
596 }
597
598 return extracted;
599}
600
601
603{
604 vector<string> element_names = GetElementNames();
605
606 for (const string& element : element_names)
607 {
608 // Assign distribution at dataset level (all groups combined)
609 Distribution* overall_fitted = element_distributions_[element].GetFittedDistribution();
610 overall_fitted->distribution = element_distributions_[element].SelectBestDistribution();
611 overall_fitted->parameters = element_distributions_[element].EstimateDistributionParameters();
612
613 // Assign distributions at group level
614 for (auto& [group_name, profile_set] : *this)
615 {
616 ConcentrationSet* group_dist = profile_set.GetElementDistribution(element);
617 Distribution* group_fitted = group_dist->GetFittedDistribution();
618
619 // Use same distribution type as overall
620 group_fitted->distribution = overall_fitted->distribution;
621
622 // Estimate parameters from group-specific data
624 {
625 // Elements: use selected distribution type
626 group_fitted->parameters = group_dist->EstimateDistributionParameters(
627 overall_fitted->distribution
628 );
629 }
630 else
631 {
632 // Isotopes: always use normal distribution
633 group_fitted->parameters = group_dist->EstimateDistributionParameters(
635 );
636 }
637 }
638 }
639}
640
642{
643 if (element_distributions_.count(element_name) == 0) {
644 return nullptr;
645 }
646
647 return element_distributions_[element_name].GetFittedDistribution();
648}
649
650void SourceSinkData::PopulateElementInformation(const map<string, element_information>* ElementInfo)
651{
652 element_information_.clear();
653 vector<string> element_names = GetElementNames();
654
655 for (const string& element : element_names)
656 {
657 if (ElementInfo == nullptr)
658 {
659 // Use default element information
661 }
662 else
663 {
664 // Copy from provided element information
665 element_information_[element] = ElementInfo->at(element);
666 }
667 }
668
669 // Update source sample set count
670 if (!target_group_.empty())
671 {
672 numberofsourcesamplesets_ = size() - 1; // Exclude target group
673 }
674 else
675 {
676 numberofsourcesamplesets_ = size(); // No target group
677 }
678}
679
680string SourceSinkData::GetParameterName(int index) const
681{
682 if (parameter(index))
683 {
684 return parameter(index)->Name();
685 }
686 return "";
687}
688
690{
691 // Set first source to dummy value to force recalculation
693
694 // Keep sampling until valid contributions found (sum = 1, all >= 0)
695 while (GetContributionVector(false).min() < 0 || GetContributionVector(false).sum() > 1)
696 {
697 for (size_t i = 0; i < samplesetsorder_.size() - 1; i++)
698 {
699 SetContribution(i, stream.Uniform());
700 }
701 }
702
703 return true;
704}
705
707{
708 // Set first source to dummy value
710
711 // Generate random normal values
712 CVector X(static_cast<int>(samplesetsorder_.size()));
713 for (size_t i = 0; i < samplesetsorder_.size(); i++)
714 X[i] = stream.StandardNormal();
715
716 // Apply softmax transformation to ensure sum = 1
718
719 return true;
720}
721
722
723namespace {
724
739bool FittedParametersAvailable(const Distribution* fitted,
740 size_t needed,
741 const string& element_name,
742 const string& group_name)
743{
744 if (fitted != nullptr && fitted->parameters.size() >= needed)
745 return true;
746
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;
751 return false;
752}
753
754} // namespace
755
757 const string& targetsamplename,
758 estimation_mode est_mode)
759{
760 // Populate element ordering vectors
762 selected_target_sample_ = targetsamplename;
763
764 // Validate data is loaded
765 if (empty())
766 {
767 std::cerr << "Data has not been loaded!" << std::endl;
768 return false;
769 }
770
771 numberofsourcesamplesets_ = size() - 1;
772
773 // Clear existing parameters and observations
774 parameters_.clear();
775 observations_.clear();
776 samplesetsorder_.clear();
777
778 // ========== Setup Source Contribution Parameters ==========
779
781 {
782 // Create contribution parameters for all sources except last (calculated from constraint)
783 for (auto& [group_name, profile_set] : *this)
784 {
785 if (group_name != GetTargetGroup())
786 {
787 Parameter p;
788 p.SetName(group_name + "_contribution");
790 p.SetRange(0, 1);
791 parameters_.push_back(p);
792 samplesetsorder_.push_back(group_name);
793 }
794 }
795 // Remove last contribution parameter (calculated from sum constraint)
796 parameters_.pop_back();
797 }
798 else
799 {
800 // Build source order without creating parameters
801 for (auto& [group_name, profile_set] : *this)
802 {
803 if (group_name != GetTargetGroup())
804 {
805 samplesetsorder_.push_back(group_name);
806 }
807 }
808 }
809
810 // ========== Count Elements and Isotopes ==========
811
814
815 for (const auto& [element_name, elem_info] : element_information_)
816 {
817 if (elem_info.include_in_analysis)
818 {
819 if (elem_info.Role == element_information::role::element) {
821 }
822 else if (elem_info.Role == element_information::role::isotope) {
824 }
825 }
826 }
827
828 // ========== Initialize Estimated Distributions from Fitted ==========
829
830 // For elements
831 for (const auto& [element_name, elem_info] : element_information_)
832 {
833 if (elem_info.Role == element_information::role::element && elem_info.include_in_analysis)
834 {
835 for (auto& [group_name, profile_set] : *this)
836 {
837 if (group_name != target_group_)
838 {
839 // Copy fitted distribution to estimated (starting point for optimization)
840 *profile_set.GetEstimatedDistribution(element_name) =
841 *profile_set.GetFittedDistribution(element_name);
842 }
843 }
844 }
845 }
846
847 // For isotopes
848 for (const auto& [element_name, elem_info] : element_information_)
849 {
850 if (elem_info.Role == element_information::role::isotope && elem_info.include_in_analysis)
851 {
852 for (auto& [group_name, profile_set] : *this)
853 {
854 if (group_name != target_group_)
855 {
856 *profile_set.GetEstimatedDistribution(element_name) =
857 *profile_set.GetFittedDistribution(element_name);
858 }
859 }
860 }
861 }
862
863 // ========== Setup Source Profile Parameters (if estimating profiles) ==========
864
866 {
867 // Mu parameters for elements (lognormal)
868 for (const auto& [element_name, elem_info] : element_information_)
869 {
870 if (elem_info.Role == element_information::role::element && elem_info.include_in_analysis)
871 {
872 for (auto& [group_name, profile_set] : *this)
873 {
874 if (group_name != target_group_)
875 {
876 Parameter p;
877 p.SetName(group_name + "_" + element_name + "_mu");
879
880 // A dataset that has not had its distributions built
881 // has no fitted parameters to center the range on.
882 // Reading them anyway is an out-of-range access on an
883 // empty vector, so report the omission instead.
884 Distribution* estimated = profile_set.GetEstimatedDistribution(element_name);
885 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
886
887 if (estimated == nullptr ||
888 !FittedParametersAvailable(fitted, 1, element_name, group_name))
889 {
890 return false;
891 }
892
893 // Set estimated distribution type
895
896 // Set parameter range around fitted mu
897 p.SetRange(fitted->parameters[0] - 0.2, fitted->parameters[0] + 0.2);
898
899 parameters_.push_back(p);
900 }
901 }
902 }
903 }
904
905 // Mu parameters for isotopes (normal)
906 for (const auto& [element_name, elem_info] : element_information_)
907 {
908 if (elem_info.Role == element_information::role::isotope && elem_info.include_in_analysis)
909 {
910 for (auto& [group_name, profile_set] : *this)
911 {
912 if (group_name != target_group_)
913 {
914 Parameter p;
915 p.SetName(group_name + "_" + element_name + "_mu");
917
918 Distribution* estimated = profile_set.GetEstimatedDistribution(element_name);
919 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
920
921 if (estimated == nullptr ||
922 !FittedParametersAvailable(fitted, 1, element_name, group_name))
923 {
924 return false;
925 }
926
927 // Set estimated distribution type
929
930 // Set parameter range around fitted mu
931 p.SetRange(fitted->parameters[0] - 0.2, fitted->parameters[0] + 0.2);
932
933 parameters_.push_back(p);
934 }
935 }
936 }
937 }
938
939 // Sigma parameters for elements
940 for (const auto& [element_name, elem_info] : element_information_)
941 {
942 if (elem_info.Role == element_information::role::element && elem_info.include_in_analysis)
943 {
944 for (auto& [group_name, profile_set] : *this)
945 {
946 if (group_name != target_group_)
947 {
948 Parameter p;
949 p.SetName(group_name + "_" + element_name + "_sigma");
951
952 // Set parameter range around fitted sigma (with bounds)
953 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
954
955 if (!FittedParametersAvailable(fitted, 2, element_name, group_name))
956 return false;
957
958 double lower = std::max(fitted->parameters[1] * 0.8, 0.001);
959 double upper = std::max(fitted->parameters[1] / 0.8, 2.0);
960 p.SetRange(lower, upper);
961
962 parameters_.push_back(p);
963 }
964 }
965 }
966 }
967
968 // Sigma parameters for isotopes
969 for (const auto& [element_name, elem_info] : element_information_)
970 {
971 if (elem_info.Role == element_information::role::isotope && elem_info.include_in_analysis)
972 {
973 for (auto& [group_name, profile_set] : *this)
974 {
975 if (group_name != target_group_)
976 {
977 Parameter p;
978 p.SetName(group_name + "_" + element_name + "_sigma");
980
981 // Set parameter range around fitted sigma (with bounds)
982 const Distribution* fitted = profile_set.GetFittedDistribution(element_name);
983
984 if (!FittedParametersAvailable(fitted, 2, element_name, group_name))
985 return false;
986
987 double lower = std::max(fitted->parameters[1] * 0.8, 0.001);
988 double upper = std::max(fitted->parameters[1] / 0.8, 2.0);
989 p.SetRange(lower, upper);
990
991 parameters_.push_back(p);
992 }
993 }
994 }
995 }
996 }
997
998 // ========== Setup Error and Observation Parameters ==========
999
1001 {
1002 // Error standard deviation for elements
1003 Parameter error_param;
1004 error_param.SetName("Error STDev");
1006 error_param.SetRange(0.01, 0.1);
1007 parameters_.push_back(error_param);
1008
1009 // Create observations for elements
1010 for (const auto& [element_name, elem_info] : element_information_)
1011 {
1012 if (elem_info.Role == element_information::role::element && elem_info.include_in_analysis)
1013 {
1014 Observation obs;
1015 obs.SetName(targetsamplename + "_" + element_name);
1016 obs.AppendValues(0, GetElementalProfile(targetsamplename)->GetValue(element_name));
1017 observations_.push_back(obs);
1018 }
1019 }
1020
1021 // Error standard deviation for isotopes
1022 Parameter error_param_isotope;
1023 error_param_isotope.SetName("Error STDev for isotopes");
1025 error_param_isotope.SetRange(0.01, 0.1);
1026 parameters_.push_back(error_param_isotope);
1027
1028 // Create observations for isotopes
1029 for (const auto& [element_name, elem_info] : element_information_)
1030 {
1031 if (elem_info.Role == element_information::role::isotope && elem_info.include_in_analysis)
1032 {
1033 Observation obs;
1034 obs.SetName(targetsamplename + "_" + element_name);
1035 obs.AppendValues(0, GetElementalProfile(targetsamplename)->GetValue(element_name));
1036 observations_.push_back(obs);
1037 }
1038 }
1039 }
1040
1041 return true;
1042}
1043
1044
1046{
1047 CVector contributions(size()-1);
1048 for (unsigned long int i=0; i<size()-2; i++)
1049 {
1050 contributions[i] = parameter(i)->Value();
1051 }
1052 contributions[size()-2] = 1 - contributions.sum();
1053 return contributions;
1054}
1055
1056
1058{
1059 if (GetSourceContributions().min()<0)
1060 return -1e10;
1061 else
1062 return 0;
1063}
1064
1066{
1067 double logLikelihood = 0;
1068 for (unsigned int element_counter=0; element_counter<element_order_.size(); element_counter++)
1069 {
1070 for (unsigned int source_group_counter=0; source_group_counter<numberofsourcesamplesets_; source_group_counter++)
1071 {
1072 Elemental_Profile_Set *this_source_group = GetSampleSet(samplesetsorder_[source_group_counter]);
1073
1074
1075 for (map<string,Elemental_Profile>::iterator sample = this_source_group->begin(); sample!=this_source_group->end(); sample++)
1076 {
1077 logLikelihood += this_source_group->GetElementDistribution(element_order_[element_counter])->GetEstimatedDistribution()->EvalLog(sample->second.GetValue(element_order_[element_counter]));
1078 }
1079
1080 }
1081 }
1082 return logLikelihood;
1083}
1084
1086{
1087 CVector observed_data(element_order_.size());
1088 for (unsigned int i=0; i<element_order_.size(); i++)
1089 { if (SelectedTargetSample!="")
1090 observed_data[i] = this->GetSampleSet(GetTargetGroup())->GetProfile(SelectedTargetSample)->GetValue(element_order_[i]);
1091 else if (selected_target_sample_!="")
1093 }
1094 return observed_data;
1095}
1096
1098{
1099 CVector observed_data(isotope_order_.size());
1100 for (unsigned int i=0; i<isotope_order_.size(); i++)
1101 { string corresponding_element = element_information_[isotope_order_[i]].base_element;
1102 if (SelectedTargetSample!="")
1103 observed_data[i] = (this->GetSampleSet(GetTargetGroup())->GetProfile(SelectedTargetSample)->GetValue(isotope_order_[i])/double(1000)+1.0)*element_information_[isotope_order_[i]].standard_ratio*GetSampleSet(GetTargetGroup())->GetProfile(SelectedTargetSample)->GetValue(corresponding_element);
1104 else if (selected_target_sample_!="")
1106 // (This branch read the base element from GetProfile(SelectedTargetSample),
1107 // which is empty here, so it dereferenced a null pointer)
1108 }
1109 return observed_data;
1110}
1111
1113{
1114 CVector observed_data(isotope_order_.size());
1115 for (unsigned int i=0; i<isotope_order_.size(); i++)
1116 {
1117 if (SelectedTargetSample!="")
1118 observed_data[i] = this->GetSampleSet(GetTargetGroup())->GetProfile(SelectedTargetSample)->GetValue(isotope_order_[i]);
1119 else if (selected_target_sample_!="")
1121 }
1122 return observed_data;
1123}
1124
1125
1127{
1128 // Determine parameter mode based on estimation mode
1132
1133 // Get predicted and observed concentrations
1134 CVector predicted_concentrations = PredictTarget(param_mode);
1135 CVector observed_concentrations = ObservedDataforSelectedSample(selected_target_sample_);
1136
1137 // Check validity of predictions (all values must be positive for log-transformation)
1138 if (predicted_concentrations.min() <= 0)
1139 {
1140 return -1e10; // Invalid prediction: return extremely low likelihood
1141 }
1142
1143 // Calculate log-likelihood in log-space
1144 // Formula: log(L) = -n*log(σ) - ||log(C_pred) - log(C_obs)||² / (2σ²)
1145 const double num_elements = predicted_concentrations.num;
1146 const double normalization_term = num_elements * log(error_stdev_);
1147
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);
1151
1152 double log_likelihood = -normalization_term - (sum_squared_residuals / variance_term);
1153
1154 return log_likelihood;
1155}
1156
1158{
1159 // Determine parameter mode based on estimation mode
1163
1164 // Get predicted and observed isotopic delta values
1165 CVector predicted_deltas = PredictTarget_Isotope_delta(param_mode);
1167
1168 // Calculate log-likelihood in linear space (delta values)
1169 // Formula: log(L) = -n*log(σ_iso) - ||δ_pred - δ_obs||² / (2σ_iso²)
1170 const double num_isotopes = predicted_deltas.num;
1171 const double normalization_term = num_isotopes * log(error_stdev_isotope_);
1172
1173 CVector residuals = predicted_deltas - observed_deltas;
1174 const double sum_squared_residuals = pow(residuals.norm2(), 2);
1175 const double variance_term = 2.0 * pow(error_stdev_isotope_, 2);
1176
1177 double log_likelihood = -normalization_term - (sum_squared_residuals / variance_term);
1178
1179 return log_likelihood;
1180}
1181
1182
1184{
1185 // Get predicted values using direct parameter mode
1186 CVector predicted_concentrations = PredictTarget(parameter_mode::direct);
1187 CVector predicted_deltas = PredictTarget_Isotope_delta(parameter_mode::direct);
1188
1189 // Check for invalid predictions
1190 if (!predicted_concentrations.is_finite())
1191 {
1192 // qDebug() << "Warning: Non-finite predicted concentrations detected in ResidualVector()";
1193 }
1194
1195 // Get observed values for the selected target sample
1196 CVector observed_concentrations = ObservedDataforSelectedSample(selected_target_sample_);
1198
1199 // Calculate residuals
1200 // Elemental: log-space residuals (log(predicted) - log(observed))
1201 CVector elemental_residuals = predicted_concentrations.Log() - observed_concentrations.Log();
1202
1203 // Isotopic: linear residuals (predicted_delta - observed_delta)
1204 CVector isotopic_residuals = predicted_deltas - observed_deltas;
1205
1206 // Combine residuals: [elemental_residuals, isotopic_residuals]
1207 CVector combined_residuals = elemental_residuals;
1208 combined_residuals.append(isotopic_residuals);
1209
1210 // Check for non-finite residuals (indicates numerical issues)
1211 //if (!combined_residuals.is_finite())
1212 //{
1213 // qDebug() << "Warning: Non-finite residuals detected in ResidualVector()";
1214 // qDebug() << "Contribution vector:" << GetContributionVector().toString();
1215 // qDebug() << "Contribution vector (softmax):" << GetContributionVectorSoftmax().toString();
1216 //}
1217
1218 return combined_residuals;
1219}
1220
1222{
1223 // Get predicted values (returns CVector with .vec member for Armadillo compatibility)
1224 CVector_arma predicted_concentrations = PredictTarget().vec;
1225 CVector_arma predicted_deltas = PredictTarget_Isotope_delta().vec;
1226
1227 // Get observed values for the selected target sample
1228 CVector_arma observed_concentrations = ObservedDataforSelectedSample(selected_target_sample_).vec;
1229 CVector_arma observed_deltas = ObservedDataforSelectedSample_Isotope_delta(selected_target_sample_).vec;
1230
1231 // Calculate residuals
1232 // Elemental: log-space residuals (log(predicted) - log(observed))
1233 CVector_arma elemental_residuals = predicted_concentrations.Log() - observed_concentrations.Log();
1234
1235 // Isotopic: linear residuals (predicted_delta - observed_delta)
1236 CVector_arma isotopic_residuals = predicted_deltas - observed_deltas;
1237
1238 // Combine residuals: [elemental_residuals, isotopic_residuals]
1239 CVector_arma combined_residuals = elemental_residuals;
1240 combined_residuals.append(isotopic_residuals);
1241
1242 return combined_residuals;
1243}
1244
1245
1247{
1248 const size_t num_sources = GetSourceOrder().size();
1249 const size_t num_parameters = num_sources - 1; // Last contribution is implicit
1250 const size_t num_residuals = element_order_.size() + isotope_order_.size();
1251
1252 CMatrix_arma jacobian(num_parameters, num_residuals);
1253
1254 // Store base state
1255 CVector_arma base_contributions = GetContributionVector(false).vec;
1256 CVector_arma base_residuals = ResidualVector_arma();
1257
1258 // Compute derivatives using finite differences
1259 for (unsigned int i = 0; i < num_parameters; i++)
1260 {
1261 // Adaptive epsilon: smaller when far from 0.5, larger when near boundaries
1262 const double epsilon = (0.5 - base_contributions[i]) * 1e-6;
1263
1264 // Perturb contribution
1265 SetContribution(i, base_contributions[i] + epsilon);
1266 CVector_arma perturbed_residuals = ResidualVector_arma();
1267
1268 // Compute derivative: ∂residuals/∂contribution_i
1269 jacobian.setcol(i, (perturbed_residuals - base_residuals) / epsilon);
1270
1271 // Restore original contribution
1272 SetContribution(i, base_contributions[i]);
1273 }
1274
1275 return jacobian;
1276}
1277
1279{
1280 const size_t num_sources = GetSourceOrder().size();
1281 const size_t num_parameters = num_sources - 1; // Last contribution is implicit
1282 const size_t num_residuals = element_order_.size() + isotope_order_.size();
1283
1284 CMatrix jacobian(num_parameters, num_residuals);
1285
1286 // Store base state
1287 CVector base_contributions = GetContributionVector(false);
1288 CVector base_residuals = ResidualVector();
1289
1290 // Compute derivatives using finite differences
1291 for (unsigned int i = 0; i < num_parameters; i++)
1292 {
1293 // Adaptive epsilon: smaller when far from 0.5, larger when near boundaries
1294 const double epsilon = (0.5 - base_contributions[i]) * 1e-3;
1295
1296 // Perturb contribution
1297 SetContribution(i, base_contributions[i] + epsilon);
1298 CVector perturbed_residuals = ResidualVector();
1299
1300 // Compute derivative: ∂residuals/∂contribution_i
1301 jacobian.setrow(i, (perturbed_residuals - base_residuals) / epsilon);
1302
1303 // Restore original contribution
1304 SetContribution(i, base_contributions[i]);
1305 }
1306
1307 return jacobian;
1308}
1309
1311{
1312 const size_t num_sources = GetSourceOrder().size();
1313 const size_t num_residuals = element_order_.size() + isotope_order_.size();
1314
1315 CMatrix jacobian(num_sources, num_residuals); // All sources are parameters in softmax
1316
1317 // Store base state
1318 CVector base_softmax_params = GetContributionVectorSoftmax();
1319 CVector base_residuals = ResidualVector();
1320
1321 // Compute derivatives using finite differences
1322 for (unsigned int i = 0; i < num_sources; i++)
1323 {
1324 // Sign-dependent epsilon for better numerical behavior
1325 const double epsilon = -sign(base_softmax_params[i]) * 1e-3;
1326
1327 // Perturb softmax parameter
1328 CVector perturbed_params = base_softmax_params;
1329 perturbed_params[i] += epsilon;
1330 SetContributionSoftmax(perturbed_params);
1331
1332 CVector perturbed_residuals = ResidualVector();
1333
1334 // Compute derivative: ∂residuals/∂softmax_param_i
1335 jacobian.setrow(i, (perturbed_residuals - base_residuals) / epsilon);
1336
1337 // Restore original softmax parameters
1338 SetContributionSoftmax(base_softmax_params);
1339 }
1340
1341 return jacobian;
1342}
1343
1345{
1346 // Get current residuals and Jacobian
1347 CVector residuals = ResidualVector();
1348 CMatrix jacobian = ResidualJacobian();
1349
1350 // Compute J^T J (normal equations matrix)
1351 CMatrix jacobian_transpose_jacobian = jacobian * Transpose(jacobian);
1352
1353 // Apply Levenberg-Marquardt damping: (1 + λ) on diagonal
1354 jacobian_transpose_jacobian.ScaleDiagonal(1.0 + lambda);
1355
1356 // Compute right-hand side: J^T r
1357 CVector jacobian_times_residuals = jacobian * residuals;
1358
1359 // Check for near-singular matrix and add regularization if needed
1360 if (det(jacobian_transpose_jacobian) <= 1e-6)
1361 {
1362 // Add additional regularization: λI
1363 const size_t matrix_size = jacobian_transpose_jacobian.getnumcols();
1364 CMatrix identity = CMatrix::Diag(matrix_size);
1365 jacobian_transpose_jacobian += lambda * identity;
1366 }
1367
1368 // Solve for parameter update: dx = (J^T J)^(-1) J^T r
1369 CVector parameter_update = jacobian_times_residuals / jacobian_transpose_jacobian;
1370
1371 return parameter_update;
1372}
1373
1375{
1376 // Get current residuals and Jacobian (softmax parameterization)
1377 CVector residuals = ResidualVector();
1378 CMatrix jacobian = ResidualJacobian_softmax();
1379
1380 // Compute J^T J (normal equations matrix)
1381 CMatrix jacobian_transpose_jacobian = jacobian * Transpose(jacobian);
1382
1383 // Apply Levenberg-Marquardt damping: (1 + λ) on diagonal
1384 jacobian_transpose_jacobian.ScaleDiagonal(1.0 + lambda);
1385
1386 // Compute right-hand side: J^T r
1387 CVector jacobian_times_residuals = jacobian * residuals;
1388
1389 // Check for near-singular matrix and add regularization if needed
1390 if (det(jacobian_transpose_jacobian) <= 1e-6)
1391 {
1392 // Add additional regularization: λI
1393 const size_t matrix_size = jacobian_transpose_jacobian.getnumcols();
1394 CMatrix identity = CMatrix::Diag(matrix_size);
1395 jacobian_transpose_jacobian += lambda * identity;
1396 }
1397
1398 // Solve for parameter update: dx = (J^T J)^(-1) J^T r
1399 CVector parameter_update = jacobian_times_residuals / jacobian_transpose_jacobian;
1400
1401 return parameter_update;
1402}
1403
1405{
1406 // Initialize contributions based on parameterization. The starting
1407 // point comes from a stream with a fixed seed, created for each solve,
1408 // so a fit does not depend on what ran before it (it used rand(), whose
1409 // state other analyses changed) and is the same on every platform.
1410 RandomStream starting_point(DefaultRandomSeed);
1411 if (trans == transformation::linear)
1412 InitializeContributionsRandomly(starting_point);
1413 else if (trans == transformation::softmax)
1415
1416 // Algorithm parameters
1417 const double tolerance = 1e-10;
1418 const int max_iterations = 1000;
1419 const double improvement_threshold = 0.8; // Error must reduce to <80% for lambda decrease
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;
1423
1424 // Initialize tracking variables
1425 double lambda = 1.0;
1426 double current_error = ResidualVector().norm2();
1427 double previous_error = 1000.0;
1428 double initial_param_change = 10000.0;
1429 double current_param_change = 10000.0;
1430 int iteration = 0;
1431
1432 // Main optimization loop
1433 while (current_error > tolerance &&
1434 current_param_change > tolerance &&
1435 iteration < max_iterations)
1436 {
1437 // Store current parameter values
1438 CVector current_params;
1439 if (trans == transformation::linear)
1440 current_params = GetContributionVector(false);
1441 else if (trans == transformation::softmax)
1442 current_params = GetContributionVectorSoftmax();
1443
1444 previous_error = current_error;
1445
1446 // Compute parameter update step
1447 CVector parameter_update;
1448 if (trans == transformation::linear)
1449 parameter_update = OneStepLevenberg_Marquardt(lambda);
1450 else if (trans == transformation::softmax)
1451 parameter_update = OneStepLevenberg_Marquardt_softmax(lambda);
1452
1453 // Handle singular Jacobian (no valid update computed)
1454 if (parameter_update.num == 0)
1455 {
1456 lambda *= lambda_no_update_factor;
1457 continue; // Skip to next iteration
1458 }
1459
1460 // Track parameter change magnitude
1461 current_param_change = parameter_update.norm2();
1462 if (iteration == 0)
1463 initial_param_change = current_param_change;
1464
1465 // Apply parameter update
1466 CVector updated_params = current_params - parameter_update;
1467 if (trans == transformation::linear)
1468 SetContribution(updated_params);
1469 else if (trans == transformation::softmax)
1470 SetContributionSoftmax(updated_params);
1471
1472 // Evaluate new error
1473 CVector residuals = ResidualVector();
1474 current_error = residuals.norm2();
1475
1476 // Adaptive lambda adjustment based on error change
1477 if (current_error < previous_error * improvement_threshold)
1478 {
1479 // Good progress: decrease lambda (move toward Gauss-Newton)
1480 lambda /= lambda_decrease_factor;
1481 }
1482 else if (current_error > previous_error)
1483 {
1484 // Error increased: reject step, increase lambda (move toward gradient descent)
1485 lambda *= lambda_increase_factor;
1486
1487 // Restore previous parameters
1488 if (trans == transformation::linear)
1489 SetContribution(current_params);
1490 else if (trans == transformation::softmax)
1491 SetContributionSoftmax(current_params);
1492
1493 current_error = previous_error;
1494 }
1495 // else: modest improvement, keep lambda unchanged
1496
1497 // Update progress visualization if available
1498 if (rtw_)
1499 {
1500 rtw_->AppendPoint(iteration, current_error);
1501 rtw_->SetXRange(0, iteration);
1502 rtw_->SetProgress(1.0 - current_param_change / initial_param_change);
1503 }
1504
1505 iteration++;
1506 }
1507
1508 // The reported fraction approaches 1 without reaching it, because the loop
1509 // exits once the parameter change falls below the tolerance rather than
1510 // when it reaches zero. Report completion explicitly so the display does
1511 // not stop short of the end.
1512 if (rtw_)
1513 rtw_->SetProgress(1.0);
1514
1515 // TODO: Return convergence status instead of always false
1516 return false;
1517}
1518
1519
1521{
1522 // Compute predicted concentrations: C = Source_Matrix × Contribution_Vector
1523 CMatrix source_mean_matrix = BuildSourceMeanMatrix(param_mode);
1524 CVector contribution_vector = GetContributionVector();
1525 CVector predicted_concentrations = source_mean_matrix * contribution_vector;
1526
1527 // Update stored predicted values in observation objects for each element
1528 for (unsigned int i = 0; i < element_order_.size(); i++)
1529 {
1530 observation(i)->SetPredictedValue(predicted_concentrations[i]);
1531 }
1532
1533 return predicted_concentrations;
1534}
1535
1537{
1538 // Compute predicted isotopic concentrations: C = Source_Matrix × Contribution_Vector
1539 CMatrix source_isotope_matrix = BuildSourceMeanMatrix_Isotopes(param_mode);
1540 CVector contribution_vector = GetContributionVector();
1541 CVector predicted_isotope_concentrations = source_isotope_matrix * contribution_vector;
1542
1543 return predicted_isotope_concentrations;
1544}
1545
1547{
1548 CMatrix SourceMeanMat_Iso = BuildSourceMeanMatrix_Isotopes(param_mode);
1549 CVector C = SourceMeanMat_Iso*GetContributionVector();
1550 const CVector contributions = GetContributionVector();
1551 for (unsigned int i=0; i<numberofisotopes_; i++)
1552 {
1553 // The mixture's base element content, from the same source means as
1554 // the isotope's (the base element need not be a tracer itself)
1555 string corresponding_element = element_information_[isotope_order_[i]].base_element;
1556 double predicted_corresponding_element_concentration = 0;
1557 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
1558 predicted_corresponding_element_concentration += contributions[source_idx] *
1559 IsotopeBaseMean(GetSampleSet(samplesetsorder_[source_idx]), corresponding_element, param_mode);
1560 double ratio = C[i]/predicted_corresponding_element_concentration;
1561 double standard_ratio = element_information_[isotope_order_[i]].standard_ratio;
1562 C[i] = (ratio/standard_ratio-1.0)*1000.0;
1563 }
1564 for (unsigned int i=element_order_.size(); i<element_order_.size()+isotope_order_.size(); i++)
1565 {
1567 }
1568 return C;
1569}
1570
1571
1576
1578{
1579 // Initialize likelihood components
1580 double source_data_log_likelihood = 0.0;
1581 double element_observation_log_likelihood = 0.0;
1582 double isotope_observation_log_likelihood = 0.0;
1583
1584 // Component 1: Log-likelihood of source data given estimated distributions
1585 // P(Y | μ, σ) - Only included when estimating source profiles
1586 if (est_mode != estimation_mode::only_contributions) {
1587 source_data_log_likelihood = LogLikelihoodSourceElementalDistributions();
1588 }
1589
1590 // Component 2: Log-prior on contributions
1591 // P(f) - Always included (uniform Dirichlet prior)
1592 double contribution_log_prior = LogPriorContributions();
1593
1594 // Component 3: Log-likelihood of observations given model predictions
1595 // P(C_obs | f, μ, σ) - Only when fitting to target sample
1597 // Elements: log P(C_obs | C_pred)
1598 element_observation_log_likelihood = LogLikelihoodModelvsMeasured(est_mode);
1599
1600 // Isotopes: log P(δ_obs | δ_pred)
1601 isotope_observation_log_likelihood = LogLikelihoodModelvsMeasured_Isotope(est_mode);
1602 }
1603
1604 // Sum all components to get total log-likelihood
1605 double total_log_likelihood = source_data_log_likelihood +
1606 element_observation_log_likelihood +
1607 isotope_observation_log_likelihood +
1608 contribution_log_prior;
1609
1610 return total_log_likelihood;
1611}
1612
1614{
1615 const size_t num_elements = element_order_.size();
1616 const size_t num_sources = numberofsourcesamplesets_;
1617
1618 // Initialize source mean matrix: rows = elements, cols = sources
1619 // Matrix entry [i,j] = mean concentration of element i in source j
1620 CMatrix source_means(num_elements, num_sources);
1621
1622 // Fill matrix with mean concentrations for each element and source
1623 for (size_t element_idx = 0; element_idx < num_elements; element_idx++)
1624 {
1625 const string& element_name = element_order_[element_idx];
1626
1627 for (size_t source_idx = 0; source_idx < num_sources; source_idx++)
1628 {
1629 const string& source_name = samplesetsorder_[source_idx];
1630 Elemental_Profile_Set* source_group = GetSampleSet(source_name);
1631
1632 // Get estimated distribution for this element in this source
1633 Distribution* element_dist = source_group->GetEstimatedDistribution(element_name);
1634
1635 // Calculate mean based on parameter mode
1637 // Parametric mean from distribution parameters (μ, σ)
1638 // For lognormal: Mean = exp(μ + σ²/2)
1639 source_means[element_idx][source_idx] = element_dist->Mean();
1640 }
1641 else {
1642 // Empirical mean calculated directly from data points
1643 source_means[element_idx][source_idx] = element_dist->DataMean();
1644 }
1645 }
1646 }
1647
1648 return source_means;
1649}
1650
1651double SourceSinkData::IsotopeBaseMean(Elemental_Profile_Set* source_group, const string& base_element, parameter_mode param_mode)
1652{
1653 // A base element that is a tracer has an estimated distribution, which the
1654 // Bayesian analysis updates. One that is not (the organic matter
1655 // constituent, e.g. TOC for delta 13C) is taken as known from the source
1656 // samples: its distribution fitted to the data.
1657 const bool is_tracer = lookup(element_order_, base_element) != -1;
1658 Distribution* distribution = is_tracer ? source_group->GetEstimatedDistribution(base_element)
1659 : source_group->GetFittedDistribution(base_element);
1660 if (distribution == nullptr)
1661 return NAN;
1662 return (param_mode == parameter_mode::based_on_fitted_distribution) ? distribution->Mean() : distribution->DataMean();
1663}
1664
1666{
1667 const size_t num_isotopes = isotope_order_.size();
1668 const size_t num_sources = numberofsourcesamplesets_;
1669
1670 // Initialize source isotope matrix: rows = isotopes, cols = sources
1671 // Matrix entry [i,j] = mean absolute concentration of isotope i in source j
1672 CMatrix source_isotope_means(num_isotopes, num_sources);
1673
1674 // Fill matrix with mean isotope concentrations (converted from delta)
1675 for (size_t isotope_idx = 0; isotope_idx < num_isotopes; isotope_idx++)
1676 {
1677 const string& isotope_name = isotope_order_[isotope_idx];
1678 const element_information& isotope_info = element_information_[isotope_name];
1679 const string& base_element = isotope_info.base_element;
1680 const double standard_ratio = isotope_info.standard_ratio;
1681
1682 for (size_t source_idx = 0; source_idx < num_sources; source_idx++)
1683 {
1684 const string& source_name = samplesetsorder_[source_idx];
1685 Elemental_Profile_Set* source_group = GetSampleSet(source_name);
1686
1687 // Get distributions for isotope and its base element
1688 Distribution* isotope_dist = source_group->GetEstimatedDistribution(isotope_name);
1689
1690 // Retrieve mean values based on parameter mode
1691 double mean_delta = NAN;
1692 const double mean_base_concentration = IsotopeBaseMean(source_group, base_element, param_mode);
1693
1695 // Use parametric means from fitted distributions
1696 mean_delta = isotope_dist->Mean();
1697 }
1698 else {
1699 // Use empirical means from actual data
1700 mean_delta = isotope_dist->DataMean();
1701 }
1702
1703 // Convert delta notation to absolute concentration
1704 // Formula: [isotope] = (δ/1000 + 1) × R_standard × [base_element]
1705 double delta_ratio = (mean_delta / 1000.0) + 1.0;
1706 double absolute_isotope_concentration = delta_ratio * standard_ratio * mean_base_concentration;
1707
1708 source_isotope_means[isotope_idx][source_idx] = absolute_isotope_concentration;
1709 }
1710 }
1711
1712 return source_isotope_means;
1713}
1714
1716{
1717 // Determine vector size based on whether to include constrained contribution
1718 const size_t num_contributions = include_all ?
1721
1722 CVector contributions(num_contributions);
1723
1724 // Retrieve contribution values from each source group
1725 for (size_t source_idx = 0; source_idx < num_contributions; source_idx++)
1726 {
1727 const string& source_name = samplesetsorder_[source_idx];
1728 Elemental_Profile_Set* source_group = GetSampleSet(source_name);
1729 contributions[source_idx] = source_group->GetContribution();
1730 }
1731
1732 return contributions;
1733}
1734
1736{
1737 const size_t num_sources = numberofsourcesamplesets_;
1738 CVector softmax_parameters(num_sources);
1739
1740 // Retrieve softmax parameter values from each source group
1741 for (size_t source_idx = 0; source_idx < num_sources; source_idx++)
1742 {
1743 const string& source_name = samplesetsorder_[source_idx];
1744 Elemental_Profile_Set* source_group = GetSampleSet(source_name);
1745 softmax_parameters[source_idx] = source_group->GetContributionSoftmax();
1746 }
1747
1748 return softmax_parameters;
1749}
1750
1751
1752
1753
1754void SourceSinkData::SetContribution(size_t source_index, double contribution_value)
1755{
1756 // Set the specified contribution
1757 const string& source_name = samplesetsorder_[source_index];
1758 GetSampleSet(source_name)->SetContribution(contribution_value);
1759
1760 // Update last contribution to maintain sum constraint
1761 const size_t last_source_index = samplesetsorder_.size() - 1;
1762 const string& last_source_name = samplesetsorder_[last_source_index];
1763
1764 // Calculate constrained contribution: c_last = 1 - Σ(c_i)
1765 double sum_of_independent = GetContributionVector(false).sum();
1766 double constrained_contribution = 1.0 - sum_of_independent;
1767
1768 GetSampleSet(last_source_name)->SetContribution(constrained_contribution);
1769}
1770
1771void SourceSinkData::SetContributionSoftmax(size_t source_index, double softmax_value)
1772{
1773 // Set softmax parameter (no constraint to maintain)
1774 const string& source_name = samplesetsorder_[source_index];
1775 GetSampleSet(source_name)->SetContributionSoftmax(softmax_value);
1776}
1777
1778void SourceSinkData::SetContribution(const CVector& contributions)
1779{
1780 // Set each contribution (last contribution updated automatically each time)
1781 for (size_t i = 0; i < static_cast<size_t>(contributions.num); i++)
1782 {
1783 SetContribution(i, contributions.vec[i]);
1784 }
1785
1786 // Validate: all contributions should be non-negative
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;
1790 }
1791}
1792
1793void SourceSinkData::SetContributionSoftmax(const CVector& softmax_params)
1794{
1795 // Compute softmax normalization denominator: Σ exp(x_i)
1796 double denominator = 0.0;
1797 for (size_t i = 0; i < static_cast<size_t>(softmax_params.num); i++)
1798 {
1799 denominator += exp(softmax_params[i]);
1800 }
1801
1802 // Apply softmax transformation: c_i = exp(x_i) / Σ exp(x_j)
1803 for (size_t i = 0; i < static_cast<size_t>(softmax_params.num); i++)
1804 {
1805 double softmax_param = softmax_params.at(i);
1806 double contribution = exp(softmax_param) / denominator;
1807
1808 // Set both softmax parameter and computed contribution
1809 SetContributionSoftmax(i, softmax_param);
1811 }
1812
1813 // Validate: resulting contributions should be valid
1814 CVector resulting_contributions = GetContributionVector();
1815 if (resulting_contributions.min() < -1e-12) { // not round-off (about -2e-16)
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;
1819 }
1820}
1821
1823 size_t element_index,
1824 size_t source_index)
1825{
1826 // Parameter vector layout:
1827 // [0 to n-2]: Contribution parameters (n-1 independent contributions)
1828 // [n-1 onwards]: Element μ parameters
1829
1830 const size_t num_contribution_params = size() - 1; // Exclude target group
1831 const size_t element_mu_base_index = num_contribution_params;
1832
1833 // Calculate index for this element's μ in this source
1834 // Elements are stored in blocks: all sources for element 0, then all sources for element 1, etc.
1835 const size_t parameter_index = element_mu_base_index +
1836 (element_index * numberofsourcesamplesets_) +
1837 source_index;
1838
1839 // Bounds check
1840 if (parameter_index >= parameters_.size()) {
1841 std::cerr << "Error: Parameter index out of bounds in GetElementDistributionMuParameter" << std::endl;
1842 return nullptr;
1843 }
1844
1845 return &parameters_[parameter_index];
1846}
1847
1849 size_t element_index,
1850 size_t source_index)
1851{
1852 // Parameter vector layout:
1853 // [0 to n-2]: Contribution parameters
1854 // [n-1 to n-1 + num_elements × num_sources - 1]: Element μ parameters
1855 // [next block]: Element σ parameters ← We're here
1856
1857 const size_t num_contribution_params = size() - 1;
1858 const size_t num_element_mu_params = static_cast<size_t>(numberofconstituents_) * numberofsourcesamplesets_;
1859 const size_t element_sigma_base_index = num_contribution_params + num_element_mu_params;
1860
1861 // Calculate index for this element's σ in this source
1862 const size_t parameter_index = element_sigma_base_index +
1863 (element_index * numberofsourcesamplesets_) +
1864 source_index;
1865
1866 // Bounds check
1867 if (parameter_index >= parameters_.size()) {
1868 std::cerr << "Error: Parameter index out of bounds in GetElementDistributionSigmaParameter" << std::endl;
1869 return nullptr;
1870 }
1871
1872 return &parameters_[parameter_index];
1873}
1874
1876 size_t element_index,
1877 size_t source_index)
1878{
1879 Parameter* mu_param = GetElementDistributionMuParameter(element_index, source_index);
1880
1881 if (mu_param == nullptr) {
1882 std::cerr << "Warning: Unable to retrieve μ parameter for element "
1883 << element_index << ", source " << source_index << std::endl;
1884 return 0.0;
1885 }
1886
1887 return mu_param->Value();
1888}
1889
1891 size_t element_index,
1892 size_t source_index)
1893{
1894 Parameter* sigma_param = GetElementDistributionSigmaParameter(element_index, source_index);
1895
1896 if (sigma_param == nullptr) {
1897 std::cerr << "Warning: Unable to retrieve σ parameter for element "
1898 << element_index << ", source " << source_index << std::endl;
1899 return 0.0;
1900 }
1901
1902 return sigma_param->Value();
1903}
1904
1905bool SourceSinkData::SetParameterValue(size_t index, double value)
1906{
1907 // Validate index
1908 if (index >= parameters_.size()) {
1909 return false;
1910 }
1911
1912 // Determine which parameter blocks are active based on estimation mode
1913 const bool estimating_contributions =
1915 const bool estimating_profiles =
1917
1918 // Calculate parameter block boundaries
1919 const size_t num_contribution_params = estimating_contributions ? (numberofsourcesamplesets_ - 1) : 0;
1920 const size_t num_element_mu_params = static_cast<size_t>(numberofconstituents_) * numberofsourcesamplesets_;
1921 const size_t num_isotope_mu_params = static_cast<size_t>(numberofisotopes_) * numberofsourcesamplesets_;
1922 const size_t num_element_sigma_params = num_element_mu_params;
1923 const size_t num_isotope_sigma_params = num_isotope_mu_params;
1924
1925 // Update parameter value
1926 parameters_[index].SetValue(value);
1927
1928 // ========== Block 1: Contribution Parameters ==========
1929 if (estimating_contributions && index < num_contribution_params)
1930 {
1931 // Update this source's contribution
1933
1934 // Update last contribution to maintain sum constraint: c_n = 1 - Σ(c_1...c_{n-1})
1935 const size_t last_source_index = numberofsourcesamplesets_ - 1;
1936 double sum_of_independent = GetContributionVector(false).sum();
1937 GetSampleSet(samplesetsorder_[last_source_index])->SetContribution(1.0 - sum_of_independent);
1938
1939 return true;
1940 }
1941
1942 // ========== Block 2: Element μ Parameters ==========
1943 size_t element_mu_start = num_contribution_params;
1944 size_t element_mu_end = element_mu_start + num_element_mu_params;
1945
1946 if (estimating_profiles &&
1948 index >= element_mu_start && index < element_mu_end)
1949 {
1950 size_t offset = index - element_mu_start;
1951 size_t element_index = offset / numberofsourcesamplesets_;
1952 size_t source_index = offset % numberofsourcesamplesets_;
1953
1954 GetElementDistribution(element_order_[element_index], samplesetsorder_[source_index])
1955 ->SetEstimatedMu(value);
1956
1957 return true;
1958 }
1959
1960 // ========== Block 3: Isotope μ Parameters ==========
1961 size_t isotope_mu_start = element_mu_end;
1962 size_t isotope_mu_end = isotope_mu_start + num_isotope_mu_params;
1963
1964 if (estimating_profiles &&
1966 index >= isotope_mu_start && index < isotope_mu_end)
1967 {
1968 size_t offset = index - isotope_mu_start;
1969 size_t isotope_index = offset / numberofsourcesamplesets_;
1970 size_t source_index = offset % numberofsourcesamplesets_;
1971
1972 GetElementDistribution(isotope_order_[isotope_index], samplesetsorder_[source_index])
1973 ->SetEstimatedMu(value);
1974
1975 return true;
1976 }
1977
1978 // ========== Block 4: Element σ Parameters ==========
1979 size_t element_sigma_start = isotope_mu_end;
1980 size_t element_sigma_end = element_sigma_start + num_element_sigma_params;
1981
1982 if (estimating_profiles &&
1984 index >= element_sigma_start && index < element_sigma_end)
1985 {
1986 if (value < 0.0) {
1987 std::cerr << "Error: Element σ parameter cannot be negative (value = "
1988 << value << ")" << std::endl;
1989 return false;
1990 }
1991
1992 size_t offset = index - element_sigma_start;
1993 size_t element_index = offset / numberofsourcesamplesets_;
1994 size_t source_index = offset % numberofsourcesamplesets_;
1995
1996 GetElementDistribution(element_order_[element_index], samplesetsorder_[source_index])
1997 ->SetEstimatedSigma(value);
1998
1999 return true;
2000 }
2001
2002 // ========== Block 5: Isotope σ Parameters ==========
2003 size_t isotope_sigma_start = element_sigma_end;
2004 size_t isotope_sigma_end = isotope_sigma_start + num_isotope_sigma_params;
2005
2006 if (estimating_profiles &&
2008 index >= isotope_sigma_start && index < isotope_sigma_end)
2009 {
2010 if (value < 0.0) {
2011 std::cerr << "Error: Isotope σ parameter cannot be negative (value = "
2012 << value << ")" << std::endl;
2013 return false;
2014 }
2015
2016 size_t offset = index - isotope_sigma_start;
2017 size_t isotope_index = offset / numberofsourcesamplesets_;
2018 size_t source_index = offset % numberofsourcesamplesets_;
2019
2020 GetElementDistribution(isotope_order_[isotope_index], samplesetsorder_[source_index])
2021 ->SetEstimatedSigma(value);
2022
2023 return true;
2024 }
2025
2026 // ========== Block 6: Element Error Standard Deviation ==========
2027 size_t error_element_index = isotope_sigma_end;
2028
2029 if (estimating_contributions && index == error_element_index)
2030 {
2031 if (value < 0.0) {
2032 std::cerr << "Error: Element error std dev cannot be negative (value = "
2033 << value << ")" << std::endl;
2034 return false;
2035 }
2036
2037 error_stdev_ = value;
2038 return true;
2039 }
2040
2041 // ========== Block 7: Isotope Error Standard Deviation ==========
2042 size_t error_isotope_index = error_element_index + 1;
2043
2044 if (estimating_contributions && index == error_isotope_index)
2045 {
2046 if (value < 0.0) {
2047 std::cerr << "Error: Isotope error std dev cannot be negative (value = "
2048 << value << ")" << std::endl;
2049 return false;
2050 }
2051
2052 error_stdev_isotope_ = value;
2053 return true;
2054 }
2055
2056 // If we reach here, index doesn't match any known parameter block
2057 std::cerr << "Warning: Parameter index " << index << " not recognized" << std::endl;
2058 return false;
2059}
2060
2061double SourceSinkData::GetParameterValue(size_t index) const
2062{
2063 return parameters_[index].Value();
2064}
2065
2066bool SourceSinkData::SetParameterValue(const CVector& values)
2067{
2068 bool all_successful = true;
2069
2070 // Update each parameter sequentially
2071 for (size_t i = 0; i < static_cast<size_t>(values.num); i++)
2072 {
2073 bool success = SetParameterValue(i, values[i]);
2074 all_successful &= success;
2075
2076 // Note: Continue even if one fails to attempt all updates
2077 }
2078
2079 return all_successful;
2080}
2081
2083{
2084 CVector parameter_values(parameters_.size());
2085
2086 // Extract value from each parameter
2087 for (size_t i = 0; i < parameters_.size(); i++)
2088 {
2089 parameter_values[i] = parameters_[i].Value();
2090 }
2091
2092 return parameter_values;
2093}
2094
2095CVector SourceSinkData::Gradient(const CVector& parameters, estimation_mode est_mode)
2096{
2097 CVector gradient(parameters.num);
2098 CVector perturbed_params = parameters;
2099
2100 // Set base parameters and evaluate baseline log-likelihood
2101 SetParameterValue(parameters);
2102 double baseline_log_likelihood = LogLikelihood(est_mode);
2103
2104 // Compute partial derivative for each parameter using finite differences
2105 for (size_t i = 0; i < static_cast<size_t>(parameters.num); i++)
2106 {
2107 // Perturb parameter i by epsilon
2108 perturbed_params[i] += epsilon_;
2109 SetParameterValue(perturbed_params);
2110
2111 // Evaluate log-likelihood at perturbed point
2112 double perturbed_log_likelihood = LogLikelihood(est_mode);
2113
2114 // Compute numerical derivative: ∂log(L)/∂θ_i ≈ Δlog(L) / Δθ_i
2115 gradient[i] = (perturbed_log_likelihood - baseline_log_likelihood) / epsilon_;
2116
2117 // Restore parameter for next iteration
2118 perturbed_params[i] = parameters[i];
2119 }
2120
2121 // Normalize gradient to unit length for numerical stability
2122 return gradient / gradient.norm2();
2123}
2124
2126{
2127 // Get current parameters and evaluate baseline likelihood
2128 CVector current_params = GetParameterValue();
2129 double baseline_likelihood = LogLikelihood(est_mode);
2130
2131 // Compute normalized gradient direction
2132 CVector gradient_direction = Gradient(current_params, est_mode);
2133
2134 // Try two candidate steps: standard and aggressive (2×)
2135 CVector candidate_step1 = current_params + distance_coeff_ * gradient_direction;
2136 SetParameterValue(candidate_step1);
2137 double likelihood_step1 = LogLikelihood(est_mode);
2138
2139 CVector candidate_step2 = current_params + 2.0 * distance_coeff_ * gradient_direction;
2140 SetParameterValue(candidate_step2);
2141 double likelihood_step2 = LogLikelihood(est_mode);
2142
2143 // Debug output
2144 std::cout << "Distance Coefficient: " << distance_coeff_ << std::endl;
2145
2146 // Reset step size if it becomes too small
2147 if (distance_coeff_ < 1e-6) {
2148 distance_coeff_ = 1.0;
2149 }
2150
2151 // ========== Strategy 1: Aggressive step (2×) is best ==========
2152 if (likelihood_step2 > likelihood_step1 && likelihood_step2 > baseline_likelihood)
2153 {
2154 // Success with larger step - increase step size for next iteration
2155 distance_coeff_ *= 2.0;
2156 return candidate_step2;
2157 }
2158
2159 // ========== Strategy 2: Standard step (1×) is best ==========
2160 else if (likelihood_step1 > likelihood_step2 && likelihood_step1 > baseline_likelihood)
2161 {
2162 // Success with standard step - keep current step size
2163 SetParameterValue(candidate_step1);
2164 return candidate_step1;
2165 }
2166
2167 // ========== Strategy 3: Neither improved - backtrack ==========
2168 else
2169 {
2170 const int max_backtrack_iterations = 5;
2171 int backtrack_count = 0;
2172
2173 // Progressively reduce step size until we find improvement
2174 while (baseline_likelihood >= likelihood_step1 && backtrack_count < max_backtrack_iterations)
2175 {
2176 distance_coeff_ *= 0.5; // Halve the step size
2177
2178 candidate_step1 = current_params + distance_coeff_ * gradient_direction;
2179 SetParameterValue(candidate_step1);
2180 likelihood_step1 = LogLikelihood(est_mode);
2181
2182 backtrack_count++;
2183 }
2184
2185 if (backtrack_count < max_backtrack_iterations)
2186 {
2187 // Found an improvement with smaller step
2188 SetParameterValue(candidate_step1);
2189 return candidate_step1;
2190 }
2191 else
2192 {
2193 // No improvement found after backtracking - return to original
2194 std::cerr << "Warning: No improvement found after " << max_backtrack_iterations
2195 << " backtracking iterations" << std::endl;
2196 SetParameterValue(current_params);
2197 return current_params;
2198 }
2199 }
2200}
2201
2203{
2204 // Reset counters and ordering
2206 constituent_order_.clear();
2207
2208 // Collect all chemical elements (exclude isotopes, size, organic carbon)
2209 for (const auto& [element_name, elem_info] : element_information_)
2210 {
2211 if (elem_info.Role == element_information::role::element)
2212 {
2214 constituent_order_.push_back(element_name);
2215 }
2216 }
2217
2218 return constituent_order_;
2219}
2220
2222{
2223 // Reset counters and ordering
2225 isotope_order_.clear();
2226
2227 // Collect isotopes marked for inclusion in analysis
2228 for (const auto& [element_name, elem_info] : element_information_)
2229 {
2230 if (elem_info.Role == element_information::role::isotope &&
2231 elem_info.include_in_analysis)
2232 {
2234 isotope_order_.push_back(element_name);
2235 }
2236 }
2237
2238 return isotope_order_;
2239}
2241{
2242 vector<string> problems;
2243 for (const auto& [isotope_name, isotope_info] : element_information_)
2244 {
2245 if (isotope_info.Role != element_information::role::isotope || !isotope_info.include_in_analysis)
2246 continue;
2247
2248 const string& base = isotope_info.base_element;
2249 const auto base_info = element_information_.find(base);
2250 if (base.empty())
2251 problems.push_back("Isotope '" + isotope_name + "' has no base element.");
2252 else if (base_info == element_information_.end())
2253 problems.push_back("The base element '" + base + "' of isotope '" + isotope_name + "' is not in the data.");
2254 // The base element is an element included in the analysis, or the
2255 // organic matter constituent (the carbon content for delta 13C)
2256 else if (base_info->second.Role == element_information::role::organic_carbon)
2257 continue;
2258 else if (base_info->second.Role != element_information::role::element)
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.");
2262 }
2263 return problems;
2264}
2265
2267{
2268 // Reset all counters and ordering vectors
2270 constituent_order_.clear();
2271 element_order_.clear();
2272 size_om_order_.clear();
2273 isotope_order_.clear();
2274
2275 // Pass 1: Collect ALL constituents (elements, isotopes, metadata)
2276 for (const auto& [constituent_name, constituent_info] : element_information_)
2277 {
2279 constituent_order_.push_back(constituent_name);
2280 }
2281
2282 // Pass 2: Collect chemical elements included in analysis
2283 for (const auto& [element_name, elem_info] : element_information_)
2284 {
2285 if (elem_info.Role == element_information::role::element &&
2286 elem_info.include_in_analysis)
2287 {
2288 element_order_.push_back(element_name);
2289 }
2290 }
2291
2292 // Pass 3: Collect isotopes included in analysis
2293 for (const auto& [isotope_name, elem_info] : element_information_)
2294 {
2295 if (elem_info.Role == element_information::role::isotope &&
2296 elem_info.include_in_analysis)
2297 {
2298 isotope_order_.push_back(isotope_name);
2299 }
2300 }
2301
2302 // Pass 4: Collect particle size parameters
2303 for (const auto& [param_name, elem_info] : element_information_)
2304 {
2305 if (elem_info.Role == element_information::role::particle_size)
2306 {
2307 size_om_order_.push_back(param_name);
2308 }
2309 }
2310
2311 // Pass 5: Collect organic carbon parameters
2312 for (const auto& [param_name, elem_info] : element_information_)
2313 {
2314 if (elem_info.Role == element_information::role::organic_carbon)
2315 {
2316 size_om_order_.push_back(param_name);
2317 }
2318 }
2319}
2321{
2322 vector<string> source_names;
2323
2324 // Collect all group names except the target
2325 for (const auto& [group_name, profile_set] : *this)
2326 {
2327 if (group_name != target_group_)
2328 {
2329 source_names.push_back(group_name);
2330 }
2331 }
2332
2333 return source_names;
2334}
2335
2337{
2338 // Search all groups for the specified sample
2339 for (auto& [group_name, profile_set] : *this)
2340 {
2341 // Search within this group's samples
2342 for (const auto& [profile_name, profile] : profile_set)
2343 {
2344 if (profile_name == sample_name)
2345 {
2346 // Found it - return pointer to the profile
2347 return profile_set.GetProfile(profile_name);
2348 }
2349 }
2350 }
2351
2352 // Sample not found in any group
2353 return nullptr;
2354}
2355
2357{
2358 ResultItem result;
2359 Contribution* contributions = new Contribution();
2360
2361 // Package contribution values with source names
2362 vector<string> source_order = GetSourceOrder();
2363 CVector contribution_values = GetContributionVector();
2364
2365 for (size_t i = 0; i < source_order.size(); i++)
2366 {
2367 (*contributions)[source_order[i]] = contribution_values[i];
2368 }
2369
2370 // Configure result item
2371 result.SetName("Contributions");
2372 result.SetResult(contributions);
2374
2375 return result;
2376}
2377
2379{
2380 ResultItem result;
2381 Elemental_Profile* predicted_profile = new Elemental_Profile();
2382
2383 // Compute predicted concentrations using mixing model
2384 CVector predicted_concentrations = PredictTarget(param_mode);
2385 vector<string> element_names = ElementOrder();
2386
2387 // Package predictions into elemental profile
2388 for (size_t i = 0; i < element_names.size(); i++)
2389 {
2390 predicted_profile->AppendElement(element_names[i], predicted_concentrations[i]);
2391 }
2392
2393 // Configure result item
2394 result.SetName("Modeled Elemental Profile");
2395 result.SetResult(predicted_profile);
2397
2398 return result;
2399}
2400
2402{
2403 const size_t num_observations = ObservationsCount();
2404 CVector predicted_values(num_observations);
2405
2406 // Collect predicted value from each observation
2407 for (size_t i = 0; i < num_observations; i++)
2408 {
2409 predicted_values[i] = observation(i)->PredictedValue();
2410 }
2411
2412 return predicted_values;
2413}
2414
2416{
2417 ResultItem result;
2418 Elemental_Profile* predicted_isotopes = new Elemental_Profile();
2419
2420 // Compute predicted delta values using mixing model
2421 CVector predicted_delta_values = PredictTarget_Isotope_delta(param_mode);
2422 vector<string> isotope_names = IsotopeOrder();
2423
2424 // Package predictions into elemental profile
2425 for (size_t i = 0; i < isotope_names.size(); i++)
2426 {
2427 predicted_isotopes->AppendElement(isotope_names[i], predicted_delta_values[i]);
2428 }
2429
2430 // Configure result item
2431 result.SetName("Modeled Elemental Profile for Isotopes");
2432 result.SetResult(predicted_isotopes);
2434
2435 return result;
2436}
2437
2439{
2440 ResultItem result;
2441
2442 // Get predicted and observed profiles
2443 Elemental_Profile* predicted = static_cast<Elemental_Profile*>(
2445 );
2446 Elemental_Profile* observed = static_cast<Elemental_Profile*>(
2448 );
2449
2450 // Create comparison profile set
2451 Elemental_Profile_Set* comparison = new Elemental_Profile_Set();
2452 comparison->AppendProfile("Observed", *observed);
2453 comparison->AppendProfile("Modeled", *predicted);
2454
2455 // Configure result item
2456 result.SetName("Observed vs Modeled Elemental Profile");
2457 result.SetResult(comparison);
2459
2460 return result;
2461}
2462
2464{
2465 vector<ResultItem> mlr_results;
2466
2467 // Collect regression results from each sample group
2468 for (auto& [group_name, profile_set] : *this)
2469 {
2470 // Get MLR models for this group
2471 ResultItem regression_result = profile_set.GetRegressionsAsResult();
2472
2473 // Configure for display
2474 regression_result.SetShowTable(true);
2475 regression_result.SetName("OM & Size MLR for " + group_name);
2476
2477 mlr_results.push_back(regression_result);
2478 }
2479
2480 return mlr_results;
2481}
2482
2484{
2485 ResultItem result;
2486
2487 // Get predicted and observed isotope profiles
2488 Elemental_Profile* predicted = static_cast<Elemental_Profile*>(
2490 );
2491 Elemental_Profile* observed = static_cast<Elemental_Profile*>(
2493 );
2494
2495 // Create comparison profile set
2496 Elemental_Profile_Set* comparison = new Elemental_Profile_Set();
2497 comparison->AppendProfile("Observed", *observed);
2498 comparison->AppendProfile("Modeled", *predicted);
2499
2500 // Configure result item
2501 result.SetName("Observed vs Modeled Elemental Profile for Isotopes");
2502 result.SetResult(comparison);
2504
2505 return result;
2506}
2507
2509{
2510 ResultItem result;
2511 Elemental_Profile* observed_profile = new Elemental_Profile();
2512
2513 // Retrieve observed concentrations for selected target sample
2514 CVector observed_concentrations = ObservedDataforSelectedSample(selected_target_sample_);
2515 vector<string> element_names = ElementOrder();
2516
2517 // Package observations into elemental profile
2518 for (size_t i = 0; i < element_names.size(); i++)
2519 {
2520 observed_profile->AppendElement(element_names[i], observed_concentrations[i]);
2521 }
2522
2523 // Configure result item
2524 result.SetName("Observed Elemental Profile");
2525 result.SetResult(observed_profile);
2527
2528 return result;
2529}
2530
2532{
2533 ResultItem result;
2534 Elemental_Profile* observed_isotopes = new Elemental_Profile();
2535
2536 // Retrieve observed delta values for selected target sample
2538 vector<string> isotope_names = IsotopeOrder();
2539
2540 // Package observations into elemental profile
2541 for (size_t i = 0; i < isotope_names.size(); i++)
2542 {
2543 observed_isotopes->AppendElement(isotope_names[i], observed_delta_values[i]);
2544 }
2545
2546 // Configure result item
2547 result.SetName("Observed Elemental Profile for Isotopes");
2548 result.SetResult(observed_isotopes);
2550
2551 return result;
2552}
2553
2555{
2556 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2557
2558 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2559 {
2560 if (it->first != target_group_)
2561 {
2562 Elemental_Profile element_profile;
2563 for (unsigned int element_counter = 0; element_counter < element_order_.size(); element_counter++)
2564 {
2565 element_profile.AppendElement(element_order_[element_counter], it->second.GetElementDistribution(element_order_[element_counter])->CalculateMean());
2566 }
2567 profile_set->AppendProfile(it->first, element_profile);
2568 }
2569 }
2570
2571 ResultItem resitem;
2572 resitem.SetName("Calculated mean elemental contents");
2574 resitem.SetResult(profile_set);
2575 return resitem;
2576}
2577
2579{
2580 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2581
2582 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2583 {
2584 if (it->first != target_group_)
2585 {
2586 Elemental_Profile element_profile;
2587 for (unsigned int element_counter = 0; element_counter < element_order_.size(); element_counter++)
2588 {
2589 if (it->second.GetElementDistribution(element_order_[element_counter])->GetEstimatedDistribution()->distribution == distribution_type::normal)
2590 element_profile.AppendElement(element_order_[element_counter], it->second.GetElementDistribution(element_order_[element_counter])->CalculateStdDev());
2591 else if (it->second.GetElementDistribution(element_order_[element_counter])->GetEstimatedDistribution()->distribution == distribution_type::lognormal)
2592 element_profile.AppendElement(element_order_[element_counter], it->second.GetElementDistribution(element_order_[element_counter])->CalculateStdDevLog());
2593 }
2594 profile_set->AppendProfile(it->first, element_profile);
2595 }
2596 }
2597
2598 ResultItem resitem;
2599 resitem.SetName("Calculated elemental contents standard deviations");
2601 resitem.SetResult(profile_set);
2602 return resitem;
2603}
2604
2605
2607{
2608 vector<ResultItem> source_profile_results;
2609
2610 // Package elemental profiles for each source group
2611 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2612 {
2613 // Skip target group - only process sources
2614 if (it->first != target_group_)
2615 {
2616 // Create and configure result item for this source
2617 ResultItem result_item;
2618 result_item.SetName("Elemental Profiles for " + it->first);
2619 result_item.SetShowAsString(true);
2620 result_item.SetShowTable(true);
2621 result_item.SetShowGraph(true);
2623
2624 // Copy profile set for this source
2625 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2626 *profile_set = it->second;
2627 result_item.SetResult(profile_set);
2628
2629 source_profile_results.push_back(result_item);
2630 }
2631 }
2632
2633 return source_profile_results;
2634}
2635
2636
2638{
2639 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2640
2641 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2642 {
2643 if (it->first != target_group_)
2644 {
2645 Elemental_Profile element_profile;
2646 for (unsigned int element_counter = 0; element_counter < element_order_.size(); element_counter++)
2647 {
2648 element_profile.AppendElement(element_order_[element_counter], it->second.GetElementDistribution(element_order_[element_counter])->CalculateMeanLog());
2649 }
2650 profile_set->AppendProfile(it->first, element_profile);
2651 }
2652 }
2653
2654 ResultItem resitem;
2655 resitem.SetName("Calculated mu parameter of elemental contents");
2657 resitem.SetResult(profile_set);
2658 return resitem;
2659}
2660
2662{
2663 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2664
2665 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2666 {
2667 if (it->first != target_group_)
2668 {
2669 Elemental_Profile element_profile;
2670 for (unsigned int element_counter = 0; element_counter < element_order_.size(); element_counter++)
2671 {
2672 element_profile.AppendElement(element_order_[element_counter], it->second.GetElementDistribution(element_order_[element_counter])->GetEstimatedMu());
2673 }
2674 profile_set->AppendProfile(it->first, element_profile);
2675 }
2676 }
2677
2678 ResultItem resitem;
2679 resitem.SetName("Infered mu parameter elemental contents");
2681 resitem.SetResult(profile_set);
2682 return resitem;
2683}
2684
2686{
2687 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2688
2689 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2690 {
2691 if (it->first != target_group_)
2692 {
2693 Elemental_Profile element_profile;
2694 for (unsigned int element_counter = 0; element_counter < element_order_.size(); element_counter++)
2695 {
2696 double sigma = it->second.GetElementDistribution(element_order_[element_counter])->GetEstimatedSigma();
2697 double mu = it->second.GetElementDistribution(element_order_[element_counter])->GetEstimatedMu();
2698 element_profile.AppendElement(element_order_[element_counter], exp(mu + pow(sigma, 2) / 2));
2699 }
2700 profile_set->AppendProfile(it->first, element_profile);
2701 }
2702 }
2703
2704 ResultItem resitem;
2705 resitem.SetName("Infered mean of elemental contents");
2707 resitem.SetResult(profile_set);
2708 return resitem;
2709}
2710
2712{
2713 Elemental_Profile_Set* profile_set = new Elemental_Profile_Set();
2714
2715 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2716 {
2717 if (it->first != target_group_)
2718 {
2719 Elemental_Profile element_profile;
2720 for (unsigned int element_counter = 0; element_counter < element_order_.size(); element_counter++)
2721 {
2722 double sigma = it->second.GetElementDistribution(element_order_[element_counter])->GetEstimatedSigma();
2723 element_profile.AppendElement(element_order_[element_counter], sigma);
2724 }
2725 profile_set->AppendProfile(it->first, element_profile);
2726 }
2727 }
2728
2729 ResultItem resitem;
2730 resitem.SetName("Infered sigma parameter");
2732 resitem.SetResult(profile_set);
2733 return resitem;
2734}
2735
2736
2737
2739{
2740 QJsonArray tools_used_json_array;
2741
2742 // Serialize each tool name
2743 for (list<string>::const_iterator it = tools_used_.cbegin(); it != tools_used_.cend(); it++)
2744 {
2745 tools_used_json_array.append(QString::fromStdString(*it));
2746 }
2747
2748 return tools_used_json_array;
2749}
2750
2752{
2753 QJsonObject json_object;
2754
2755 // Serialize each option name-value pair
2756 for (QMap<QString, double>::const_iterator it = options_.cbegin(); it != options_.cend(); it++)
2757 {
2758 json_object[it.key()] = it.value();
2759 }
2760
2761 return json_object;
2762}
2763
2764void SourceSinkData::AddtoToolsUsed(const string& tool)
2765{
2766 // Only add if not already present
2767 if (!ToolsUsed(tool))
2768 {
2769 tools_used_.push_back(tool);
2770 }
2771}
2772
2773bool SourceSinkData::ReadToolsUsedFromJsonObject(const QJsonArray& jsonarray)
2774{
2775 // Deserialize each tool name
2776 foreach (const QJsonValue& value, jsonarray)
2777 {
2778 AddtoToolsUsed(value.toString().toStdString());
2779 }
2780
2781 return true;
2782}
2783
2785{
2786 // Clear existing element information
2787 element_information_.clear();
2788
2789 // Deserialize metadata for each element
2790 for (const QString& key : jsonobject.keys())
2791 {
2792 element_information elem_info;
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();
2796 elem_info.include_in_analysis = jsonobject[key].toObject()["Include"].toBool();
2797 elem_info.notes = jsonobject[key].toObject()["Notes"].toString().toStdString(); // absent in older projects
2798
2799 element_information_[key.toStdString()] = elem_info;
2800 }
2801
2802 return true;
2803}
2804
2805bool SourceSinkData::ReadElementDatafromJsonObject(const QJsonObject& jsonobject)
2806{
2807 QString error;
2808 return ReadElementDatafromJsonObject(jsonobject, error);
2809}
2810
2811bool SourceSinkData::ReadElementDatafromJsonObject(const QJsonObject& jsonobject, QString& error)
2812{
2813 // Clear existing data
2814 clear();
2815
2816 // Deserialize each sample group
2817 for (const QString& key : jsonobject.keys())
2818 {
2820 QString set_error;
2821 if (!elemental_profile_set.ReadFromJsonObject(jsonobject[key].toObject(), set_error))
2822 {
2823 error = QStringLiteral("group '%1', %2").arg(key, set_error);
2824 return false;
2825 }
2826 operator[](key.toStdString()) = elemental_profile_set;
2827 }
2828
2829 return true;
2830}
2831
2832bool SourceSinkData::ReadOptionsfromJsonObject(const QJsonObject& jsonobject)
2833{
2834 // Deserialize each option
2835 for (const QString& key : jsonobject.keys())
2836 {
2837 options_[key] = jsonobject[key].toDouble();
2838 }
2839
2840 return true;
2841}
2842
2844{
2845 QJsonObject json_object;
2846
2847 // Serialize each sample group
2848 for (map<string, Elemental_Profile_Set>::const_iterator it = cbegin(); it != cend(); it++)
2849 {
2850 json_object[QString::fromStdString(it->first)] = it->second.toJsonObject();
2851 }
2852
2853 return json_object;
2854}
2855
2857{
2858 // Write header
2859 file->write("***\n");
2860 file->write("Elemental Profiles\n");
2861
2862 // Write each sample group
2863 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2864 {
2865 file->write("**\n");
2866 file->write(QString::fromStdString(it->first + "\n").toUtf8());
2867 it->second.writetofile(file);
2868 }
2869
2870 return true;
2871}
2872
2874{
2875 return WriteDataToFile(file);
2876}
2877
2879{
2880 // Clear existing data
2881 Clear();
2882
2883 load_error_.clear();
2884
2885 // Parse JSON from file
2886 QJsonParseError parse_error;
2887 QJsonDocument document = QJsonDocument::fromJson(fil->readAll(), &parse_error);
2888 if (document.isNull())
2889 {
2890 load_error_ = QStringLiteral("The file is not valid JSON (%1).").arg(parse_error.errorString());
2891 return false;
2892 }
2893 QJsonObject jsondoc = document.object();
2894
2895 // Load all components. Every data value must be a finite number.
2896 QString data_error;
2897 if (!ReadElementDatafromJsonObject(jsondoc["Element Data"].toObject(), data_error))
2898 {
2899 load_error_ = QStringLiteral("Invalid data value in %1.").arg(data_error);
2900 Clear();
2901 return false;
2902 }
2903 ReadElementInformationfromJsonObject(jsondoc["Element Information"].toObject());
2904 ReadToolsUsedFromJsonObject(jsondoc["Tools used"].toArray());
2905 ReadOptionsfromJsonObject(jsondoc["Options"].toObject());
2906 target_group_ = jsondoc["Target Group"].toString().toStdString();
2907
2908 return true;
2909}
2910
2912{
2913 QJsonObject json_object;
2914
2915 // Serialize metadata for each element
2916 for (map<string, element_information>::const_iterator it = element_information_.cbegin(); it != element_information_.cend(); it++)
2917 {
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);
2924
2925 json_object[QString::fromStdString(it->first)] = elem_info_json_obj;
2926 }
2927
2928 return json_object;
2929}
2930
2932{
2933 // Convert enum to string representation
2935 return "DoNotInclude";
2936 else if (role == element_information::role::element)
2937 return "Element";
2938 else if (role == element_information::role::isotope)
2939 return "Isotope";
2941 return "ParticleSize";
2943 return "OM";
2944
2945 // Default for unrecognized values
2946 return "DoNotInclude";
2947}
2948
2949element_information::role SourceSinkData::Role(const QString& role_string) const
2950{
2951 // Convert string to enum representation
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")
2962
2963 // Default for unrecognized values
2965}
2966
2968 const string& om,
2969 const string& particle_size,
2970 regression_form form,
2971 const double& p_value_threshold)
2972{
2973 // Store OM and size constituent names for later use in corrections
2974 omconstituent_ = om;
2975 sizeconstituent_ = particle_size;
2976 regression_p_value_threshold_ = p_value_threshold;
2977
2978 // Compute regression models for all sample groups
2979 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
2980 {
2981 it->second.SetRegressionModels(om, particle_size, form, p_value_threshold);
2982 }
2983
2984 // Isotopes are not corrected by default, even when the regression is
2985 // significant: their delta values depend on the relative proportions of
2986 // organic matter, so a correction would bias them (as in Sed_SAT 1.0).
2987 // The user can still choose to correct them in Settings > Organic
2988 // Matter and Size Correction.
2989 for (auto& [group_name, profile_set] : *this)
2990 {
2991 MultipleLinearRegressionSet* models = profile_set.GetRegressionModels();
2992 if (models == nullptr)
2993 continue;
2994 for (const auto& [name, info] : element_information_)
2995 {
2996 if (info.Role != element_information::role::isotope || models->count(name) == 0)
2997 continue;
2998 MultipleLinearRegression& model = models->at(name);
2999 for (size_t term = 0; term < model.GetIndependentVariableNames().size(); term++)
3000 model.SetEffective(int(term), false);
3001 }
3002 }
3003
3004 return true;
3005}
3006
3007void SourceSinkData::OutlierAnalysisForAll(const double& lower_threshold, const double& upper_threshold)
3008{
3009 // Perform outlier detection on each source group
3010 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3011 {
3012 // Skip target group - only analyze sources
3013 if (it->first != target_group_)
3014 {
3015 it->second.DetectOutliers(lower_threshold, upper_threshold);
3016 }
3017 }
3018}
3019
3021{
3022 DFA_result result;
3023
3024 // Initialize result vectors for all sources
3025 const size_t num_sources = size() - 1; // Exclude target
3026 result.F_test_P_value = CMBVector(num_sources);
3027 result.p_values = CMBVector(num_sources);
3028 result.wilkslambda = CMBVector(num_sources);
3029
3030 // Perform DFA for each source vs all others
3031 size_t counter = 0;
3032 for (map<string, Elemental_Profile_Set>::iterator source = begin(); source != end(); source++)
3033 {
3034 // Skip target group
3035 if (source->first != target_group_)
3036 {
3037 // Run one-vs-rest DFA for this source
3038 DFA_result source_result = DiscriminantFunctionAnalysis(source->first);
3039
3040 // Extract and store results
3041 result.F_test_P_value[counter] = source_result.F_test_P_value[0];
3042 result.F_test_P_value.SetLabel(counter, source->first);
3043
3044 result.p_values[counter] = source_result.p_values[0];
3045 result.p_values.SetLabel(counter, source->first);
3046
3047 result.wilkslambda[counter] = source_result.wilkslambda[0];
3048 result.wilkslambda.SetLabel(counter, source->first);
3049
3050 result.eigen_vectors.Append(source->first, source_result.eigen_vectors[source->first + " vs the rest"]);
3051 result.multi_projected.Append(source->first, source_result.projected);
3052
3053 counter++;
3054 }
3055 }
3056
3057 return result;
3058}
3059
3060DFA_result SourceSinkData::DiscriminantFunctionAnalysis(const string& source1, const string& source2)
3061{
3062 // Create temporary dataset with only two sources
3063 SourceSinkData two_sources;
3064 two_sources.AppendSampleSet(source1, at(source1));
3065 two_sources.AppendSampleSet(source2, at(source2));
3067
3068 DFA_result result;
3069
3070 // Compute discriminant eigenvector
3071 CMBVector eigen_vector = two_sources.DFA_eigvector();
3072
3073 // Return empty result if eigenvector computation failed
3074 if (eigen_vector.size() == 0)
3075 {
3076 return result;
3077 }
3078
3079 // Project samples onto discriminant axis
3080 result.projected = two_sources.DFA_Projected(source1, source2);
3081
3082 // Compute F-test p-value for separation
3083 result.F_test_P_value = CMBVector(1);
3084 result.F_test_P_value[0] = result.projected.FTest_p_value();
3085
3086 // Store eigenvector
3087 result.eigen_vectors.Append(source1 + " vs " + source2, eigen_vector);
3088
3089 // Compute discriminant p-value and Wilks' Lambda
3090 double p_value = two_sources.DFA_P_Value();
3091 result.p_values = CMBVector(1);
3092 result.p_values[0] = p_value;
3093
3094 result.wilkslambda = CMBVector(1);
3095 result.wilkslambda[0] = two_sources.WilksLambda();
3096
3097 return result;
3098}
3099
3101{
3102 // Create temporary dataset with one source vs all others
3103 SourceSinkData two_sources;
3104 two_sources.AppendSampleSet(source1, at(source1));
3105 two_sources.AppendSampleSet("Others", TheRest(source1));
3107
3108 DFA_result result;
3109
3110 // Compute discriminant eigenvector
3111 CMBVector eigen_vector = two_sources.DFA_eigvector();
3112
3113 // Project all samples onto discriminant axis
3114 result.projected = two_sources.DFA_Projected(source1, this);
3115
3116 // Project pairwise comparison (source vs others)
3117 CMBVectorSet pairwise_projected = two_sources.DFA_Projected(source1, "Others");
3118
3119 // Compute F-test p-value from pairwise projection
3120 result.F_test_P_value = CMBVector(1);
3121 result.F_test_P_value[0] = pairwise_projected.FTest_p_value();
3122
3123 // Store eigenvector with descriptive label
3124 result.eigen_vectors.Append(source1 + " vs the rest", eigen_vector);
3125
3126 // Compute discriminant p-value and Wilks' Lambda
3127 double p_value = two_sources.DFA_P_Value();
3128 result.p_values = CMBVector(1);
3129 result.p_values[0] = p_value;
3130
3131 result.wilkslambda = CMBVector(1);
3132 result.wilkslambda[0] = two_sources.WilksLambda();
3133
3134 return result;
3135}
3137{
3138 int count = 0;
3139
3140 // Sum samples across all source groups
3141 for (map<string, Elemental_Profile_Set>::const_iterator source_group = cbegin(); source_group != cend(); source_group++)
3142 {
3143 // Skip target group - only count source samples
3144 if (source_group->first != target_group_)
3145 {
3146 count += source_group->second.size();
3147 }
3148 }
3149
3150 return count;
3151}
3152
3153CMBVector SourceSinkData::DFATransformed(const CMBVector& eigenvector, const string& source_group)
3154{
3155 // Initialize result vector for discriminant scores
3156 CMBVector discriminant_scores(operator[](source_group).size());
3157
3158 // Project each sample onto the discriminant axis
3159 size_t sample_index = 0;
3160 for (map<string, Elemental_Profile>::iterator sample = operator[](source_group).begin();
3161 sample != operator[](source_group).end();
3162 sample++)
3163 {
3164 // Compute dot product: discriminant score = eigenvector · sample_profile
3165 discriminant_scores[sample_index] = sample->second.CalculateDotProduct(eigenvector);
3166 discriminant_scores.SetLabel(sample_index, sample->first);
3167
3168 sample_index++;
3169 }
3170
3171 return discriminant_scores;
3172}
3173
3175{
3176 Elemental_Profile_Set combined_sources;
3177
3178 // Iterate through all sample groups
3179 for (map<string, Elemental_Profile_Set>::iterator profile_set = begin();
3180 profile_set != end();
3181 profile_set++)
3182 {
3183 // Skip the excluded source and target group
3184 if (profile_set->first != excluded_source && profile_set->first != target_group_)
3185 {
3186 // Add all samples from this source group
3187 for (map<string, Elemental_Profile>::iterator profile = profile_set->second.begin();
3188 profile != profile_set->second.end();
3189 profile++)
3190 {
3191 combined_sources.AppendProfile(profile->first, profile->second);
3192 }
3193 }
3194 }
3195
3196 return combined_sources;
3197}
3198
3199
3200CMBVector SourceSinkData::BracketTest(const string& target_sample, bool correct_based_on_om_n_size, double tolerance)
3201{
3202 vector<string> element_names = GetElementNames();
3203 const size_t num_elements = element_names.size();
3204
3205 CMBVector bracket_test_results(num_elements);
3206
3207 // Create corrected dataset for testing
3209 false, false, correct_based_on_om_n_size, target_sample);
3210
3211 for (size_t i = 0; i < num_elements; i++)
3212 {
3213 bracket_test_results.SetLabel(i, element_names[i]);
3214
3215 // The range of all source samples together
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();
3220 it++)
3221 {
3222 if (it->first == target_group_)
3223 continue;
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());
3226 }
3227
3228 // The tolerance widens both ends by a fraction of that range
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;
3234
3235 // Fail if above all maxima or below all minima
3236 bracket_test_results[i] = (exceeds_max || below_min) ? 1.0 : 0.0;
3237
3238 // Annotate failures in target sample notes
3239 if (exceeds_max)
3240 {
3241 at(target_group_).GetProfile(target_sample)->AppendtoNotes(
3242 element_names[i] + " value is higher than the maximum of the sources");
3243 }
3244 else if (below_min)
3245 {
3246 at(target_group_).GetProfile(target_sample)->AppendtoNotes(
3247 element_names[i] + " value is lower than the minimum of the sources");
3248 }
3249 }
3250
3251 return bracket_test_results;
3252}
3253
3254
3256 bool correct_based_on_om_n_size,
3257 bool exclude_elements,
3258 bool exclude_samples,
3259 double tolerance)
3260{
3261 // Initialize result matrix
3262 // Note: Matrix is constructed as (num_rows, num_cols) but accessed as [row][col]
3263 const size_t num_target_samples = at(target_group_).size();
3264 const size_t num_elements = CountElements(exclude_elements);
3265 CMBMatrix bracket_results(num_target_samples, num_elements);
3266
3267 // Test each target sample
3268 size_t sample_index = 0;
3269 for (map<string, Elemental_Profile>::iterator sample = at(target_group_).begin();
3270 sample != at(target_group_).end();
3271 sample++)
3272 {
3273 // Prepare dataset for this target sample
3274 SourceSinkData corrected_data;
3275 if (correct_based_on_om_n_size)
3276 {
3277 corrected_data = CreateTracerDataset(
3278 exclude_samples, exclude_elements, true, sample->first);
3279 }
3280 else
3281 {
3282 corrected_data = CreateTracerDataset(
3283 exclude_samples, exclude_elements, false);
3284 }
3285
3286 // Perform bracket test for this sample
3287 vector<string> element_names = corrected_data.GetElementNames();
3288 CMBVector bracket_vector = corrected_data.BracketTest(sample->first, false, tolerance);
3289
3290 // Store results in matrix
3291 for (size_t element_index = 0; element_index < element_names.size(); element_index++)
3292 {
3293 bracket_results[element_index][sample_index] = bracket_vector.valueAt(element_index);
3294 bracket_results.SetRowLabel(element_index, element_names[element_index]);
3295 }
3296 bracket_results.SetColumnLabel(sample_index, sample->first);
3297
3298 sample_index++;
3299 }
3300
3301 return bracket_results;
3302}
3303
3304
3305
3307{
3308 // Compute optimal lambda parameters for each element
3309 CMBVector lambda_parameters = OptimalBoxCoxParameters();
3310
3311 // Create copy of data for transformation
3312 SourceSinkData transformed_data(*this);
3313
3314 // Apply Box-Cox transformation to each source group
3315 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3316 {
3317 // Skip target group - only transform sources
3318 if (it->first != target_group_)
3319 {
3320 if (calculate_optimal_lambda)
3321 {
3322 // Transform using optimal lambda parameters
3323 transformed_data[it->first] = it->second.ApplyBoxCoxTransform(&lambda_parameters);
3324 }
3325 else
3326 {
3327 // Transform using default parameters
3328 transformed_data[it->first] = it->second.ApplyBoxCoxTransform();
3329 }
3330 }
3331 }
3332
3333 // Recalculate distributions for transformed data
3334 transformed_data.PopulateElementDistributions();
3335 transformed_data.AssignAllDistributions();
3336
3337 return transformed_data;
3338}
3339
3340map<string, ConcentrationSet> SourceSinkData::ExtractConcentrationSet()
3341{
3342 map<string, ConcentrationSet> element_concentrations;
3343 vector<string> element_names = GetElementNames();
3344
3345 // Build concentration set for each element
3346 for (size_t i = 0; i < element_names.size(); i++)
3347 {
3348 ConcentrationSet concentration_set;
3349
3350 // Collect concentrations from all source groups
3351 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3352 {
3353 // Skip target group - only collect from sources
3354 if (it->first != target_group_)
3355 {
3356 // Add each sample's concentration for this element
3357 for (map<string, Elemental_Profile>::iterator sample = it->second.begin();
3358 sample != it->second.end();
3359 sample++)
3360 {
3361 concentration_set.AppendValue(sample->second[element_names[i]]);
3362 }
3363 }
3364 }
3365
3366 element_concentrations[element_names[i]] = concentration_set;
3367 }
3368
3369 return element_concentrations;
3370}
3371
3373{
3374 // Extract concentration distributions for all elements
3375 map<string, ConcentrationSet> concentration_sets = ExtractConcentrationSet();
3376 vector<string> element_names = GetElementNames();
3377
3378 // Compute optimal lambda for each element
3379 CMBVector lambda_parameters(element_names.size());
3380
3381 for (size_t i = 0; i < element_names.size(); i++)
3382 {
3383 // Find optimal lambda using maximum likelihood estimation
3384 // Search range: [-5, 5], refinement iterations: 10
3385 lambda_parameters[i] = concentration_sets[element_names[i]].FindOptimalBoxCoxParameter(-5, 5, 10);
3386 }
3387
3388 // Label parameters with element names
3389 lambda_parameters.SetLabels(element_names);
3390
3391 return lambda_parameters;
3392}
3393Elemental_Profile SourceSinkData::t_TestPValue(const string& source1, const string& source2, bool use_log)
3394{
3395 vector<string> element_names = GetElementNames();
3396 Elemental_Profile p_values;
3397
3398 // Perform t-test for each element
3399 for (size_t i = 0; i < element_names.size(); i++)
3400 {
3401 // Get concentration distributions for both sources
3402 ConcentrationSet concentration_set1 = *at(source1).GetElementDistribution(element_names[i]);
3403 ConcentrationSet concentration_set2 = *at(source2).GetElementDistribution(element_names[i]);
3404
3405 // Compute statistics in appropriate space
3406 double std1 = NAN, std2 = NAN, mean1 = NAN, mean2 = NAN;
3407 if (!use_log)
3408 {
3409 // Linear-space statistics
3410 std1 = concentration_set1.CalculateStdDev();
3411 std2 = concentration_set2.CalculateStdDev();
3412 mean1 = concentration_set1.CalculateMean();
3413 mean2 = concentration_set2.CalculateMean();
3414 }
3415 else
3416 {
3417 // Log-space statistics
3418 std1 = concentration_set1.CalculateStdDevLog();
3419 std2 = concentration_set2.CalculateStdDevLog();
3420 mean1 = concentration_set1.CalculateMeanLog();
3421 mean2 = concentration_set2.CalculateMeanLog();
3422 }
3423
3424 // A t-test needs at least two samples in each group; with fewer the
3425 // degrees of freedom below would wrap around (size_t)
3426 if (concentration_set1.size() < 2 || concentration_set2.size() < 2)
3427 {
3428 p_values.AppendElement(element_names[i], NAN);
3429 continue;
3430 }
3431
3432 // Compute t-statistic
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;
3436
3437 // Compute two-tailed p-value
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);
3441
3442 // Two-tailed: use minimum of tails, then sum
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;
3446
3447 p_values.AppendElement(element_names[i], p_value);
3448 }
3449
3450 return p_values;
3451}
3452
3453Elemental_Profile SourceSinkData::DifferentiationPower(const string& source1, const string& source2, bool use_log)
3454{
3455 vector<string> element_names = GetElementNames();
3456 Elemental_Profile differentiation_powers;
3457
3458 // Compute differentiation power for each element
3459 for (size_t i = 0; i < element_names.size(); i++)
3460 {
3461 // Get concentration distributions for both sources
3462 ConcentrationSet concentration_set1 = *at(source1).GetElementDistribution(element_names[i]);
3463 ConcentrationSet concentration_set2 = *at(source2).GetElementDistribution(element_names[i]);
3464
3465 // Compute statistics in appropriate space
3466 double std1 = NAN, std2 = NAN, mean1 = NAN, mean2 = NAN;
3467 if (!use_log)
3468 {
3469 // Linear-space statistics
3470 std1 = concentration_set1.CalculateStdDev();
3471 std2 = concentration_set2.CalculateStdDev();
3472 mean1 = concentration_set1.CalculateMean();
3473 mean2 = concentration_set2.CalculateMean();
3474 }
3475 else
3476 {
3477 // Log-space statistics
3478 std1 = concentration_set1.CalculateStdDevLog();
3479 std2 = concentration_set2.CalculateStdDevLog();
3480 mean1 = concentration_set1.CalculateMeanLog();
3481 mean2 = concentration_set2.CalculateMeanLog();
3482 }
3483
3484 // Compute differentiation power: 2 × |Δμ| / (σ₁ + σ₂)
3485 double diff_power = 2.0 * fabs(mean1 - mean2) / (std1 + std2);
3486
3487 differentiation_powers.AppendElement(element_names[i], diff_power);
3488 }
3489
3490 return differentiation_powers;
3491}
3492
3494{
3495 Elemental_Profile_Set all_pairs;
3496
3497 // Compare all pairs of source groups
3498 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != prev(end()); it++)
3499 {
3500 if (include_target || it->first != target_group_)
3501 {
3502 for (map<string, Elemental_Profile_Set>::iterator it2 = next(it); it2 != end(); it2++)
3503 {
3504 if (include_target || it2->first != target_group_)
3505 {
3506 Elemental_Profile diff_power = DifferentiationPower(it->first, it2->first, use_log);
3507 all_pairs.AppendProfile(it->first + " and " + it2->first, diff_power);
3508 }
3509 }
3510 }
3511 }
3512
3513 return all_pairs;
3514}
3515
3516Elemental_Profile SourceSinkData::DifferentiationPower_Percentage(const string& source1, const string& source2)
3517{
3518 vector<string> element_names = GetElementNames();
3519 Elemental_Profile classification_percentages;
3520
3521 // Compute classification percentage for each element
3522 for (size_t i = 0; i < element_names.size(); i++)
3523 {
3524 // Get concentration distributions
3525 ConcentrationSet concentration_set1 = *at(source1).GetElementDistribution(element_names[i]);
3526 ConcentrationSet concentration_set2 = *at(source2).GetElementDistribution(element_names[i]);
3527
3528 // Pool all samples and compute ranks
3529 ConcentrationSet combined_set = concentration_set1;
3530 combined_set.AppendSet(concentration_set2);
3531 vector<unsigned int> ranks = combined_set.CalculateRanks();
3532
3533 // Count correct classifications
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);
3539
3540 // Compute classification success rates
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());
3543
3544 // Use best classification direction
3545 double classification_percentage = max(set1_fraction, set2_fraction);
3546
3547 classification_percentages.AppendElement(element_names[i], classification_percentage);
3548 }
3549
3550 return classification_percentages;
3551}
3552
3554{
3555 Elemental_Profile_Set all_pairs;
3556
3557 // Compare all pairs of source groups
3558 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != prev(end()); it++)
3559 {
3560 if (include_target || it->first != target_group_)
3561 {
3562 for (map<string, Elemental_Profile_Set>::iterator it2 = next(it); it2 != end(); it2++)
3563 {
3564 if (include_target || it2->first != target_group_)
3565 {
3566 Elemental_Profile diff_power_pct = DifferentiationPower_Percentage(it->first, it2->first);
3567 all_pairs.AppendProfile(it->first + " and " + it2->first, diff_power_pct);
3568 }
3569 }
3570 }
3571 }
3572
3573 return all_pairs;
3574}
3575
3577{
3578 Elemental_Profile_Set all_pairs;
3579
3580 // Compare all pairs of source groups
3581 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != prev(end()); it++)
3582 {
3583 if (include_target || it->first != target_group_)
3584 {
3585 for (map<string, Elemental_Profile_Set>::iterator it2 = next(it); it2 != end(); it2++)
3586 {
3587 if (include_target || it2->first != target_group_)
3588 {
3589 Elemental_Profile p_values = t_TestPValue(it->first, it2->first, false);
3590 all_pairs.AppendProfile(it->first + " and " + it2->first, p_values);
3591 }
3592 }
3593 }
3594 }
3595
3596 return all_pairs;
3597}
3598
3600{
3601 vector<string> error_messages;
3602
3603 // Ensure element ordering is current
3605
3606 // Check each source group for negative values. (This used to stop
3607 // before the last group in alphabetical order, assuming it was the
3608 // target: it skipped a source that sorts after the target, checked the
3609 // target instead, and was undefined for an empty dataset.)
3610 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++)
3611 {
3612 if (it->first == target_group_)
3613 continue;
3614 vector<string> negative_elements = it->second.CheckForNegativeValues(element_order_);
3615
3616 // Generate error message for each problematic element
3617 for (size_t i = 0; i < negative_elements.size(); i++)
3618 {
3619 error_messages.push_back("There are zero or negative values for element '" +
3620 negative_elements[i] + "' in sample group '" +
3621 it->first + "'");
3622 }
3623 }
3624
3625 return error_messages;
3626}
3627
3629{
3630 // Below round-off, not below zero: a contribution that is negative only in
3631 // the last bits is an exact zero the arithmetic could not represent, and
3632 // reporting it would cry wolf on a perfectly good solution.
3633 const double round_off = -1e-9;
3634
3635 vector<string> error_messages;
3636 const vector<string> source_names = GetSourceOrder();
3637 CVector contributions = GetContributionVector();
3638
3639 for (size_t i = 0; i < source_names.size() && i < static_cast<size_t>(contributions.num); i++)
3640 {
3641 if (contributions[static_cast<int>(i)] < round_off)
3642 {
3643 error_messages.push_back(source_names[i] + ": " +
3644 aquiutils::numbertostring(contributions[static_cast<int>(i)]));
3645 }
3646 }
3647
3648 return error_messages;
3649}
3650
3651void SourceSinkData::IncludeExcludeAllElements(bool include_in_analysis)
3652{
3653 // Set inclusion flag for all elements
3654 for (map<string, element_information>::iterator it = element_information_.begin();
3655 it != element_information_.end();
3656 it++)
3657 {
3658 it->second.include_in_analysis = include_in_analysis;
3659 }
3660}
3661
3662double SourceSinkData::GrandMean(const string& element, bool use_log)
3663{
3664 double weighted_sum = 0.0;
3665 double total_count = 0.0;
3666
3667 // Accumulate weighted means from each source group
3668 for (map<string, Elemental_Profile_Set>::iterator it = begin(); it != end(); it++) // every group but the target (this stopped before the last group, which dropped a source sorting after the target)
3669 {
3670 // Skip target group
3671 if (it->first != target_group_)
3672 {
3673 ConcentrationSet* element_dist = it->second.GetElementDistribution(element);
3674 size_t sample_count = element_dist->size();
3675
3676 if (!use_log)
3677 {
3678 // Linear-space mean
3679 weighted_sum += element_dist->CalculateMean() * sample_count;
3680 }
3681 else
3682 {
3683 // Log-space mean
3684 weighted_sum += element_dist->CalculateMeanLog() * sample_count;
3685 }
3686
3687 total_count += sample_count;
3688 }
3689 }
3690
3691 // Compute weighted average
3692 return weighted_sum / total_count;
3693}
3694
3696{
3697 Elemental_Profile_Set combined_sources;
3698
3699 // Pool samples from all source groups
3700 for (map<string, Elemental_Profile_Set>::const_iterator it = begin(); it != end(); it++) // every group but the target (this stopped before the last group, which dropped a source sorting after the target)
3701 {
3702 // Skip target group
3703 if (it->first != target_group_)
3704 {
3705 combined_sources.AppendProfiles(it->second, nullptr);
3706 }
3707 }
3708
3709 // Recalculate distributions for combined dataset
3710 combined_sources.UpdateElementDistributions();
3711
3712 return combined_sources;
3713}
3714
3716{
3717 vector<string> element_names = GetElementNames();
3718 CMBVector p_values(element_names.size());
3719 p_values.SetLabels(element_names);
3720
3721 // Perform ANOVA for each element
3722 for (size_t i = 0; i < element_names.size(); i++)
3723 {
3724 ANOVA_info anova_result = ANOVA(element_names[i], use_log);
3725 p_values[i] = anova_result.p_value;
3726 }
3727
3728 return p_values;
3729}
3730
3731ANOVA_info SourceSinkData::ANOVA(const string& element, bool use_log)
3732{
3733 ANOVA_info anova;
3734
3735 // Combine all source samples for total variance calculation
3737 ConcentrationSet* all_element_data = all_sources.GetElementDistribution(element);
3738
3739 if (!use_log)
3740 {
3741 // Linear-space ANOVA
3742
3743 // Total sum of squares (SST)
3744 anova.SST = all_element_data->CalculateSSE();
3745
3746 // Between-group sum of squares (SSB) and within-group sum of squares (SSW)
3747 double grand_mean = all_element_data->CalculateMean();
3748 double sum_between = 0.0;
3749 double sum_within = 0.0;
3750
3751 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
3752 source_group != end();
3753 source_group++)
3754 {
3755 if (source_group->first != target_group_)
3756 {
3757 ConcentrationSet* group_data = source_group->second.GetElementDistribution(element);
3758 double group_mean = group_data->CalculateMean();
3759 size_t group_size = group_data->size();
3760
3761 // SSB: variance of group means weighted by sample size
3762 sum_between += pow(group_mean - grand_mean, 2) * group_size;
3763
3764 // SSW: sum of within-group variances
3765 sum_within += group_data->CalculateSSE();
3766 }
3767 }
3768
3769 anova.SSB = sum_between;
3770 anova.SSW = sum_within;
3771 }
3772 else
3773 {
3774 // Log-space ANOVA
3775
3776 // Total sum of squares (SST)
3777 double total_std_log = all_element_data->CalculateStdDevLog();
3778 size_t total_size = all_element_data->size();
3779 anova.SST = pow(total_std_log, 2) * (total_size - 1);
3780
3781 // Between-group sum of squares (SSB) and within-group sum of squares (SSW)
3782 double grand_mean_log = all_element_data->CalculateMeanLog();
3783 double sum_between = 0.0;
3784 double sum_within = 0.0;
3785
3786 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
3787 source_group != end();
3788 source_group++)
3789 {
3790 if (source_group->first != target_group_)
3791 {
3792 ConcentrationSet* group_data = source_group->second.GetElementDistribution(element);
3793 double group_mean_log = group_data->CalculateMeanLog();
3794 size_t group_size = group_data->size();
3795
3796 // SSB: variance of group means weighted by sample size
3797 sum_between += pow(group_mean_log - grand_mean_log, 2) * group_size;
3798
3799 // SSW: sum of within-group variances
3800 sum_within += group_data->CalculateSSELog();
3801 }
3802 }
3803
3804 anova.SSB = sum_between;
3805 anova.SSW = sum_within;
3806 }
3807
3808 // Compute mean squares and F-statistic
3809 size_t num_groups = this->size() - 1; // Exclude target
3810 size_t total_samples = all_element_data->size();
3811
3812 // Degrees of freedom
3813 size_t df_between = num_groups - 1;
3814 size_t df_within = total_samples - num_groups;
3815
3816 // Mean squares
3817 anova.MSB = anova.SSB / double(df_between);
3818 anova.MSW = anova.SSW / double(df_within);
3819
3820 // F-statistic
3821 anova.F = anova.MSB / anova.MSW;
3822
3823 // P-value from F-distribution
3824 anova.p_value = gsl_cdf_fdist_Q(anova.F, df_between, total_samples);
3825
3826 return anova;
3827}
3828void SourceSinkData::IncludeExcludeElementsBasedOn(const vector<string>& elements)
3829{
3830 // First, exclude all elements and isotopes. The organic matter and particle
3831 // size constituents are not tracers and are left as they are: excluding
3832 // them stopped the size and organic matter correction of later steps.
3833 for (map<string, element_information>::iterator element = element_information_.begin();
3834 element != element_information_.end();
3835 element++)
3836 {
3837 if (element->second.Role == element_information::role::element ||
3838 element->second.Role == element_information::role::isotope)
3839 element->second.include_in_analysis = false;
3840 }
3841
3842 // Then, include only specified elements
3843 for (size_t i = 0; i < elements.size(); i++)
3844 {
3845 if (element_information_.count(elements[i]) > 0)
3846 {
3847 element_information_[elements[i]].include_in_analysis = true;
3848 }
3849 }
3850}
3851
3853{
3854 SourceSinkData reduced_dataset;
3855
3856 // Randomly select samples to eliminate
3857 vector<string> samples_to_eliminate = RandomlypickSamples(percentage / 100.0, stream);
3858
3859 // Copy groups with specified samples eliminated
3860 for (map<string, Elemental_Profile_Set>::const_iterator it = cbegin(); it != cend(); it++)
3861 {
3862 if (it->first != target_group_)
3863 {
3864 // Remove randomly selected samples from source groups
3865 reduced_dataset[it->first] = it->second.EliminateSamples(
3866 samples_to_eliminate, &element_information_);
3867 }
3868 else
3869 {
3870 // Preserve target group unchanged
3871 reduced_dataset[it->first] = it->second;
3872 }
3873 }
3874
3875 // Copy metadata and settings
3876 reduced_dataset.omconstituent_ = omconstituent_;
3877 reduced_dataset.sizeconstituent_ = sizeconstituent_;
3878 reduced_dataset.target_group_ = target_group_;
3879
3880 // Recalculate distributions for reduced dataset
3882 reduced_dataset.PopulateElementDistributions();
3883 reduced_dataset.AssignAllDistributions();
3884
3885 return reduced_dataset;
3886}
3887
3888Elemental_Profile SourceSinkData::Sample(const string& sample_name) const
3889{
3890 // Search all groups for the specified sample
3891 for (map<string, Elemental_Profile_Set>::const_iterator it = cbegin(); it != cend(); it++)
3892 {
3893 if (it->second.count(sample_name) == 1)
3894 {
3895 return it->second.at(sample_name);
3896 }
3897 }
3898
3899 // Sample not found - return empty profile
3900 return Elemental_Profile();
3901}
3902SourceSinkData SourceSinkData::ReplaceSourceAsTarget(const string& source_sample_name) const
3903{
3904 // Create copy of current dataset
3905 SourceSinkData modified_dataset = *this;
3906
3907 // Extract specified source sample
3908 Elemental_Profile target_profile = Sample(source_sample_name);
3909
3910 // Create new target group with this sample
3911 Elemental_Profile_Set new_target_group = Elemental_Profile_Set();
3912 new_target_group.AppendProfile(source_sample_name, target_profile);
3913 modified_dataset[target_group_] = new_target_group;
3914
3915 // Copy metadata and settings
3916 modified_dataset.omconstituent_ = omconstituent_;
3917 modified_dataset.sizeconstituent_ = sizeconstituent_;
3918 modified_dataset.target_group_ = target_group_;
3919
3920 // Recalculate distributions
3922 modified_dataset.PopulateElementDistributions();
3923 modified_dataset.AssignAllDistributions();
3924
3925 return modified_dataset;
3926}
3927
3929 const double& percentage,
3930 unsigned int num_iterations,
3931 const string& target_sample,
3932 bool use_softmax,
3933 std::uint64_t seed)
3934{
3935 // One stream for the whole analysis, so the same seed repeats it
3936 // (the elimination used a shared stream whose state depended on what
3937 // ran earlier in the session)
3938 RandomStream sampling_stream(seed);
3939
3940 // Initialize result time series
3941 CMBTimeSeriesSet contribution_time_series(numberofsourcesamplesets_);
3942
3943 // Set source names for time series
3944 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
3945 {
3946 contribution_time_series.setname(source_idx, samplesetsorder_[source_idx]);
3947 }
3948
3949 // Perform bootstrap iterations
3950 for (size_t iteration = 0; iteration < num_iterations; iteration++)
3951 {
3952 // Create bootstrapped dataset with randomly excluded samples
3953 SourceSinkData bootstrapped_data = RandomlyEliminateSourceSamples(percentage, sampling_stream);
3954 bootstrapped_data.InitializeParametersAndObservations(target_sample);
3955
3956 // Update progress if progress tracker available
3957 if (rtw_)
3958 {
3959 rtw_->SetProgress(double(iteration) / double(num_iterations));
3960 }
3961
3962 // Solve CMB model with appropriate transformation
3963 if (use_softmax)
3964 {
3966 }
3967 else
3968 {
3970 }
3971
3972 // Record contributions from this iteration
3973 contribution_time_series.append(iteration, bootstrapped_data.GetContributionVector().vec);
3974 }
3975
3976 return contribution_time_series;
3977}
3978
3980 Results* results,
3981 const double& percentage,
3982 unsigned int num_iterations,
3983 const string& target_sample,
3984 bool use_softmax,
3985 std::uint64_t seed)
3986{
3987 // One stream for the whole analysis, so the same seed repeats it
3988 // (the elimination used a shared stream whose state depended on what
3989 // ran earlier in the session)
3990 RandomStream sampling_stream(seed);
3991
3992 // Initialize contribution time series
3994
3995 // Set source names
3996 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
3997 {
3998 contributions->setname(source_idx, samplesetsorder_[source_idx]);
3999 }
4000
4001 // Perform bootstrap iterations
4002 for (size_t iteration = 0; iteration < num_iterations; iteration++)
4003 {
4004 // Create bootstrapped dataset
4005 SourceSinkData bootstrapped_data = RandomlyEliminateSourceSamples(percentage, sampling_stream);
4006 bootstrapped_data.InitializeParametersAndObservations(target_sample);
4007
4008 // Update progress
4009 if (rtw_)
4010 {
4011 rtw_->SetProgress(double(iteration) / double(num_iterations));
4012 }
4013
4014 // Solve CMB model
4015 if (use_softmax)
4016 {
4018 }
4019 else
4020 {
4022 }
4023
4024 // Record contributions
4025 contributions->append(iteration, bootstrapped_data.GetContributionVector().vec);
4026 }
4027
4028 // ========== Result 1: Contribution Time Series ==========
4029 ResultItem contributions_result;
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);
4033 contributions_result.SetType(result_type::stacked_bar_chart);
4034 contributions_result.SetShowAsString(false);
4035 contributions_result.SetShowTable(true);
4036
4037 // Only show graph for small sample sizes (to avoid clutter)
4038 if (num_iterations < 101)
4039 {
4040 contributions_result.SetShowGraph(true);
4041 }
4042 else
4043 {
4044 contributions_result.SetShowGraph(false);
4045 }
4046
4047 contributions_result.SetYLimit(_range::high, 1);
4048 contributions_result.SetYLimit(_range::low, 0);
4049 contributions_result.SetXAxisMode(xaxis_mode::counter);
4050 contributions_result.setYAxisTitle("Contribution");
4051 contributions_result.setXAxisTitle("Sample");
4052 results->Append(contributions_result);
4053
4054 // ========== Result 2: Posterior Distributions ==========
4055 CMBTimeSeriesSet* distributions = new CMBTimeSeriesSet();
4056 // All realizations (the end index 0 used to mean the first one only, so
4057 // the plotted distribution was a spike at the first realization)
4058 *distributions = contributions->distribution(100, 0, -1);
4059
4060 ResultItem distributions_result;
4061 distributions_result.SetName("Posterior Distributions");
4062 distributions_result.SetShowAsString(false);
4063 distributions_result.SetShowTable(true);
4064 distributions_result.SetType(result_type::distribution);
4065 distributions_result.SetResult(distributions);
4066 results->Append(distributions_result);
4067
4068 // ========== Result 3: 95% Credible Intervals ==========
4069 RangeSet* credible_intervals = new RangeSet();
4070
4071 for (size_t i = 0; i < GetSourceOrder().size(); i++)
4072 {
4073 Range interval;
4074
4075 // Compute statistics for this source
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);
4080
4081 // Configure credible interval
4082 interval.Set(_range::low, percentile_2_5);
4083 interval.Set(_range::high, percentile_97_5);
4084 interval.SetMean(mean_contribution);
4085 interval.SetMedian(median_contribution);
4086
4087 (*credible_intervals)[contributions->getSeriesName(i)] = interval;
4088 }
4089
4090 ResultItem intervals_result;
4091 intervals_result.SetName("Source Contribution Credible Intervals");
4092 intervals_result.SetShowAsString(true);
4093 intervals_result.SetShowTable(true);
4094 intervals_result.SetType(result_type::rangeset);
4095 intervals_result.SetResult(credible_intervals);
4096 intervals_result.setXAxisTitle("Source");
4097 intervals_result.setYAxisTitle("Contribution");
4098 intervals_result.SetYAxisMode(yaxis_mode::normal);
4099 intervals_result.SetYLimit(_range::high, 1.0);
4100 intervals_result.SetYLimit(_range::low, 0);
4101 results->Append(intervals_result);
4102
4103 return true;
4104}
4105
4107 const string& source_group,
4108 bool use_softmax,
4109 bool apply_om_size_correction)
4110{
4111 // Initialize with first target sample (will be replaced in loop)
4113
4114 // Initialize result time series
4115 CMBTimeSeriesSet validation_results(numberofsourcesamplesets_);
4116
4117 // Set source names
4118 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
4119 {
4120 validation_results.setname(source_idx, samplesetsorder_[source_idx]);
4121 }
4122
4123 // Perform leave-one-out validation for each sample in the source group.
4124 // The samples excluded in Settings > Include/Exclude Samples are neither
4125 // tested nor used in the source statistics.
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();
4129 sample++)
4130 {
4131 if (sample->first.empty() || !sample->second.IsIncludedInAnalysis())
4132 continue;
4133
4134 // Create dataset with this sample as target, and leave it out of its
4135 // source group (CreateCorrectedDataset drops the excluded samples)
4136 SourceSinkData test_dataset = ReplaceSourceAsTarget(sample->first);
4137 test_dataset[source_group].GetProfile(sample->first)->SetIncludedInAnalysis(false);
4138
4139 // Apply corrections if requested
4140 SourceSinkData corrected_dataset = test_dataset.CreateCorrectedDataset(
4141 sample->first, apply_om_size_correction, test_dataset.GetElementInformation());
4142 // No progress reporter for the per-sample fit: the analysis window has
4143 // no chart panel, and Levenberg-Marquardt plots its error on panel 0
4144 // (giving it the reporter crashed the program, and reset the bar for
4145 // every sample). The loop below reports the progress over samples.
4146
4147 // Check for negative values (would cause problems in CMB)
4148 vector<string> negative_elements = corrected_dataset.NegativeValueCheck();
4149
4150 if (negative_elements.size() == 0)
4151 {
4152 // No negative values - proceed with CMB solution on the corrected
4153 // data (solving the uncorrected copy ignored the correction and
4154 // the exclusions)
4155 corrected_dataset.InitializeParametersAndObservations(sample->first);
4156
4157 // Update progress
4158 if (rtw_)
4159 {
4160 rtw_->SetProgress(double(valid_sample_count) / double(at(source_group).size()));
4161 }
4162
4163 // Solve CMB model
4164 if (use_softmax)
4165 {
4167 }
4168 else
4169 {
4171 }
4172
4173 // Record contributions and label with sample name
4174 validation_results.append(valid_sample_count, corrected_dataset.GetContributionVector().vec);
4175 validation_results.SetLabel(valid_sample_count, sample->first);
4176 valid_sample_count++;
4177 }
4178 else
4179 {
4180 // Negative values detected - skip this sample and report
4181 for (size_t i = 0; i < negative_elements.size(); i++)
4182 {
4183 // qDebug() << QString::fromStdString(negative_elements[i]);
4184 }
4185 }
4186 }
4187
4188 return validation_results;
4189}
4190
4192 transformation transform,
4193 bool apply_om_size_correction,
4194 map<string, vector<string>>& negative_elements)
4195{
4196 // Initialize with first target sample (will be replaced in loop)
4198
4199 // Initialize result time series
4200 CMBTimeSeriesSet contribution_results(numberofsourcesamplesets_);
4201
4202 // Set source names
4203 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
4204 {
4205 contribution_results.setname(source_idx, samplesetsorder_[source_idx]);
4206 }
4207
4208 // Solve CMB for each target sample
4209 size_t valid_sample_count = 0;
4210 for (map<string, Elemental_Profile>::iterator sample = at(target_group_).begin();
4211 sample != at(target_group_).end();
4212 sample++)
4213 {
4214 // Skip samples with empty names, and the target samples excluded in
4215 // Settings > Include/Exclude Samples
4216 if (sample->first != "" && sample->second.IsIncludedInAnalysis())
4217 {
4218 // Apply corrections if requested
4219 SourceSinkData corrected_dataset = CreateCorrectedDataset(
4220 sample->first, apply_om_size_correction, GetElementInformation());
4221
4222 // Check for negative values
4223 negative_elements[sample->first] = corrected_dataset.NegativeValueCheck();
4224
4225 if (negative_elements[sample->first].size() == 0)
4226 {
4227 // No negative values - proceed with CMB solution
4228 corrected_dataset.InitializeParametersAndObservations(sample->first);
4229
4230 // Update progress with sample name
4231 if (rtw_)
4232 {
4233 rtw_->SetProgress(double(valid_sample_count) / double(at(target_group_).size()));
4234 rtw_->SetLabel(QString::fromStdString(sample->first));
4235 }
4236
4237 // Solve CMB model
4238 corrected_dataset.SolveLevenberg_Marquardt(transform);
4239
4240 // Record contributions and label with sample name
4241 contribution_results.append(valid_sample_count, corrected_dataset.GetContributionVector().vec);
4242 contribution_results.SetLabel(valid_sample_count, sample->first);
4243 valid_sample_count++;
4244 }
4245 }
4246 }
4247
4248 // Set progress to 100% at completion
4249 if (rtw_)
4250 {
4251 rtw_->SetProgress(1.0);
4252 }
4253
4254 return contribution_results;
4255}
4256
4257
4259{
4260 vector<string> all_sample_names;
4261
4262 // Collect sample names from all source groups
4263 for (map<string, Elemental_Profile_Set>::const_iterator profile_set = cbegin();
4264 profile_set != cend();
4265 profile_set++)
4266 {
4267 // Skip target group
4268 if (profile_set->first != target_group_)
4269 {
4270 // Add all sample names from this source group
4271 for (map<string, Elemental_Profile>::const_iterator profile = profile_set->second.cbegin();
4272 profile != profile_set->second.cend();
4273 profile++)
4274 {
4275 all_sample_names.push_back(profile->first);
4276 }
4277 }
4278 }
4279
4280 return all_sample_names;
4281}
4282
4283vector<string> SourceSinkData::RandomlypickSamples(const double& percentage, RandomStream& stream) const
4284{
4285 // Get all source sample names
4286 vector<string> all_samples = AllSourceSampleNames();
4287 vector<string> selected_samples;
4288
4289 // Perform Bernoulli sampling: each sample included independently with probability = percentage
4290 for (size_t i = 0; i < all_samples.size(); i++)
4291 {
4292 // Generate random number in [0, 1)
4293 double random_value = stream.Uniform();
4294
4295 // Include sample if random value < percentage
4296 if (random_value < percentage)
4297 {
4298 selected_samples.push_back(all_samples[i]);
4299 }
4300 }
4301
4302 return selected_samples;
4303}
4304
4306 const string& target_sample,
4307 map<string, string> arguments,
4309 ProgressReporter* progress_window,
4310 const string& working_folder)
4311{
4312 // A null reporter stands in for a missing one so that the progress calls
4313 // below need no null test. Callers that want no progress display pass
4314 // nullptr.
4315 NullProgressReporter discarded_progress;
4316 if (progress_window == nullptr)
4317 progress_window = &discarded_progress;
4318
4319 // Initialize results container
4320 Results results;
4321
4322 // The seed is recorded in the results name and in the sample file so
4323 // the run can be repeated; a blank seed is drawn here
4324 std::uint64_t seed = 0;
4325 if (!ParseRandomSeed(arguments["Random seed"], seed))
4326 {
4327 results.SetError("The random seed '" + arguments["Random seed"] + "' is not a whole number.");
4328 return results;
4329 }
4330 mcmc->SetRandomSeed(seed);
4331 results.SetName("MCMC results for '" + target_sample + "' (random seed " + std::to_string(seed) + ")");
4332
4333 // Parse OM/size correction setting
4334 bool apply_om_size_correction = (arguments["Apply size and organic matter correction"] == "true");
4335
4336 // Apply corrections and validate
4337 SourceSinkData corrected_data = CreateCorrectedDataset(
4338 target_sample, apply_om_size_correction, GetElementInformation());
4339 vector<string> negative_elements = corrected_data.NegativeValueCheck();
4340
4341 if (negative_elements.size() > 0)
4342 {
4343 // Negative values detected - return error
4344 results.SetError("Negative elemental content in ");
4345 for (size_t i = 0; i < negative_elements.size(); i++)
4346 {
4347 if (i == 0)
4348 results.AppendError(negative_elements[i]);
4349 else
4350 results.AppendError("," + negative_elements[i]);
4351 }
4352 return results;
4353 }
4354
4355 // Configure MCMC sampler
4356 mcmc->Model = &corrected_data;
4357
4358 // Setup progress window charts
4359 progress_window->SetTitle("Acceptance Rate", 0);
4360 progress_window->SetTitle("Perturbation Factor", 1);
4361 progress_window->SetTitle("Log posterior value", 2);
4362 progress_window->SetYAxisTitle("Acceptance Rate", 0);
4363 progress_window->SetYAxisTitle("Perturbation Factor", 1);
4364 progress_window->SetYAxisTitle("Log posterior value", 2);
4365 progress_window->Start();
4366
4367 // ========== Run MCMC Sampling ==========
4368 corrected_data.InitializeParametersAndObservations(target_sample);
4369
4370 // Set MCMC parameters
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"]);
4375 // Blank (an older script or project) keeps the default: on
4376 mcmc->SetProperty("covariance_proposal", arguments["Correlated proposal"]);
4377
4378 // Initialize MCMC sampler
4380 mcmc->initialize(mcmc_samples, true);
4381
4382 // Determine output file path
4383 string output_path;
4384 if (!QString::fromStdString(arguments["Samples File Name"]).contains("/"))
4385 {
4386 output_path = working_folder + "/";
4387 }
4388
4389 // Run MCMC chains
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"],
4393 mcmc_samples, progress_window);
4394
4395 // Append last contribution (computed from sum constraint)
4396 vector<string> source_names = corrected_data.SourceGroupNames();
4397 size_t last_source_idx = source_names.size() - 1;
4398 mcmc_samples->AppendLastContribution(last_source_idx,
4399 source_names[last_source_idx] + "_contribution");
4400
4401 // Store MCMC samples result
4402 ResultItem mcmc_samples_result;
4403 mcmc_samples_result.SetShowAsString(false);
4404 mcmc_samples_result.SetType(result_type::mcmc_samples);
4405 mcmc_samples_result.SetName("MCMC samples");
4406 mcmc_samples_result.SetResult(mcmc_samples);
4407 results.Append(mcmc_samples_result);
4408
4409 // Parse burnin parameter
4410 int burnin_samples = QString::fromStdString(arguments["Samples to be discarded (burnout)"]).toInt();
4411
4412 // ========== Result 1: Posterior Distributions for Contributions ==========
4413 ResultItem posterior_distributions_result;
4414 CMBTimeSeriesSet* posterior_distributions = new CMBTimeSeriesSet();
4415 *posterior_distributions = mcmc_samples->distribution(100, burnin_samples);
4416
4417 posterior_distributions_result.SetName("Posterior Distributions");
4418 posterior_distributions_result.SetShowAsString(false);
4419 posterior_distributions_result.SetShowTable(true);
4420 posterior_distributions_result.SetType(result_type::distribution);
4421 posterior_distributions_result.SetResult(posterior_distributions);
4422 results.Append(posterior_distributions_result);
4423
4424 // ========== Result 2: Contribution Credible Intervals ==========
4425 RangeSet* contribution_credible_intervals = new RangeSet();
4426
4427 for (size_t i = 0; i < corrected_data.GetSourceOrder().size(); i++)
4428 {
4429 Range interval;
4430
4431 // Compute statistics (excluding burnin)
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);
4434 double mean_contribution = mcmc_samples->at(i).mean(burnin_samples);
4435 double median_contribution = mcmc_samples->at(i).percentile(0.5, burnin_samples);
4436
4437 interval.Set(_range::low, percentile_2_5);
4438 interval.Set(_range::high, percentile_97_5);
4439 interval.SetMean(mean_contribution);
4440 interval.SetMedian(median_contribution);
4441
4442 (*contribution_credible_intervals)[mcmc_samples->getSeriesName(i)] = interval;
4443 }
4444
4445 ResultItem contribution_intervals_result;
4446 contribution_intervals_result.SetName("Source Contribution Credible Intervals");
4447 contribution_intervals_result.SetShowAsString(true);
4448 contribution_intervals_result.SetShowTable(true);
4449 contribution_intervals_result.SetType(result_type::rangeset);
4450 contribution_intervals_result.SetResult(contribution_credible_intervals);
4451 contribution_intervals_result.setXAxisTitle("Source");
4452 contribution_intervals_result.setYAxisTitle("Contribution");
4453 contribution_intervals_result.SetYAxisMode(yaxis_mode::log);
4454 contribution_intervals_result.SetYLimit(_range::high, 1.0);
4455 results.Append(contribution_intervals_result);
4456
4457 // ========== Result 3: Predicted Element Distributions ==========
4458 CMBTimeSeriesSet predicted_samples = mcmc->predicted;
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());
4463
4464 // Set constituent names
4465 for (size_t i = 0; i < predicted_samples.size(); i++)
4466 {
4467 predicted_samples.setname(i, all_constituent_names[i]);
4468 }
4469
4470 // Extract element predictions only
4471 CMBTimeSeriesSet predicted_elements;
4472 for (size_t i = 0; i < predicted_samples.size(); i++)
4473 {
4474 if (corrected_data.GetElementInformation(predicted_samples.getSeriesName(i))->Role ==
4476 {
4477 predicted_elements.append(predicted_samples[i], predicted_samples.getSeriesName(i));
4478 }
4479 }
4480
4481 // Compute posterior distributions for elements
4482 CMBTimeSeriesSet* predicted_element_distributions = new CMBTimeSeriesSet();
4483 *predicted_element_distributions = predicted_elements.distribution(100, burnin_samples);
4484
4485 // Add observed values
4486 for (size_t i = 0; i < predicted_elements.size(); i++)
4487 {
4488 predicted_element_distributions->SetObservedValue(i, corrected_data.observation(i)->Value());
4489 }
4490
4491 ResultItem predicted_elements_result;
4492 predicted_elements_result.SetName("Posterior Predicted Constituents");
4493 predicted_elements_result.SetShowAsString(false);
4494 predicted_elements_result.SetShowTable(true);
4495 predicted_elements_result.SetType(result_type::distribution_with_observed);
4496 predicted_elements_result.SetResult(predicted_element_distributions);
4497 results.Append(predicted_elements_result);
4498
4499 // ========== Result 4: Element Credible Intervals ==========
4500 RangeSet* predicted_element_intervals = new RangeSet();
4501
4502 // Compute percentiles for all predictions
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);
4507
4508 for (size_t i = 0; i < predicted_element_distributions->size(); i++)
4509 {
4510 Range interval;
4511 interval.Set(_range::low, percentile_2_5_all[i]);
4512 interval.Set(_range::high, percentile_97_5_all[i]);
4513 interval.SetMean(mean_all[i]);
4514 interval.SetMedian(median_all[i]);
4515
4516 (*predicted_element_intervals)[predicted_element_distributions->getSeriesName(i)] = interval;
4517 (*predicted_element_intervals)[predicted_element_distributions->getSeriesName(i)].SetValue(
4518 corrected_data.observation(i)->Value());
4519 }
4520
4521 ResultItem predicted_element_intervals_result;
4522 predicted_element_intervals_result.SetName("Predicted Samples Credible Intervals");
4523 predicted_element_intervals_result.SetShowAsString(true);
4524 predicted_element_intervals_result.SetShowTable(true);
4525 predicted_element_intervals_result.SetType(result_type::rangeset_with_observed);
4526 predicted_element_intervals_result.SetResult(predicted_element_intervals);
4527 predicted_element_intervals_result.setXAxisTitle("Constituent");
4528 predicted_element_intervals_result.setYAxisTitle("Concentration");
4529 predicted_element_intervals_result.SetYAxisMode(yaxis_mode::log);
4530 results.Append(predicted_element_intervals_result);
4531
4532 // ========== Result 5: Predicted Isotope Distributions ==========
4533 CMBTimeSeriesSet predicted_isotopes;
4534
4535 for (size_t i = 0; i < predicted_samples.size(); i++)
4536 {
4537 if (corrected_data.GetElementInformation(predicted_samples.getSeriesName(i))->Role ==
4539 {
4540 predicted_isotopes.append(predicted_samples[i], predicted_samples.getSeriesName(i));
4541 }
4542 }
4543
4544 CMBTimeSeriesSet* predicted_isotope_distributions = new CMBTimeSeriesSet();
4545 *predicted_isotope_distributions = predicted_isotopes.distribution(100, burnin_samples);
4546
4547 // Add observed values
4548 for (size_t i = 0; i < predicted_isotopes.size(); i++)
4549 {
4550 predicted_isotope_distributions->SetObservedValue(
4551 i, corrected_data.observation(i + element_names.size())->Value());
4552 }
4553
4554 ResultItem predicted_isotopes_result;
4555 predicted_isotopes_result.SetName("Posterior Predicted Isotopes");
4556 predicted_isotopes_result.SetShowAsString(false);
4557 predicted_isotopes_result.SetShowTable(true);
4558 predicted_isotopes_result.SetType(result_type::distribution_with_observed);
4559 predicted_isotopes_result.SetResult(predicted_isotope_distributions);
4560 results.Append(predicted_isotopes_result);
4561
4562 // ========== Result 6: Isotope Credible Intervals ==========
4563 RangeSet* predicted_isotope_intervals = new RangeSet();
4564 size_t element_offset = corrected_data.ElementOrder().size();
4565
4566 for (size_t i = 0; i < predicted_isotope_distributions->size(); i++)
4567 {
4568 Range interval;
4569 interval.Set(_range::low, percentile_2_5_all[i + element_offset]);
4570 interval.Set(_range::high, percentile_97_5_all[i + element_offset]);
4571 interval.SetMean(mean_all[i + element_offset]);
4572 interval.SetMedian(median_all[i + element_offset]);
4573
4574 (*predicted_isotope_intervals)[predicted_isotope_distributions->getSeriesName(i)] = interval;
4575 (*predicted_isotope_intervals)[predicted_isotope_distributions->getSeriesName(i)].SetValue(
4576 corrected_data.observation(i + element_offset)->Value());
4577 }
4578
4579 ResultItem predicted_isotope_intervals_result;
4580 predicted_isotope_intervals_result.SetName("Predicted Samples Credible Intervals for Isotopes");
4581 predicted_isotope_intervals_result.SetShowAsString(true);
4582 predicted_isotope_intervals_result.SetShowTable(true);
4583 predicted_isotope_intervals_result.SetType(result_type::rangeset_with_observed);
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)");
4587 predicted_isotope_intervals_result.SetYAxisMode(yaxis_mode::normal);
4588 results.Append(predicted_isotope_intervals_result);
4589
4590 // ========== Convergence diagnostics ==========
4591 // Split R-hat and effective sample size of every sampled quantity, from
4592 // the draws after burn-in. Draw k belongs to chain k mod (number of
4593 // chains). Appended last, so the panel and file numbers above stay the
4594 // same.
4595 CMBVector* rhat_values = new CMBVector(int(mcmc_samples->size()));
4596 CMBVector* ess_values = new CMBVector(int(mcmc_samples->size()));
4597 for (int i = 0; i < int(mcmc_samples->size()); i++)
4598 {
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));
4604 rhat_values->SetLabel(i, mcmc_samples->getSeriesName(i));
4605 ess_values->SetLabel(i, mcmc_samples->getSeriesName(i));
4606 (*rhat_values)[i] = d.rhat;
4607 (*ess_values)[i] = d.effective_sample_size;
4608 }
4609 // Values beyond the usual thresholds are shown in red: R-hat above 1.01,
4610 // fewer than 400 effective samples (Vehtari and others, 2021)
4611 rhat_values->SetLimit(_range::low, 0.0);
4612 rhat_values->SetLimit(_range::high, 1.01);
4613 ess_values->SetLimit(_range::low, 400.0);
4614 ess_values->SetLimit(_range::high, std::numeric_limits<double>::max());
4615
4616 ResultItem rhat_result;
4617 rhat_result.SetName("Convergence: split R-hat");
4618 rhat_result.SetType(result_type::vector);
4619 rhat_result.SetShowAsString(false);
4620 rhat_result.SetShowTable(true);
4621 rhat_result.SetShowGraph(false); // one bar per parameter is unreadable; the table is the useful view
4622 rhat_result.SetYAxisMode(yaxis_mode::normal);
4623 rhat_result.SetResult(rhat_values);
4624 rhat_result.setXAxisTitle("Parameter");
4625 rhat_result.setYAxisTitle("Split R-hat");
4626 results.Append(rhat_result);
4627
4628 ResultItem ess_result;
4629 ess_result.SetName("Convergence: effective sample size");
4630 ess_result.SetType(result_type::vector);
4631 ess_result.SetShowAsString(false);
4632 ess_result.SetShowTable(true);
4633 ess_result.SetShowGraph(false);
4634 ess_result.SetYAxisMode(yaxis_mode::normal);
4635 ess_result.SetResult(ess_values);
4636 ess_result.setXAxisTitle("Parameter");
4637 ess_result.setYAxisTitle("Effective sample size");
4638 results.Append(ess_result);
4639
4640 // Set progress to 100%
4641 progress_window->SetProgress(1.0);
4642
4643 // corrected_data is about to go out of scope; do not leave the sampler
4644 // pointing at it.
4645 mcmc->Model = nullptr;
4646
4647 return results;
4648}
4649
4650
4651// Replaces the characters Windows does not allow in a file or folder name, and
4652// the trailing dots and spaces it silently strips, so that the same name works
4653// on every platform.
4654static QString SafeFileName(const QString& name)
4655{
4656 QString safe = name;
4657 safe.replace(QStringLiteral(": "), QStringLiteral(" - ")); // "Convergence: split R-hat"
4658 for (QChar& c : safe)
4659 {
4660 if (c.unicode() < 32 || QStringLiteral("\\/:*?\"<>|").contains(c))
4661 c = QLatin1Char('_');
4662 }
4663 while (safe.endsWith(QLatin1Char('.')) || safe.endsWith(QLatin1Char(' ')))
4664 safe.chop(1);
4665 return safe.isEmpty() ? QStringLiteral("_") : safe;
4666}
4667
4669 const map<string, string>& arguments,
4671 ProgressReporter* progress_window,
4672 const string& working_folder,
4673 vector<string>* failed_writes)
4674{
4675 // A null reporter stands in for a missing one so that the progress calls
4676 // below need no null test. Callers that want no progress display pass
4677 // nullptr.
4678 NullProgressReporter discarded_progress;
4679 if (progress_window == nullptr)
4680 progress_window = &discarded_progress;
4681
4682 // The target samples marked for inclusion (Settings > Include/Exclude
4683 // Samples); the batch tools skip the others
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())
4689 return CMBMatrix();
4690
4691 // Initialize with first target sample
4692 InitializeParametersAndObservations(included_targets.front());
4693
4694 // Initialize contribution matrix: 4 columns per source (low, high, median, mean)
4695 const size_t num_target_samples = included_targets.size();
4696 const size_t num_columns = static_cast<size_t>(numberofsourcesamplesets_) * 4;
4697 CMBMatrix contribution_statistics(num_columns, num_target_samples);
4698
4699 // Set column labels
4700 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
4701 {
4702 const string& source_name = samplesetsorder_[source_idx];
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");
4707 }
4708
4709 // Process each target sample
4710 size_t sample_counter = 0;
4711 for (const string& sample_name : included_targets)
4712 {
4713 // Create output directory for this sample
4714 QDir sample_dir(QString::fromStdString(working_folder) + "/" +
4715 SafeFileName(QString::fromStdString(sample_name)));
4716 const bool sample_dir_ok = sample_dir.exists() || sample_dir.mkpath(".");
4717 if (!sample_dir_ok && failed_writes != nullptr)
4718 {
4719 failed_writes->push_back("could not create folder " +
4720 sample_dir.absolutePath().toStdString());
4721 }
4722
4723 // Set matrix row label
4724 contribution_statistics.SetRowLabel(sample_counter, sample_name);
4725
4726 // Update progress label
4727 progress_window->SetLabel(QString::fromStdString(sample_name));
4728
4729 // Run MCMC analysis for this sample
4730 // The raw chain log goes in the sample's own folder, so that each sample
4731 // keeps its log instead of the next sample truncating a shared one. If
4732 // that folder could not be created, the log falls back to the parent.
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);
4735
4736 // Save all result items to text files. The result keys have the form
4737 // "<index>:<name>", and a colon in a path on Windows names an NTFS
4738 // alternate data stream, so the key must be made safe before use.
4739 for (map<string, ResultItem>::iterator result_item = mcmc_results.begin();
4740 sample_dir_ok && result_item != mcmc_results.end();
4741 result_item++)
4742 {
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))
4747 {
4748 if (failed_writes != nullptr)
4749 failed_writes->push_back(file_path.toStdString() + ": " +
4750 output_file.errorString().toStdString());
4751 continue;
4752 }
4753 result_item->second.Result()->writetofile(&output_file);
4754 output_file.close();
4755 if (output_file.error() != QFileDevice::NoError && failed_writes != nullptr)
4756 {
4757 failed_writes->push_back(file_path.toStdString() + ": " +
4758 output_file.errorString().toStdString());
4759 }
4760 }
4761
4762 // Extract contribution statistics from credible intervals
4763 RangeSet* credible_intervals = static_cast<RangeSet*>(
4764 mcmc_results.at("3:Source Contribution Credible Intervals").Result());
4765
4766 for (size_t source_idx = 0; source_idx < numberofsourcesamplesets_; source_idx++)
4767 {
4768 const string contribution_name = samplesetsorder_[source_idx] + "_contribution";
4769 const Range& contribution_interval = credible_intervals->at(contribution_name);
4770
4771 // Store statistics: low (2.5%), high (97.5%), median, mean
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();
4776 }
4777
4778 sample_counter++;
4779
4780 // Update batch progress
4781 progress_window->SetProgress2(double(sample_counter) / double(num_target_samples));
4782
4783 // Clear MCMC progress charts for next sample
4784 progress_window->ClearGraph(0);
4785 progress_window->ClearGraph(1);
4786 progress_window->ClearGraph(2);
4787 }
4788
4789 // Set batch progress to 100%
4790 progress_window->SetProgress2(1.0);
4791
4792 return contribution_statistics;
4793}
4794bool SourceSinkData::ToolsUsed(const string& tool_name)
4795{
4796 // Search for tool in the tools_used list
4797 std::list<string>::iterator iter = std::find(tools_used_.begin(), tools_used_.end(), tool_name);
4798
4799 // Return true if found, false if not found
4800 return (iter != tools_used_.end());
4801}
4802
4804{
4805 // Search for first organic carbon constituent
4806 for (map<string, element_information>::iterator element = element_information_.begin();
4807 element != element_information_.end();
4808 element++)
4809 {
4810 if (element->second.Role == element_information::role::organic_carbon)
4811 {
4812 return element->first;
4813 }
4814 }
4815
4816 // No organic carbon constituent found
4817 return "";
4818}
4819
4821{
4822 // Search for first particle size constituent
4823 for (map<string, element_information>::iterator element = element_information_.begin();
4824 element != element_information_.end();
4825 element++)
4826 {
4827 if (element->second.Role == element_information::role::particle_size)
4828 {
4829 return element->first;
4830 }
4831 }
4832
4833 // No particle size constituent found
4834 return "";
4835}
4836
4838{
4839 // Leave-one-out classification of the source samples by linear
4840 // discriminant analysis with equal priors, as in Sed_SAT 1.0 (MASS::lda
4841 // with CV = TRUE): each sample in turn is left out, the group means and
4842 // the pooled within-group covariance are computed from the other samples,
4843 // and the sample is assigned to the group whose mean is nearest in
4844 // Mahalanobis distance.
4845 const vector<string> constituents = GetElementNames();
4846 vector<string> groups;
4847 vector<arma::mat> data; // per group: samples x constituents
4848 for (auto& [group_name, profile_set] : *this)
4849 {
4850 if (group_name == target_group_ || profile_set.size() == 0)
4851 continue;
4852 arma::mat values(profile_set.size(), constituents.size());
4853 size_t row = 0;
4854 for (const auto& [sample_name, profile] : profile_set)
4855 {
4856 for (size_t j = 0; j < constituents.size(); j++)
4857 values(row, j) = profile.GetValue(constituents[j]);
4858 row++;
4859 }
4860 groups.push_back(group_name);
4861 data.push_back(values);
4862 }
4863
4864 const size_t num_groups = groups.size();
4865 CMBMatrix confusion(int(num_groups) + 1, int(num_groups)); // (columns, rows)
4866 for (size_t g = 0; g < num_groups; g++)
4867 {
4868 confusion.SetRowLabel(int(g), groups[g]);
4869 confusion.SetColumnLabel(int(g), groups[g]);
4870 }
4871 confusion.SetColumnLabel(int(num_groups), "% correct");
4872 if (num_groups < 2 || constituents.empty())
4873 return confusion;
4874
4875 for (size_t g = 0; g < num_groups; g++)
4876 {
4877 size_t correct = 0;
4878 for (arma::uword i = 0; i < data[g].n_rows; i++)
4879 {
4880 // Means and pooled covariance without sample i of group g
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++)
4885 {
4886 arma::mat values = data[h];
4887 if (h == g)
4888 values.shed_row(i);
4889 if (values.n_rows == 0)
4890 {
4891 means[h] = arma::rowvec(constituents.size());
4892 means[h].fill(arma::datum::nan);
4893 continue;
4894 }
4895 means[h] = arma::mean(values, 0);
4896 // In-place form: Armadillo 4 (used by SedSat3.vcxproj) has no
4897 // binary each_row() - rowvec
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;
4902 }
4903 if (degrees_of_freedom <= 0)
4904 continue;
4905 // A pseudo-inverse keeps the classification defined when the
4906 // covariance is singular (more constituents than samples)
4907 const arma::mat inverse = arma::pinv(scatter / degrees_of_freedom);
4908
4909 const arma::rowvec x = data[g].row(i);
4910 size_t best = 0;
4911 double best_distance = arma::datum::inf;
4912 for (size_t h = 0; h < num_groups; h++)
4913 {
4914 if (!means[h].is_finite())
4915 continue;
4916 const arma::rowvec d = x - means[h];
4917 const double distance = arma::as_scalar(d * inverse * d.t());
4918 if (distance < best_distance)
4919 {
4920 best_distance = distance;
4921 best = h;
4922 }
4923 }
4924 confusion.matr[g][best] += 1;
4925 if (best == g)
4926 correct++;
4927 }
4928 // Percentage to one decimal place
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;
4931 }
4932 return confusion;
4933}
4934
4936{
4937 vector<string> element_names = GetElementNames();
4938 CMatrix within_group_covariance(element_names.size());
4939
4940 // Accumulate weighted covariance matrices from each source group
4941 int total_degrees_of_freedom = 0;
4942 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
4943 source_group != end();
4944 source_group++)
4945 {
4946 if (source_group->first != target_group_)
4947 {
4948 // Weight by degrees of freedom (n - 1) for this group
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;
4952 }
4953 }
4954
4955 // Return pooled within-group covariance
4956 return within_group_covariance / double(total_degrees_of_freedom);
4957}
4958
4960{
4961 vector<string> element_names = GetElementNames();
4962 CMatrix between_group_covariance(element_names.size());
4963
4964 // Get overall mean across all sources
4965 CMBVector overall_mean = MeanElementalContent();
4966
4967 // Accumulate weighted outer products of group mean deviations
4968 double total_samples = 0.0;
4969 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
4970 source_group != end();
4971 source_group++)
4972 {
4973 if (source_group->first != target_group_)
4974 {
4975 // Compute deviation of group mean from overall mean
4976 CMBVector group_mean = MeanElementalContent(source_group->first);
4977 CMBVector deviation = overall_mean - group_mean;
4978
4979 // Add weighted outer product: n_i × (μ_i - μ)(μ_i - μ)ᵀ
4980 size_t group_size = source_group->second.size();
4981 for (size_t i = 0; i < element_names.size(); i++)
4982 {
4983 for (size_t j = 0; j < element_names.size(); j++)
4984 {
4985 between_group_covariance[i][j] += deviation[i] * deviation[j] * group_size;
4986 }
4987 }
4988
4989 total_samples += group_size;
4990 }
4991 }
4992
4993 // Return normalized between-group covariance
4994 return between_group_covariance / total_samples;
4995}
4996
4998{
4999 vector<string> element_names = GetElementNames();
5000 CMatrix total_scatter(element_names.size());
5001
5002 // Get overall mean across all sources
5003 CMBVector overall_mean = MeanElementalContent();
5004
5005 // Accumulate sum of squared deviations from overall mean
5006 double total_samples = 0.0;
5007 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5008 source_group != end();
5009 source_group++)
5010 {
5011 if (source_group->first != target_group_)
5012 {
5013 // Process each sample in this group
5014 for (map<string, Elemental_Profile>::iterator sample = source_group->second.begin();
5015 sample != source_group->second.end();
5016 sample++)
5017 {
5018 // Add outer product of deviation: (x - μ)(x - μ)ᵀ
5019 for (size_t i = 0; i < element_names.size(); i++)
5020 {
5021 for (size_t j = 0; j < element_names.size(); j++)
5022 {
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;
5026 }
5027 }
5028 }
5029
5030 total_samples += source_group->second.size();
5031 }
5032 }
5033
5034 // Return normalized total scatter matrix
5035 return total_scatter / total_samples;
5036}
5037
5039{
5040 // Get covariance matrices
5041 CMatrix_arma within_group_cov = WithinGroupCovarianceMatrix();
5042 CMatrix_arma between_group_cov = BetweenGroupCovarianceMatrix();
5043 CMatrix_arma total_cov = within_group_cov + between_group_cov;
5044
5045 // Compute Wilks' Lambda = |S_W| / |S_T|
5046 double numerator = within_group_cov.det();
5047 double denominator = total_cov.det();
5048
5049 // Use absolute values for numerical stability
5050 return fabs(numerator) / fabs(denominator);
5051}
5052
5054{
5055 int num_elements = GetElementNames().size();
5056
5057 // Get Wilks' Lambda (capped at 1.0)
5058 double wilks_lambda = min(WilksLambda(), 1.0);
5059
5060 // Transform to chi-squared statistic
5061 double sample_size = TotalNumberofSourceSamples();
5062 double correction_factor = (num_elements + (numberofsourcesamplesets_ - 1.0)) / 2.0;
5063 double chi_squared = -(sample_size - 1.0 - correction_factor) * log(wilks_lambda);
5064
5065 // Compute degrees of freedom
5066 double degrees_of_freedom = NAN;
5067 if (target_group_ != "")
5068 {
5069 // Target group present: exclude from group count
5070 degrees_of_freedom = num_elements * (numberofsourcesamplesets_ - 2.0);
5071 }
5072 else
5073 {
5074 // No target group
5075 degrees_of_freedom = num_elements * (numberofsourcesamplesets_ - 1.0);
5076 }
5077
5078 // Compute p-value from chi-squared distribution
5079 double p_value = gsl_cdf_chisq_Q(chi_squared, degrees_of_freedom);
5080
5081 return p_value;
5082}
5083
5085{
5086 // Get discriminant eigenvector
5087 CMBVector discriminant_function = DFA_eigvector();
5088
5089 CMBVectorSet projected_scores;
5090
5091 // Project each group onto discriminant axis
5092 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5093 source_group != end();
5094 source_group++)
5095 {
5096 // Compute discriminant scores for this group
5097 CMBVector group_scores = source_group->second.CalculateDotProduct(discriminant_function);
5098 projected_scores.Append(source_group->first, group_scores);
5099 }
5100
5101 return projected_scores;
5102}
5103
5104CMBVectorSet SourceSinkData::DFA_Projected(const string& /*source1*/, const string& /*source2*/)
5105{
5106 // Get discriminant eigenvector
5107 CMBVector discriminant_function = DFA_eigvector();
5108
5109 CMBVectorSet projected_scores;
5110
5111 // Project each group onto discriminant axis
5112 // Note: Parameters source1 and source2 not currently used
5113 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5114 source_group != end();
5115 source_group++)
5116 {
5117 // Compute discriminant scores for this group
5118 CMBVector group_scores = source_group->second.CalculateDotProduct(discriminant_function);
5119 projected_scores.Append(source_group->first, group_scores);
5120 }
5121
5122 return projected_scores;
5123}
5124
5125CMBVectorSet SourceSinkData::DFA_Projected(const string& /*source1*/, SourceSinkData* original)
5126{
5127 // Get discriminant eigenvector from current (reduced) dataset
5128 CMBVector discriminant_function = DFA_eigvector();
5129
5130 CMBVectorSet projected_scores;
5131
5132 // Project samples from original dataset onto discriminant axis
5133 for (map<string, Elemental_Profile_Set>::iterator source_group = original->begin();
5134 source_group != original->end();
5135 source_group++)
5136 {
5137 // Skip target group
5138 if (source_group->first != original->target_group_)
5139 {
5140 // Compute discriminant scores for this group
5141 CMBVector group_scores = source_group->second.CalculateDotProduct(discriminant_function);
5142 projected_scores.Append(source_group->first, group_scores);
5143 }
5144 }
5145
5146 return projected_scores;
5147}
5148
5150{
5151 // Get covariance matrices
5152 CMatrix_arma between_group_cov = BetweenGroupCovarianceMatrix();
5153 CMatrix_arma within_group_cov = WithinGroupCovarianceMatrix();
5154
5155 // Invert within-group covariance
5156 CMatrix_arma inv_within_cov = inv(within_group_cov);
5157
5158 // Check if inversion failed (singular matrix)
5159 if (inv_within_cov.getnumrows() == 0)
5160 {
5161 return CMBVector(); // Return empty vector
5162 }
5163
5164 // Compute product matrix for eigenvalue problem
5165 CMatrix_arma product_matrix = inv_within_cov * between_group_cov;
5166
5167 // Solve eigenvalue problem
5168 arma::cx_vec eigenvalues;
5169 arma::cx_mat eigenvectors;
5170 eig_gen(eigenvalues, eigenvectors, product_matrix);
5171
5172 // Extract real parts
5173 CVector_arma real_eigenvalues = GetReal(eigenvalues);
5174 CMatrix_arma real_eigenvectors = GetReal(eigenvectors);
5175
5176 // Find eigenvector corresponding to largest eigenvalue (by absolute value)
5177 size_t max_eigenvalue_index = real_eigenvalues.abs_max_elems();
5178 CMBVector discriminant_function = CVector_arma(real_eigenvectors.getcol(max_eigenvalue_index));
5179
5180 // Label with element names
5181 vector<string> element_names = GetElementNames();
5182 discriminant_function.SetLabels(element_names);
5183
5184 return discriminant_function;
5185}
5186
5187CMBVector SourceSinkData::DFA_weight_vector(const string& source1, const string& source2)
5188{
5189 // Get covariance matrices for both groups
5190 CMatrix_arma cov_matrix1 = at(source1).CalculateCovarianceMatrix();
5191 CMatrix_arma cov_matrix2 = at(source2).CalculateCovarianceMatrix();
5192
5193 // Get mean vectors for both groups
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;
5198
5199 // Compute Fisher's linear discriminant: w = (μ₂ - μ₁) / (Σ₁ + Σ₂)
5200 CMatrix_arma pooled_cov = cov_matrix1 + cov_matrix2;
5201 CVector weight_vector_arma = (mean2 - mean1) / pooled_cov;
5202
5203 // Convert to CMBVector and normalize
5204 CMBVector weight_vector = weight_vector_arma;
5205 weight_vector = weight_vector / weight_vector.norm2();
5206
5207 // Label with element names
5208 weight_vector.SetLabels(GetElementNames());
5209
5210 return weight_vector;
5211}
5212
5214{
5215 // Check if group exists
5216 if (count(group_name) == 0)
5217 {
5218 return CMBVector(); // Return empty vector
5219 }
5220
5221 // Compute mean concentrations for this group
5222 vector<string> element_names = GetElementNames();
5223 CMBVector group_mean = at(group_name).CalculateElementMeans();
5224 group_mean.SetLabels(element_names);
5225
5226 return group_mean;
5227}
5228
5230{
5231 vector<string> element_names = GetElementNames();
5232 CMBVector weighted_mean(element_names.size());
5233
5234 // Accumulate weighted means from each source group
5235 double total_samples = 0.0;
5236 for (map<string, Elemental_Profile_Set>::iterator source_group = begin();
5237 source_group != end();
5238 source_group++)
5239 {
5240 // Skip target group
5241 if (source_group->first != target_group_)
5242 {
5243 // Weight group mean by sample size
5244 size_t group_size = source_group->second.size();
5245 CMBVector group_mean = MeanElementalContent(source_group->first);
5246
5247 weighted_mean += double(group_size) * group_mean;
5248 total_samples += double(group_size);
5249 }
5250 }
5251
5252 // Set labels and normalize by total sample count
5253 weighted_mean.SetLabels(element_order_);
5254
5255 return weighted_mean / total_samples;
5256}
5257
5259 const string& source1,
5260 const string& source2)
5261{
5262 // Initialize result vectors: [0]=p-values, [1]=Wilks' Lambda, [2]=F-test p-values
5263 vector<CMBVector> stepwise_results(3);
5264
5265 vector<string> element_names = GetElementNames();
5266 vector<string> selected_elements;
5267
5268 // Forward selection: add one element at a time
5269 for (size_t step = 0; step < element_names.size(); step++)
5270 {
5271 // Update progress
5272 if (rtw_)
5273 {
5274 rtw_->SetProgress(double(step + 1) / double(element_names.size()));
5275 }
5276
5277 // Find best element to add next
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;
5282
5283 // Test each unselected element
5284 for (size_t j = 0; j < element_names.size(); j++)
5285 {
5286 // Skip if already selected
5287 if (lookup(selected_elements, element_names[j]) == -1)
5288 {
5289 // Create candidate selection with this element added
5290 vector<string> candidate_elements = selected_elements;
5291 candidate_elements.push_back(element_names[j]);
5292
5293 // Extract dataset with only candidate elements
5294 SourceSinkData candidate_dataset = ExtractSpecificElements(candidate_elements);
5295
5296 // Perform DFA on candidate dataset
5297 DFA_result candidate_dfa = candidate_dataset.DiscriminantFunctionAnalysis(source1, source2);
5298
5299 // Check if DFA succeeded
5300 if (candidate_dfa.eigen_vectors.size() == 0)
5301 {
5302 return stepwise_results; // Return empty results on failure
5303 }
5304
5305 // Update best if this element improves discrimination
5306 if (candidate_dfa.p_values[0] < best_p_value)
5307 {
5308 best_element = element_names[j];
5309 best_p_value = candidate_dfa.p_values[0];
5310 best_wilks_lambda = candidate_dfa.wilkslambda[0];
5311 best_f_test_p_value = candidate_dfa.F_test_P_value[0];
5312 }
5313 }
5314 }
5315
5316 // Record statistics for best element at this step
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);
5320
5321 // Add best element to selection
5322 selected_elements.push_back(best_element);
5323 }
5324
5325 return stepwise_results;
5326}
5327
5329{
5330 // Initialize result vectors: [0]=p-values, [1]=Wilks' Lambda, [2]=F-test p-values
5331 vector<CMBVector> stepwise_results(3);
5332
5333 vector<string> element_names = GetElementNames();
5334 vector<string> selected_elements;
5335
5336 // Forward selection: add one element at a time
5337 for (size_t step = 0; step < element_names.size(); step++)
5338 {
5339 // Update progress
5340 if (rtw_)
5341 {
5342 rtw_->SetProgress(double(step + 1) / double(element_names.size()));
5343 }
5344
5345 // Find best element to add next
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;
5350
5351 // Test each unselected element
5352 for (size_t j = 0; j < element_names.size(); j++)
5353 {
5354 // Skip if already selected
5355 if (lookup(selected_elements, element_names[j]) == -1)
5356 {
5357 // Create candidate selection with this element added
5358 vector<string> candidate_elements = selected_elements;
5359 candidate_elements.push_back(element_names[j]);
5360
5361 // Extract dataset with only candidate elements
5362 SourceSinkData candidate_dataset = ExtractSpecificElements(candidate_elements);
5363
5364 // Compute multi-group DFA statistics
5365 double p_value = candidate_dataset.DFA_P_Value();
5366
5367 // Update best if this element improves discrimination
5368 if (p_value < best_p_value)
5369 {
5370 best_element = element_names[j];
5371 best_p_value = p_value;
5372 best_wilks_lambda = candidate_dataset.WilksLambda();
5373
5374 // Compute F-test p-value from projections
5375 CMBVectorSet projected = candidate_dataset.DFA_Projected();
5376 best_f_test_p_value = projected.FTest_p_value();
5377 }
5378 }
5379 }
5380
5381 // Record statistics for best element at this step
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);
5385
5386 // Add best element to selection
5387 selected_elements.push_back(best_element);
5388 }
5389
5390 return stepwise_results;
5391}
5392
5393vector<CMBVector> SourceSinkData::StepwiseDiscriminantFunctionAnalysis(const string& source1)
5394{
5395 // Initialize result vectors: [0]=p-values, [1]=Wilks' Lambda, [2]=F-test p-values
5396 vector<CMBVector> stepwise_results(3);
5397
5398 vector<string> element_names = GetElementNames();
5399 vector<string> selected_elements;
5400
5401 // Forward selection: add one element at a time
5402 for (size_t step = 0; step < element_names.size(); step++)
5403 {
5404 // Update progress
5405 if (rtw_)
5406 {
5407 rtw_->SetProgress(double(step + 1) / double(element_names.size()));
5408 }
5409
5410 // Find best element to add next
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;
5415
5416 // Test each unselected element
5417 for (size_t j = 0; j < element_names.size(); j++)
5418 {
5419 // Skip if already selected
5420 if (lookup(selected_elements, element_names[j]) == -1)
5421 {
5422 // Create candidate selection with this element added
5423 vector<string> candidate_elements = selected_elements;
5424 candidate_elements.push_back(element_names[j]);
5425
5426 // Extract dataset with only candidate elements
5427 SourceSinkData candidate_dataset = ExtractSpecificElements(candidate_elements);
5428
5429 // Perform one-vs-rest DFA on candidate dataset
5430 DFA_result candidate_dfa = candidate_dataset.DiscriminantFunctionAnalysis(source1);
5431
5432 // Update best if this element improves discrimination
5433 if (candidate_dfa.p_values[0] < best_p_value)
5434 {
5435 best_element = element_names[j];
5436 best_p_value = candidate_dfa.p_values[0];
5437 best_wilks_lambda = candidate_dfa.wilkslambda[0];
5438 best_f_test_p_value = candidate_dfa.F_test_P_value[0];
5439 }
5440 }
5441 }
5442
5443 // Record statistics for best element at this step
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);
5447
5448 // Add best element to selection
5449 selected_elements.push_back(best_element);
5450 }
5451
5452 return stepwise_results;
5453}
5454
5455// ========================================
5456// METHOD DEFINITIONS TO MOVE TO sourcesinkdata.cpp
5457// ========================================
5458// These were previously inline in the header and should now be implemented in the .cpp file
5459
5460// ========== Accessors ==========
5461
5462vector<Parameter>& SourceSinkData::Parameters()
5463{
5464 return parameters_;
5465}
5466
5468{
5469 return parameters_.size();
5470}
5471
5473{
5474 return observations_.size();
5475}
5476
5478{
5479 if (i < parameters_.size())
5480 return &parameters_[i];
5481 else
5482 return nullptr;
5483}
5484
5486{
5487 if (i < parameters_.size())
5488 return &parameters_[i];
5489 else
5490 return nullptr;
5491}
5492
5494{
5495 if (i < observations_.size())
5496 return &observations_[i];
5497 else
5498 return nullptr;
5499}
5500
5501bool SourceSinkData::SetTargetGroup(const string& targroup)
5502{
5503 target_group_ = targroup;
5504 return true;
5505}
5506
5508{
5509 return target_group_;
5510}
5511
5516
5521
5523{
5524 rtw_ = _rtw;
5525}
5526
5527map<string, element_information>* SourceSinkData::GetElementInformation()
5528{
5529 return &element_information_;
5530}
5531
5533{
5534 if (element_information_.count(element_name))
5535 return &element_information_.at(element_name);
5536 else
5537 return nullptr;
5538}
5539
5541{
5542 if (element_distributions_.count(element_name))
5543 return &element_distributions_.at(element_name);
5544 else
5545 return nullptr;
5546}
5547
5548ConcentrationSet* SourceSinkData::GetElementDistribution(const string& element_name, const string& sample_group)
5549{
5550 if (!GetSampleSet(sample_group))
5551 {
5552 cout << "Sample Group '" + sample_group + "' does not exist!" << std::endl;
5553 return nullptr;
5554 }
5555 if (!GetSampleSet(sample_group)->GetElementDistribution(element_name))
5556 {
5557 cout << "Element '" + element_name + "' does not exist!" << std::endl;
5558 return nullptr;
5559 }
5560 return GetSampleSet(sample_group)->GetElementDistribution(element_name);
5561}
5562
5563// ========== Ordering Accessors ==========
5564
5566{
5567 return samplesetsorder_;
5568}
5569
5571{
5572 return samplesetsorder_;
5573}
5574
5576{
5577 return constituent_order_;
5578}
5579
5581{
5582 return element_order_;
5583}
5584
5586{
5587 return isotope_order_;
5588}
5589
5591{
5592 return size_om_order_;
5593}
5594
5595// ========== OM/Size Constituent Management ==========
5596
5597void SourceSinkData::SetOMandSizeConstituents(const string& _omconstituent, const string& _sizeconstituent)
5598{
5599 omconstituent_ = _omconstituent;
5600 sizeconstituent_ = _sizeconstituent;
5601}
5602
5603void SourceSinkData::SetOMandSizeConstituents(const vector<string>& _omsizeconstituents)
5604{
5605 if (_omsizeconstituents.size() == 0)
5606 return;
5607 else if (_omsizeconstituents.size() == 1)
5608 omconstituent_ = _omsizeconstituents[0];
5609 else if (_omsizeconstituents.size() == 2)
5610 {
5611 omconstituent_ = _omsizeconstituents[0];
5612 sizeconstituent_ = _omsizeconstituents[1];
5613 }
5614}
5615
5617{
5618 vector<string> out;
5619 out.push_back(omconstituent_);
5620 out.push_back(sizeconstituent_);
5621 return out;
5622}
5623
5624// ========== Options Management ==========
5625
5626QMap<QString, double>* SourceSinkData::GetOptions()
5627{
5628 return &options_;
5629}
5630
5631// ========== Output Path Management ==========
5632
5634{
5635 return outputpath_;
5636}
5637
5638bool SourceSinkData::SetOutputPath(const string& output_path)
5639{
5640 outputpath_ = output_path;
5641 return true;
5642}
5643
5644// ========== Selected Target Sample Management ==========
5645
5646bool SourceSinkData::SetSelectedTargetSample(const string& sample_name)
5647{
5648 // Validate that sample exists in target group
5649 if (count(target_group_) == 0)
5650 return false;
5651
5652 if (at(target_group_).count(sample_name) == 0)
5653 return false;
5654
5655 selected_target_sample_ = sample_name;
5656 return true;
5657}
5658
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
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.
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
int size() const
Gets number of elements in vector.
Definition cmbvector.h:224
double valueAt(int i) const
Gets value at specified index.
Markov Chain Monte Carlo sampler for Bayesian parameter estimation.
Definition MCMC.h:351
CMBTimeSeriesSet predicted
Model predictions as time series set.
Definition MCMC.h:562
bool SetProperty(const string &varname, const string &value)
Set MCMC properties from string key-value pairs.
Definition MCMC.hpp:75
bool step(int k, int chain_counter)
Perform single MCMC step for one chain.
Definition MCMC.hpp:367
T * Model
Pointer to the model object being calibrated.
Definition MCMC.h:359
void initialize(CMBTimeSeriesSet *results, bool random=false)
Initialize MCMC chains with starting parameter values.
Definition MCMC.hpp:214
void SetRandomSeed(std::uint64_t seed)
Sets the master seed for the chains' random streams.
Definition MCMC.hpp:706
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.
Definition interface.h:236
vector< string > & GetIndependentVariableNames()
void SetEffective(int i, bool eff)
ProgressReporter that discards everything reported to it.
void SetName(const std::string &nam)
Definition observation.h:15
void SetPredictedValue(const double &value)
Definition observation.h:28
void AppendValues(const double &t, const double &val)
double Value()
Definition observation.h:20
double PredictedValue()
Definition observation.h:27
Represents a model parameter with prior distribution and constraints.
Definition parameter.h:76
void SetPriorDistribution(distribution_type dist_type)
Set the type of prior probability distribution.
Definition parameter.h:131
double Value() const
Get the current parameter value.
Definition parameter.h:261
void SetRange(const vector< double > &rng)
Set the parameter range from a vector.
Definition parameter.cpp:21
string Name() const
Get the parameter name.
Definition parameter.h:251
void SetName(const string &nam)
Set the parameter name/identifier.
Definition parameter.h:243
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.
Definition range.h:11
double Mean() const
Definition range.h:23
void Set(_range lowhigh, const double &value)
Definition range.cpp:67
double Median() const
Definition range.h:25
void SetValue(const double value)
Definition range.h:27
double mean
Definition range.h:32
void SetMedian(const double &m)
Definition range.h:26
void SetMean(const double &m)
Definition range.h:24
double Get(_range lowhigh) const
Definition range.cpp:74
void SetShowGraph(bool state)
Definition resultitem.h:83
void setYAxisTitle(const string &title)
Definition resultitem.h:42
void SetXAxisMode(xaxis_mode mode)
Definition resultitem.h:29
void SetYLimit(_range highlow, const double &value)
Definition resultitem.h:69
void SetName(const string &_name)
Definition resultitem.h:24
Interface * Result() const
Definition resultitem.h:20
void SetResult(Interface *_result)
Definition resultitem.h:21
void SetShowTable(bool state)
Definition resultitem.h:81
void setXAxisTitle(const string &title)
Definition resultitem.h:34
void SetYAxisMode(yaxis_mode mode)
Definition resultitem.h:28
void SetShowAsString(bool value)
Definition resultitem.h:32
void SetType(const result_type &_type)
Definition resultitem.h:26
void Append(const ResultItem &)
Definition results.cpp:28
void SetError(const string &_error)
Definition results.h:28
void AppendError(const string &_error)
Definition results.h:29
void SetName(const string &_name)
Definition results.h:24
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 &parameters, 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_
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.
ProgressReporter * rtw_
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.
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.
Definition parameter.h:17
@ high
Upper bound of the parameter range.
Definition parameter.h:18
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
Definition resultitem.h:9
@ predicted_concentration
Definition resultitem.h:9
@ rangeset_with_observed
Definition resultitem.h:9
@ stacked_bar_chart
Definition resultitem.h:9
@ elemental_profile_set
Definition resultitem.h:9
static QString SafeFileName(const QString &name)
transformation
estimation_mode
@ elemental_profile_and_contribution
@ source_elemental_profiles_based_on_source_data
CMBVectorSet projected
CMBVector p_values
CMBVectorSet eigen_vectors
CMBVector F_test_P_value
CMBVector wilkslambda
CMBVectorSetSet multi_projected
vector< string > sample_names
vector< double > values
Metadata describing an element's role and properties in analysis.
double standard_ratio
Standard isotopic ratio for normalization.
enum element_information::role Role
string notes
Free-text notes, e.g. why it was excluded.
role
Classification of element types.
@ 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.
string base_element
Parent element for isotopes.
double effective_sample_size
multi-chain ESS
vector< vector< double > > values
vector< string > element_names
vector< string > sample_names