SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
sourcesinkdata.h
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#ifndef SOURCESINKDATA_H
5#define SOURCESINKDATA_H
6
7#include "randomstream.h"
9#include "vector"
10#include "parameter.h"
11#include "observation.h"
12#include "contribution.h"
13#include "results.h"
14#include "progressreporter.h"
15#include "fstream"
16#include "qjsonobject.h"
17#include "cmbvector.h"
18#include "cmbvectorset.h"
19#include "cmbvectorsetset.h"
20#include "MCMC.h"
21
23
25{
26 vector<string> element_names;
27 vector<string> sample_names;
28 vector<vector<double>> values;
29};
30
32{
33 string group_name;
34 vector<string> sample_names;
35 vector<double> values;
36};
37
39{
40 vector<string> group_names;
41 vector<string> sample_names;
42 vector<vector<double>> values;
43};
44
54
56{
57 double F = 0;
58 double SST = 0;
59 double SSB = 0;
60 double SSW = 0;
61 double MSB = 0;
62 double MSW = 0;
63 double p_value = 0;
64};
65
67
68enum class negative_reporting { list, complete };
69
70class SourceSinkData : public map<string, Elemental_Profile_Set>
71{
72public:
73 // ========== Construction and Assignment ==========
74
82
92 SourceSinkData(const SourceSinkData& other);
93
104
105 // ========== Data Loading and Management ==========
106
119 void Clear();
120
133 const string& name,
135 );
136
147 vector<string> SourceGroupNames() const;
148
160 bool SetSelectedTargetSample(const string& sample_name);
161
172
182 bool SetTargetGroup(const string& targroup);
183
189 string GetTargetGroup() const;
190
191 // ========== Dataset Creation and Filtering ==========
192
211 const string& target,
212 bool omnsizecorrect,
213 map<string, element_information>* elementinfo
214 );
215
236 bool exclude_samples,
237 bool exclude_elements,
238 bool omnsizecorrect,
239 const string& target = ""
240 ) const;
241
252 bool exclude_samples,
253 bool exclude_elements,
254 bool omnsizecorrect,
255 const string& target = ""
256 ) const;
257
268 SourceSinkData ExtractChemicalElements(bool isotopes) const;
269
293 SourceSinkData BoxCoxTransformed(bool calculate_optimal_lambda = false);
294
295 // ========== Element Information Management ==========
296
305 map<string, element_information>* GetElementInformation();
306
320 void IncludeExcludeElementsBasedOn(const vector<string>& elements);
321
332 Distribution* GetFittedDistribution(const string& element_name);
333
334 // ========== OM/Size Corrections ==========
335
361 const string& om,
362 const string& particle_size,
363 regression_form form,
364 const double& p_value_threshold = 0.05
365 );
366
375 vector<string> OMandSizeConstituents();
376
390 vector<ResultItem> GetMLRResults();
391
402 string FirstOMConstituent();
403
413 string FirstSizeConstituent();
414
421 void SetOMandSizeConstituents(const string& _omconstituent, const string& _sizeconstituent);
422
428 void SetOMandSizeConstituents(const vector<string>& _omsizeconstituents);
429
430 // ========== Outlier Analysis ==========
431
451 void OutlierAnalysisForAll(const double& lower_threshold = -3, const double& upper_threshold = 3);
452
453 // ========== Validation Tests ==========
454
468 vector<string> NegativeValueCheck();
469
485 vector<string> NegativeContributionCheck();
486
512 CMBVector BracketTest(const string& target_sample, bool correct_based_on_om_n_size, double tolerance = 0);
513
536 CMBMatrix BracketTest(bool correct_based_on_om_n_size, bool exclude_elements, bool exclude_samples, double tolerance = 0);
537
538 // ========== Statistical Analysis - Discriminant Function Analysis ==========
539
562
577 DFA_result DiscriminantFunctionAnalysis(const string& source1, const string& source2);
578
591 DFA_result DiscriminantFunctionAnalysis(const string& source1);
592
611 vector<CMBVector> StepwiseDiscriminantFunctionAnalysis(
612 const string& source1,
613 const string& source2
614 );
615
629 vector<CMBVector> StepwiseDiscriminantFunctionAnalysis();
630
643 vector<CMBVector> StepwiseDiscriminantFunctionAnalysis(const string& source1);
644
645 // ========== Statistical Analysis - Differentiation Power ==========
646
666 Elemental_Profile_Set DifferentiationPower(bool use_log, bool include_target);
667
682
696
722 Elemental_Profile DifferentiationPower_Percentage(const string& source1, const string& source2);
723
750 Elemental_Profile DifferentiationPower(const string& source1, const string& source2, bool use_log);
751
774 Elemental_Profile t_TestPValue(const string& source1, const string& source2, bool use_log);
775
776 // ========== Statistical Analysis - ANOVA ==========
777
794 CMBVector ANOVA(bool use_log);
795
813 ANOVA_info ANOVA(const string& element, bool use_log);
814
815 // ========== Parameter and Observation Setup ==========
816
827 string GetParameterName(int index) const;
828
847 const string& targetsamplename,
849 );
850
862
886 bool SetParameterValue(size_t index, double value);
887
897
898
899
900 // ========== Optimization - Levenberg-Marquardt ==========
901
924
942 transformation transform,
943 bool apply_om_size_correction,
944 map<string, vector<string>>& negative_elements
945 );
946
955 CVector GetPredictedValues();
956
975
976 // ========== MCMC Analysis ==========
977
998 const string& target_sample,
999 map<string, string> arguments,
1001 ProgressReporter* progress_window,
1002 const string& working_folder
1003 );
1004
1031 const map<string, string>& arguments,
1033 ProgressReporter* progress_window,
1034 const string& working_folder,
1035 vector<string>* failed_writes = nullptr
1036 );
1037
1038 // --- Likelihood and Objective Functions ---
1039
1050
1062
1063
1064 // ========== Bootstrap and Validation ==========
1065
1083 const double& percentage,
1084 unsigned int num_iterations,
1085 const string& target_sample,
1086 bool use_softmax,
1087 std::uint64_t seed = DefaultRandomSeed
1088 );
1089
1111 bool BootStrap(
1112 Results* results,
1113 const double& percentage,
1114 unsigned int num_iterations,
1115 const string& target_sample,
1116 bool use_softmax,
1117 std::uint64_t seed = DefaultRandomSeed
1118 );
1119
1142 const string& source_group,
1143 bool use_softmax,
1144 bool apply_om_size_correction
1145 );
1146
1147 // ========== Results Retrieval ==========
1148
1160
1172
1185
1200 );
1201
1217 );
1218
1234 );
1235
1251 );
1252
1265
1277
1289
1301
1313
1325
1336 vector<ResultItem> GetSourceProfiles();
1337
1338 // ========== Utility ==========
1339
1348 void AddtoToolsUsed(const string& tool);
1349
1350 // ========== Accessors (inline for performance) ==========
1351
1356 vector<Parameter>& Parameters();
1357
1362 size_t ParametersCount();
1363
1368 size_t ObservationsCount();
1369
1375 Parameter* parameter(size_t i);
1376
1382 const Parameter* parameter(size_t i) const;
1383
1389 Observation* observation(size_t i);
1390
1396
1402 ConcentrationSet* GetElementDistribution(const string& element_name);
1403
1410 ConcentrationSet* GetElementDistribution(const string& element_name, const string& sample_group);
1411
1418 element_information* GetElementInformation(const string& element_name);
1419
1420 // --- Distribution Management ---
1421
1433
1446 void PopulateElementInformation(const map<string, element_information>* ElementInfo = nullptr);
1447
1463
1464 // --- Data Extraction and Management ---
1465
1476 int CountElements(bool exclude_elements) const;
1477
1487 vector<string> GetSampleNames(const string& group_name) const;
1488
1497 vector<string> GetGroupNames() const;
1498
1508 vector<string> GetElementNames() const;
1509
1519 void IncludeExcludeAllElements(bool include_in_analysis);
1520
1534 Elemental_Profile Sample(const string& sample_name) const;
1535
1546 profiles_data ExtractConcentrationData(const vector<vector<string>>& indicators) const;
1547
1558 Elemental_Profile_Set ExtractSamplesAsProfileSet(const vector<vector<string>>& indicators) const;
1559
1571 element_data ExtractElementConcentrations(const string& element, const string& group) const;
1572
1583 map<string, vector<double>> ExtractElementDataByGroup(const string& element) const;
1584
1595 SourceSinkData ExtractSpecificElements(const vector<string>& element_list) const;
1596
1610 map<string, ConcentrationSet> ExtractConcentrationSet();
1611
1612 // --- Element Ordering ---
1613
1624 vector<string> ElementsToBeUsedInCMB();
1625
1637 vector<string> IsotopesToBeUsedInCMB();
1638
1648 vector<string> IsotopesWithUnusableBaseElement() const;
1649
1660
1668 double IsotopeBaseMean(Elemental_Profile_Set* source_group, const string& base_element, parameter_mode param_mode);
1669
1686
1692 string SelectedTargetSample() const;
1693
1694 // --- Tools Tracking ---
1695
1705 bool ToolsUsed(const string& tool_name);
1706
1707 // --- File I/O ---
1708
1716
1717 string GetOutputPath() const;
1718
1724
1725 QMap<QString, double>* GetOptions();
1726
1736 bool SetOutputPath(const string& output_path);
1737
1746 QJsonObject ElementInformationToJsonObject() const;
1747
1756 QJsonArray ToolsUsedToJsonObject() const;
1757
1766 QJsonObject OptionsToJsonObject() const;
1767
1774 bool ReadToolsUsedFromJsonObject(const QJsonArray& jsonarray);
1775
1787 bool ReadElementInformationfromJsonObject(const QJsonObject& jsonobject);
1788
1800 bool ReadElementDatafromJsonObject(const QJsonObject& jsonobject);
1801
1807 bool ReadElementDatafromJsonObject(const QJsonObject& jsonobject, QString& error);
1808
1817 bool ReadOptionsfromJsonObject(const QJsonObject& jsonobject);
1818
1826 QJsonObject ElementDataToJsonObject() const;
1827
1839 bool WriteDataToFile(QFile* file);
1840
1849 bool WriteToFile(QFile* file);
1850
1863 bool ReadFromFile(QFile* fil);
1864
1866 const QString& LoadError() const { return load_error_; }
1867private:
1868 // ========== Private Data Members ==========
1869
1870 // Element Metadata and Distributions
1871 map<string, element_information> element_information_;
1872 map<string, ConcentrationSet> element_distributions_;
1873
1874 // Counters
1878
1879 // MCMC/Optimization Data
1880 vector<Observation> observations_;
1881 vector<Parameter> parameters_;
1882
1883 // File Paths
1885
1886 // Group and Sample Identifiers
1889
1890 // Ordering Vectors
1891 vector<string> samplesetsorder_;
1892 vector<string> constituent_order_;
1893 vector<string> element_order_;
1894 vector<string> isotope_order_;
1895 vector<string> size_om_order_;
1896
1897 // Analysis Settings
1903 QString load_error_;
1904 double error_stdev_ = 0;
1906 double epsilon_ = 0;
1907
1908 // UI and Tracking
1910 list<string> tools_used_;
1911 QMap<QString, double> options_;
1912
1913 // ========== Private Helper Methods ==========
1914
1915
1929 Elemental_Profile* GetElementalProfile(const string& sample_name);
1930
1931public:
1932 // --- Element Role Conversion ---
1933
1952 QString Role(const element_information::role& role) const;
1953
1972 element_information::role Role(const QString& role_string) const;
1973private:
1974
1975 // --- Parameter Management ---
1976
1985 double GetParameterValue(size_t index) const;
1986
1998 bool SetParameterValue(const CVector& values);
1999
2008 CVector GetParameterValue() const;
2009
2010 // --- Contribution Initialization ---
2011
2023
2038
2039 // --- Contribution Accessors ---
2040
2052 CVector GetSourceContributions();
2053
2068 CVector GetContributionVector(bool include_all = true);
2069
2081
2093 void SetContribution(size_t source_index, double contribution_value);
2094
2106 void SetContributionSoftmax(size_t source_index, double softmax_value);
2107
2118 void SetContribution(const CVector& contributions);
2119
2130 void SetContributionSoftmax(const CVector& softmax_params);
2131
2132 // --- Distribution Parameter Accessors ---
2133
2146 Parameter* GetElementDistributionMuParameter(size_t element_index, size_t source_index);
2147
2160 Parameter* GetElementDistributionSigmaParameter(size_t element_index, size_t source_index);
2161
2169 double GetElementDistributionMuValue(size_t element_index, size_t source_index);
2170
2178 double GetElementDistributionSigmaValue(size_t element_index, size_t source_index);
2179
2180 // --- Observation Data ---
2181
2191 CVector ObservedDataforSelectedSample(const string& SelectedTargetSample = "");
2192
2204
2215
2216 // --- Prediction Methods ---
2217
2229
2240
2251
2265
2281
2282 // --- Likelihood and Prior Calculations ---
2291 double LogPriorContributions();
2292
2302
2316
2330
2331 // --- Optimization Helper Methods ---
2332
2349 CVector Gradient(const CVector& parameters, estimation_mode est_mode);
2350
2364 CVector ResidualVector();
2365
2374 CVector_arma ResidualVector_arma();
2375
2389 CMatrix_arma ResidualJacobian_arma();
2390
2401 CMatrix ResidualJacobian();
2402
2414 CMatrix ResidualJacobian_softmax();
2415
2430 CVector OneStepLevenberg_Marquardt(double lambda);
2431
2442 CVector OneStepLevenberg_Marquardt_softmax(double lambda);
2443
2449 vector<string> GetSourceOrder() const;
2450
2456 vector<string> SamplesetsOrder();
2457
2463 vector<string> ConstituentOrder();
2464
2470 vector<string> ElementOrder();
2471
2477 vector<string> IsotopeOrder();
2478
2484 vector<string> SizeOMOrder();
2485
2486 // --- Statistical Methods ---
2487
2497 int TotalNumberofSourceSamples() const;
2498
2513 double GrandMean(const string& element, bool use_log);
2514
2525
2526 // --- Box-Cox Transformation ---
2527
2548
2549 // --- Bootstrap Helpers ---
2550
2563 SourceSinkData RandomlyEliminateSourceSamples(const double& percentage, RandomStream& stream);
2564
2575 vector<string> AllSourceSampleNames() const;
2576
2589 vector<string> RandomlypickSamples(const double& percentage, RandomStream& stream) const;
2590
2602 SourceSinkData ReplaceSourceAsTarget(const string& source_sample_name) const;
2603
2604 // --- DFA Helper Methods ---
2605
2619
2621
2635
2650 CMatrix TotalScatterMatrix();
2651
2668 double WilksLambda();
2669
2683 double DFA_P_Value();
2684
2694
2704 CMBVectorSet DFA_Projected(const string& source1, const string& source2);
2705
2718 CMBVectorSet DFA_Projected(const string& source1, SourceSinkData* original);
2719
2732
2745 CMBVector DFA_weight_vector(const string& source1, const string& source2);
2746
2759 CMBVector DFATransformed(const CMBVector& eigenvector, const string& source_group);
2760
2772 Elemental_Profile_Set TheRest(const string& excluded_source);
2773
2774 // --- Mean Calculation ---
2775
2787 CMBVector MeanElementalContent(const string& group_name);
2788
2803
2804
2805};
2806
2807#endif // SOURCESINKDATA_H
Matrix class with labeled rows and columns for Chemical Mass Balance analysis.
Definition cmbmatrix.h:22
Collection of time series with labels and observed values.
Collection of named CMBVectorSet objects for hierarchical data organization.
Collection of named CMBVector objects for multi-variable analysis.
Vector class with string labels for Chemical Mass Balance analysis.
Definition cmbvector.h:20
Markov Chain Monte Carlo sampler for Bayesian parameter estimation.
Definition MCMC.h:351
Manages a collection of concentration measurements with statistical analysis.
Represents a parametric probability distribution for uncertainty quantification.
Manages a collection of elemental profiles (samples) for source fingerprinting analysis.
Container for elemental concentration data of a single sediment sample.
Represents a model parameter with prior distribution and constraints.
Definition parameter.h:76
Abstract sink for progress information produced by a running analysis.
A seeded, independent stream of random numbers.
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.
const QString & LoadError() const
Why the last ReadFromFile() failed, or empty if it succeeded.
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.
constexpr std::uint64_t DefaultRandomSeed
The stream for code outside the MCMC that needs random numbers.
@ elemental_profile_set
Definition resultitem.h:9
transformation
estimation_mode
@ elemental_profile_and_contribution
@ source_elemental_profiles_based_on_source_data
negative_reporting
CMBVectorSet projected
CMBVector p_values
CMBVectorSet eigen_vectors
CMBVector F_test_P_value
CMBVector wilkslambda
CMBVectorSetSet multi_projected
vector< string > sample_names
vector< vector< double > > values
vector< string > group_names
vector< string > sample_names
vector< double > values
Metadata describing an element's role and properties in analysis.
role
Classification of element types.
vector< vector< double > > values
vector< string > element_names
vector< string > sample_names