SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
SourceSinkData Class Reference

#include <sourcesinkdata.h>

Inheritance diagram for SourceSinkData:
Inheritance graph
Collaboration diagram for SourceSinkData:
Collaboration graph

Public Member Functions

 SourceSinkData ()
 Default constructor.
 
 SourceSinkData (const SourceSinkData &other)
 Copy constructor.
 
SourceSinkDataoperator= (const SourceSinkData &other)
 Assignment operator.
 
void Clear ()
 Clear all data from the object.
 
Elemental_Profile_SetAppendSampleSet (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.
 
vector< string > SourceGroupNames () const
 Retrieves the names of all source groups (excluding target)
 
bool SetSelectedTargetSample (const string &sample_name)
 Sets the currently selected target sample for analysis.
 
Elemental_Profile_SetGetSampleSet (const string &name)
 Get a sample set (source or target group) by name.
 
bool SetTargetGroup (const string &targroup)
 Sets the target/sink group designation.
 
string GetTargetGroup () const
 Retrieves the name of the target group.
 
SourceSinkData CreateCorrectedDataset (const string &target, bool omnsizecorrect, map< string, element_information > *elementinfo)
 Create a corrected copy of the dataset for a specific target sample.
 
SourceSinkData CreateCorrectedAndFilteredDataset (bool exclude_samples, bool exclude_elements, bool omnsizecorrect, const string &target="") const
 Create a corrected and filtered copy of the dataset.
 
SourceSinkData ExtractChemicalElements (bool isotopes) const
 Extract only chemical elements (and optionally isotopes)
 
SourceSinkData BoxCoxTransformed (bool calculate_optimal_lambda=false)
 Applies Box-Cox transformation to all source groups for normalization.
 
map< string, element_information > * GetElementInformation ()
 Retrieves pointer to the element information map.
 
void IncludeExcludeElementsBasedOn (const vector< string > &elements)
 Sets element inclusion based on a specified list.
 
DistributionGetFittedDistribution (const string &element_name)
 Get the fitted distribution for a specific element at dataset level.
 
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 > OMandSizeConstituents ()
 Retrieves the names of OM and particle size constituents.
 
vector< ResultItemGetMLRResults ()
 Retrieves multiple linear regression results for all sample groups.
 
string FirstOMConstituent ()
 Retrieves the name of the first organic matter constituent.
 
string FirstSizeConstituent ()
 Retrieves the name of the first particle size constituent.
 
void SetOMandSizeConstituents (const string &_omconstituent, const string &_sizeconsituent)
 Sets the names of OM and particle size constituents.
 
void SetOMandSizeConstituents (const vector< string > &_omsizeconstituents)
 Sets the names of OM and particle size constituents from a vector.
 
void OutlierAnalysisForAll (const double &lower_threshold=-3, const double &upper_threshold=3)
 Performs outlier detection on all source groups.
 
vector< string > NegativeValueCheck ()
 Checks for zero or negative concentration values across all sources.
 
CMBVector BracketTest (const string &target_sample, bool correct_based_on_om_n_size)
 Performs bracket test to check if target concentrations fall within source ranges.
 
CMBMatrix BracketTest (bool correct_based_on_om_n_size, bool exclude_elements, bool exclude_samples)
 Performs bracket test on all target samples.
 
DFA_result DiscriminantFunctionAnalysis ()
 Performs discriminant function analysis for all source groups.
 
DFA_result DiscriminantFunctionAnalysis (const string &source1, const string &source2)
 Performs discriminant function analysis between two specific sources.
 
DFA_result DiscriminantFunctionAnalysis (const string &source1)
 Performs discriminant function analysis for one source vs all others.
 
vector< CMBVectorStepwiseDiscriminantFunctionAnalysis (const string &source1, const string &source2)
 Performs stepwise discriminant analysis between two specific sources.
 
vector< CMBVectorStepwiseDiscriminantFunctionAnalysis ()
 Performs stepwise discriminant analysis across all source groups.
 
vector< CMBVectorStepwiseDiscriminantFunctionAnalysis (const string &source1)
 Performs stepwise discriminant analysis for one source vs all others.
 
Elemental_Profile_Set DifferentiationPower (bool use_log, bool include_target)
 Computes differentiation power for all source pairs.
 
Elemental_Profile_Set DifferentiationPower_Percentage (bool include_target)
 Computes rank-based differentiation percentage for all source pairs.
 
Elemental_Profile_Set DifferentiationPower_P_value (bool include_target)
 Computes t-test p-values for all source pairs.
 
Elemental_Profile DifferentiationPower_Percentage (const string &source1, const string &source2)
 Computes rank-based differentiation percentage between two sources.
 
Elemental_Profile DifferentiationPower (const string &source1, const string &source2, bool use_log)
 Computes differentiation power metric between two sources.
 
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.
 
CMBVector ANOVA (bool use_log)
 Performs one-way ANOVA for all elements across source groups.
 
ANOVA_info ANOVA (const string &element, bool use_log)
 Performs one-way ANOVA for a single element across source groups.
 
string GetParameterName (int index) const
 Get the name of a parameter by its index.
 
bool InitializeParametersAndObservations (const string &targetsamplename, estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
 Initialize parameters and observations for MCMC optimization.
 
void SetParameterEstimationMode (estimation_mode est_mode)
 Sets the estimation mode for parameter optimization.
 
bool SetParameterValue (size_t index, double value)
 Sets a parameter value and updates corresponding model components.
 
void SetProgressWindow (ProgressWindow *_rtw)
 Sets the progress window for displaying optimization progress.
 
bool SolveLevenberg_Marquardt (transformation trans=transformation::linear)
 Solves for optimal source contributions using the Levenberg-Marquardt algorithm.
 
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.
 
CVector GetPredictedValues ()
 Retrieves predicted values for all observations.
 
CVector GradientUpdate (estimation_mode estmode=estimation_mode::elemental_profile_and_contribution)
 Performs one gradient ascent step with adaptive step size.
 
Results MCMC (const string &target_sample, map< string, string > arguments, CMCMC< SourceSinkData > *mcmc, ProgressWindow *progress_window, const string &working_folder)
 Performs Markov Chain Monte Carlo analysis for Bayesian source apportionment.
 
CMBMatrix MCMC_Batch (map< string, string > arguments, CMCMC< SourceSinkData > *mcmc, ProgressWindow *progress_window, const string &working_folder)
 Performs batch MCMC analysis on all target samples.
 
double GetObjectiveFunctionValue ()
 Returns the objective function value for optimization algorithms.
 
double LogLikelihood (estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
 Calculates the total log-likelihood for Bayesian source apportionment.
 
CMBTimeSeriesSet BootStrap (const double &percentage, unsigned int num_iterations, string target_sample, bool use_softmax)
 Performs bootstrap uncertainty analysis on source contributions.
 
bool BootStrap (Results *results, const double &percentage, unsigned int num_iterations, string target_sample, bool use_softmax)
 Performs bootstrap analysis and generates comprehensive uncertainty results.
 
CMBTimeSeriesSet VerifySource (const string &source_group, bool use_softmax, bool apply_om_size_correction)
 Performs leave-one-out validation on a source group.
 
ResultItem GetContribution ()
 Packages source contributions into a ResultItem for output.
 
ResultItem GetObservedElementalProfile ()
 Retrieves the observed elemental concentrations for the selected target sample.
 
ResultItem GetObservedElementalProfile_Isotope ()
 Retrieves the observed isotope delta values for the selected target sample.
 
ResultItem GetPredictedElementalProfile (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Generates predicted elemental concentrations for the target sample.
 
ResultItem GetPredictedElementalProfile_Isotope (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Generates predicted isotope delta values for the target sample.
 
ResultItem GetObservedvsModeledElementalProfile (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Creates a comparison of observed vs modeled elemental profiles.
 
ResultItem GetObservedvsModeledElementalProfile_Isotope (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Creates a comparison of observed vs modeled isotope delta values.
 
ResultItem GetCalculatedElementMeans ()
 Computes estimated mean concentrations for all source elements.
 
ResultItem GetCalculatedElementSigma ()
 Computes estimated standard deviations for all source elements.
 
ResultItem GetCalculatedElementMu ()
 Computes μ parameters from fitted log-normal distributions for source elements.
 
ResultItem GetEstimatedElementMu ()
 Retrieves estimated μ parameters from Bayesian inference for source elements.
 
ResultItem GetEstimatedElementMean ()
 Computes actual mean concentrations from estimated log-normal parameters.
 
ResultItem GetEstimatedElementSigma ()
 Retrieves estimated σ parameters from Bayesian inference for source elements.
 
vector< ResultItemGetSourceProfiles ()
 Retrieves elemental profiles for all source groups.
 
void AddtoToolsUsed (const string &tool)
 Adds a tool name to the list of tools used in analysis.
 
vector< Parameter > & Parameters ()
 Retrieves reference to the parameters vector.
 
size_t ParametersCount ()
 Returns the number of parameters.
 
size_t ObservationsCount ()
 Returns the number of observations.
 
Parameterparameter (size_t i)
 Retrieves pointer to a parameter by index.
 
const Parameterparameter (size_t i) const
 Retrieves const pointer to a parameter by index.
 
Observationobservation (size_t i)
 Retrieves pointer to an observation by index.
 
estimation_mode ParameterEstimationMode ()
 Retrieves the current estimation mode.
 
ConcentrationSetGetElementDistribution (const string &element_name)
 Retrieves pointer to element distribution at dataset level.
 
ConcentrationSetGetElementDistribution (const string &element_name, const string &sample_group)
 Retrieves pointer to element distribution for a specific group.
 
element_informationGetElementInformation (const string &element_name)
 Retrieves pointer to element information metadata by name.
 
void PopulateElementDistributions ()
 Populate element distributions from all groups.
 
void PopulateElementInformation (const map< string, element_information > *ElementInfo=nullptr)
 Populate element information metadata.
 
void AssignAllDistributions ()
 Assign distributions to all elements at both dataset and group levels.
 
int CountElements (bool exclude_elements) const
 Count the number of elements in the dataset.
 
vector< string > GetSampleNames (const string &group_name) const
 Get all sample names within a specific group.
 
vector< string > GetGroupNames () const
 Get all group names in the dataset.
 
vector< string > GetElementNames () const
 Get all element names in the dataset.
 
void IncludeExcludeAllElements (bool include_in_analysis)
 Sets inclusion flag for all elements.
 
Elemental_Profile Sample (const string &sample_name) const
 Retrieves an elemental profile by sample name.
 
profiles_data ExtractConcentrationData (const vector< vector< string > > &indicators) const
 Extract concentration data for specified samples.
 
Elemental_Profile_Set ExtractSamplesAsProfileSet (const vector< vector< string > > &indicators) const
 Extract samples as an Elemental_Profile_Set.
 
element_data ExtractElementConcentrations (const string &element, const string &group) const
 Extract concentration data for a specific element from a group.
 
map< string, vector< double > > ExtractElementDataByGroup (const string &element) const
 Extract concentration data for a specific element from all groups.
 
SourceSinkData ExtractSpecificElements (const vector< string > &element_list) const
 Extract specific elements from source groups.
 
map< string, ConcentrationSetExtractConcentrationSet ()
 Extracts concentration distributions for all elements across sources.
 
vector< string > ElementsToBeUsedInCMB ()
 Identifies chemical elements to be used in CMB analysis.
 
vector< string > IsotopesToBeUsedInCMB ()
 Identifies isotopes to be used in CMB analysis.
 
void PopulateConstituentOrders ()
 Populates all element ordering vectors used throughout CMB analysis.
 
string SelectedTargetSample () const
 Retrieves the name of the currently selected target sample.
 
bool ToolsUsed (const string &tool_name)
 Checks if a specific analysis tool has been used.
 
string GetOutputPath () const
 Get the output directory path.
 
QMap< QString, double > * GetOptions ()
 Retrieves pointer to the options map.
 
bool SetOutputPath (const string &output_path)
 Set the output directory path.
 
QJsonObject ElementInformationToJsonObject () const
 Exports element information metadata to a JSON object.
 
QJsonArray ToolsUsedToJsonObject () const
 Exports the list of analysis tools used to a JSON array.
 
QJsonObject OptionsToJsonObject () const
 Exports analysis options/settings to a JSON object.
 
bool ReadToolsUsedFromJsonObject (const QJsonArray &jsonarray)
 Deserializes the list of analysis tools from a JSON array.
 
bool ReadElementInformationfromJsonObject (const QJsonObject &jsonobject)
 Deserializes element information metadata from a JSON object.
 
bool ReadElementDatafromJsonObject (const QJsonObject &jsonobject)
 Deserializes elemental profile data from a JSON object.
 
bool ReadOptionsfromJsonObject (const QJsonObject &jsonobject)
 Deserializes analysis options from a JSON object.
 
QJsonObject ElementDataToJsonObject () const
 Exports all elemental profile data to a JSON object.
 
bool WriteDataToFile (QFile *file)
 Writes elemental profile data to a text file.
 
bool WriteToFile (QFile *file)
 Writes dataset to a text file.
 
bool ReadFromFile (QFile *fil)
 Loads complete dataset from a JSON file.
 

Private Member Functions

Elemental_ProfileGetElementalProfile (const string &sample_name)
 Finds and retrieves an elemental profile by sample name.
 
QString Role (const element_information::role &role) const
 Converts element role enum to string representation.
 
element_information::role Role (const QString &role_string) const
 Converts string representation to element role enum.
 
double GetParameterValue (size_t index) const
 Retrieves a single parameter value by index.
 
bool SetParameterValue (const CVector &values)
 Sets multiple parameter values from a vector.
 
CVector GetParameterValue () const
 Retrieves all current parameter values as a vector.
 
bool InitializeContributionsRandomly ()
 Initialize source contributions randomly (linear constraint)
 
bool InitializeContributionsRandomlySoftmax ()
 Initialize source contributions randomly (softmax transformation)
 
CVector GetSourceContributions ()
 Retrieves the contributions from all sources.
 
CVector GetContributionVector (bool include_all=true)
 Retrieves the current source contribution fractions.
 
CVector GetContributionVectorSoftmax ()
 Retrieves the softmax parameters for source contributions.
 
void SetContribution (size_t source_index, double contribution_value)
 Sets a single source contribution value.
 
void SetContributionSoftmax (size_t source_index, double softmax_value)
 Sets a single softmax parameter value.
 
void SetContribution (const CVector &contributions)
 Sets all source contributions from a vector.
 
void SetContributionSoftmax (const CVector &softmax_params)
 Sets all source contributions using softmax transformation.
 
ParameterGetElementDistributionMuParameter (size_t element_index, size_t source_index)
 Retrieves pointer to the μ (mean) parameter for an element distribution.
 
ParameterGetElementDistributionSigmaParameter (size_t element_index, size_t source_index)
 Retrieves pointer to the σ (std dev) parameter for an element distribution.
 
double GetElementDistributionMuValue (size_t element_index, size_t source_index)
 Retrieves the current value of the μ parameter for an element distribution.
 
double GetElementDistributionSigmaValue (size_t element_index, size_t source_index)
 Retrieves the current value of the σ parameter for an element distribution.
 
CVector ObservedDataforSelectedSample (const string &SelectedTargetSample="")
 Retrieves the observed elemental data for a selected target sample.
 
CVector ObservedDataforSelectedSample_Isotope (const string &SelectedTargetSample="")
 Retrieves the observed isotopic data for a selected target sample.
 
CVector ObservedDataforSelectedSample_Isotope_delta (const string &SelectedTargetSample="")
 Retrieves the observed isotopic data in delta notation.
 
CVector PredictTarget (parameter_mode param_mode=parameter_mode::direct)
 Predicts target sample elemental concentrations based on source contributions.
 
CVector PredictTarget_Isotope (parameter_mode param_mode=parameter_mode::direct)
 Predicts target sample isotopic compositions based on source contributions.
 
CVector PredictTarget_Isotope_delta (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Predicts target sample isotopic compositions in delta notation.
 
CMatrix BuildSourceMeanMatrix (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Builds the source mean concentration matrix for chemical elements.
 
CMatrix BuildSourceMeanMatrix_Isotopes (parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
 Builds the source mean concentration matrix for isotopes.
 
double LogPriorContributions ()
 Calculates the log prior probability for source contributions.
 
double LogLikelihoodSourceElementalDistributions ()
 Calculates the log-likelihood of source elemental distributions.
 
double LogLikelihoodModelvsMeasured (estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
 Calculates the log-likelihood of the model prediction versus measured data.
 
double LogLikelihoodModelvsMeasured_Isotope (estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
 Calculates the log-likelihood of model versus measured isotopic data.
 
CVector Gradient (const CVector &parameters, estimation_mode est_mode)
 Computes the normalized gradient of the log-likelihood function.
 
CVector ResidualVector ()
 Calculates the combined residual vector for elemental and isotopic predictions.
 
CVector_arma ResidualVector_arma ()
 Calculates the combined residual vector using Armadillo vector format.
 
CMatrix_arma ResidualJacobian_arma ()
 Calculates the Jacobian matrix of residuals with respect to contributions (Armadillo)
 
CMatrix ResidualJacobian ()
 Calculates the Jacobian matrix of residuals with respect to contributions.
 
CMatrix ResidualJacobian_softmax ()
 Calculates the Jacobian using softmax parameterization of contributions.
 
CVector OneStepLevenberg_Marquardt (double lambda)
 Performs one iteration of the Levenberg-Marquardt optimization algorithm.
 
CVector OneStepLevenberg_Marquardt_softmax (double lambda)
 Performs one iteration of Levenberg-Marquardt using softmax parameterization.
 
vector< string > GetSourceOrder () const
 Retrieves the ordering of source groups.
 
vector< string > SamplesetsOrder ()
 Retrieves the ordering of sample sets.
 
vector< string > ConstituentOrder ()
 Retrieves the ordering of all constituents.
 
vector< string > ElementOrder ()
 Retrieves the ordering of chemical elements.
 
vector< string > IsotopeOrder ()
 Retrieves the ordering of isotopes.
 
vector< string > SizeOMOrder ()
 Retrieves the ordering of size and OM constituents.
 
int TotalNumberofSourceSamples () const
 Counts the total number of source samples across all source groups.
 
double GrandMean (const string &element, bool use_log)
 Computes grand mean concentration for an element across all sources.
 
Elemental_Profile_Set LumpAllProfileSets ()
 Combines all source samples into a single profile set.
 
CMBVector OptimalBoxCoxParameters ()
 Computes optimal Box-Cox transformation parameters for all elements.
 
SourceSinkData RandomlyEliminateSourceSamples (const double &percentage)
 Creates dataset with randomly excluded source samples for validation.
 
vector< string > AllSourceSampleNames () const
 Retrieves names of all samples across all source groups.
 
vector< string > RandomlypickSamples (const double &percentage) const
 Randomly selects a subset of source samples.
 
SourceSinkData ReplaceSourceAsTarget (const string &source_sample_name) const
 Creates a new dataset with a source sample designated as the target.
 
CMatrix WithinGroupCovarianceMatrix ()
 Computes pooled within-group covariance matrix.
 
CMatrix BetweenGroupCovarianceMatrix ()
 Computes between-group covariance matrix.
 
CMatrix TotalScatterMatrix ()
 Computes total scatter matrix.
 
double WilksLambda ()
 Computes Wilks' Lambda statistic for multivariate group separation.
 
double DFA_P_Value ()
 Computes p-value for discriminant function analysis.
 
CMBVectorSet DFA_Projected ()
 Projects all groups onto the discriminant function axis.
 
CMBVectorSet DFA_Projected (const string &source1, const string &source2)
 Projects two specific groups onto the discriminant function axis.
 
CMBVectorSet DFA_Projected (const string &source1, SourceSinkData *original)
 Projects samples from original dataset onto discriminant function.
 
CMBVector DFA_eigvector ()
 Computes the primary discriminant function eigenvector.
 
CMBVector DFA_weight_vector (const string &source1, const string &source2)
 Computes discriminant weight vector for two-group comparison.
 
CMBVector DFATransformed (const CMBVector &eigenvector, const string &source_group)
 Projects samples onto a discriminant function axis.
 
Elemental_Profile_Set TheRest (const string &excluded_source)
 Collects all source samples except those from a specified source group.
 
CMBVector MeanElementalContent (const string &group_name)
 Computes mean elemental concentrations for a specific group.
 
CMBVector MeanElementalContent ()
 Computes weighted mean elemental concentrations across all sources.
 

Private Attributes

map< string, element_informationelement_information_
 
map< string, ConcentrationSetelement_distributions_
 
int numberofconstituents_
 
int numberofisotopes_
 
int numberofsourcesamplesets_
 
vector< Observationobservations_
 
vector< Parameterparameters_
 
string outputpath_
 
string target_group_
 
string selected_target_sample_
 
vector< string > samplesetsorder_
 
vector< string > constituent_order_
 
vector< string > element_order_
 
vector< string > isotope_order_
 
vector< string > size_om_order_
 
estimation_mode parameter_estimation_mode_
 
string omconstituent_
 
string sizeconsituent_
 
double regression_p_value_threshold_
 
double distance_coeff_
 
double error_stdev_
 
double error_stdev_isotope_
 
double epsilon_
 
ProgressWindowrtw_ = nullptr
 
list< string > tools_used_
 
QMap< QString, double > options_
 

Detailed Description

Definition at line 66 of file sourcesinkdata.h.

Constructor & Destructor Documentation

◆ SourceSinkData() [1/2]

SourceSinkData::SourceSinkData ( )

Default constructor.

Initializes an empty SourceSinkData object with default options. Sets outlier deviation threshold to 3.0 by default.

Definition at line 17 of file sourcesinkdata.cpp.

References options_, rtw_, and string.

◆ SourceSinkData() [2/2]

SourceSinkData::SourceSinkData ( const SourceSinkData other)

Copy constructor.

Creates a deep copy of another SourceSinkData object, including all elemental profile sets, element information, distributions, parameters, observations, and analysis settings.

Parameters
otherThe SourceSinkData object to copy from

Definition at line 46 of file sourcesinkdata.cpp.

References rtw_, and string.

Member Function Documentation

◆ AddtoToolsUsed()

void SourceSinkData::AddtoToolsUsed ( const string &  tool)

Adds a tool name to the list of tools used in analysis.

Records that a particular analysis tool was applied to this dataset. Prevents duplicate entries.

Parameters
toolName of the tool used (e.g., "MCMC", "Bootstrap")

Definition at line 2606 of file sourcesinkdata.cpp.

References tools_used_, and ToolsUsed().

Referenced by Conductor::Execute(), and ReadToolsUsedFromJsonObject().

◆ AllSourceSampleNames()

vector< string > SourceSinkData::AllSourceSampleNames ( ) const
private

Retrieves names of all samples across all source groups.

Collects sample names from all source groups (excluding target) into a single flat list.

Returns
Vector of all source sample names
Note
Target group samples are excluded

Definition at line 4000 of file sourcesinkdata.cpp.

References target_group_.

Referenced by RandomlypickSamples().

◆ ANOVA() [1/2]

CMBVector SourceSinkData::ANOVA ( bool  use_log)

Performs one-way ANOVA for all elements across source groups.

Conducts analysis of variance to test whether mean concentrations differ significantly among source groups for each element.

Null hypothesis: μ₁ = μ₂ = ... = μₖ (all source means equal)

Parameters
use_logIf true, perform ANOVA on log-transformed concentrations; if false, use linear-space concentrations
Returns
CMBVector of p-values for each element, labeled with element names
Note
Lower p-values indicate significant differences among sources
Target group is excluded from analysis

Definition at line 3490 of file sourcesinkdata.cpp.

References ANOVA(), GetElementNames(), ANOVA_info::p_value, and CMBVector::SetLabels().

Referenced by ANOVA(), and Conductor::ExecuteANOVA().

◆ ANOVA() [2/2]

ANOVA_info SourceSinkData::ANOVA ( const string &  element,
bool  use_log 
)

Performs one-way ANOVA for a single element across source groups.

Conducts detailed analysis of variance decomposing total variance into between-group and within-group components.

ANOVA decomposition:

  • SST (Total) = SSB + SSW
  • SSB (Between-group) = Σ n_i(μ_i - μ_grand)²
  • SSW (Within-group) = Σ Σ (x_ij - μ_i)²
  • F-statistic = MSB / MSW
Parameters
elementName of the element to analyze
use_logIf true, perform ANOVA on log-transformed concentrations
Returns
ANOVA_info structure containing SST, SSB, SSW, MSB, MSW, F, and p-value

Definition at line 3506 of file sourcesinkdata.cpp.

References ConcentrationSet::CalculateMean(), ConcentrationSet::CalculateMeanLog(), ConcentrationSet::CalculateSSE(), ConcentrationSet::CalculateSSELog(), ConcentrationSet::CalculateStdDevLog(), ANOVA_info::F, Elemental_Profile_Set::GetElementDistribution(), LumpAllProfileSets(), ANOVA_info::MSB, ANOVA_info::MSW, ANOVA_info::p_value, ANOVA_info::SSB, ANOVA_info::SST, ANOVA_info::SSW, and target_group_.

◆ AppendSampleSet()

Elemental_Profile_Set * SourceSinkData::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.

Adds a collection of elemental profiles under a group name. Typical group names are source identifiers (e.g., "Agricultural soil", "Road dust") or the target group name (e.g., "Stream sediment").

Parameters
nameGroup name for this sample set
elemental_profile_setCollection of elemental profiles for this group (default: empty)
Returns
Pointer to the added profile set, or nullptr if name already exists

Definition at line 368 of file sourcesinkdata.cpp.

References elemental_profile_set, and name.

Referenced by DiscriminantFunctionAnalysis(), DiscriminantFunctionAnalysis(), and MainWindow::ReadExcel().

◆ AssignAllDistributions()

void SourceSinkData::AssignAllDistributions ( )

Assign distributions to all elements at both dataset and group levels.

For each element:

  1. At dataset level: Selects best-fitting distribution (normal vs lognormal) and estimates parameters from all data
  2. At group level: Assigns same distribution type and estimates parameters from group-specific data

Special handling for isotopes: Always uses normal distribution regardless of best-fit results.

Note
Should be called after PopulateElementDistributions()

Definition at line 557 of file sourcesinkdata.cpp.

References Distribution::distribution, element_distributions_, element_information_, ConcentrationSet::EstimateDistributionParameters(), GetElementNames(), ConcentrationSet::GetFittedDistribution(), element_information::isotope, normal, Distribution::parameters, and Role().

Referenced by BoxCoxTransformed(), CreateCorrectedAndFilteredDataset(), CreateCorrectedDataset(), ExtractChemicalElements(), ExtractSpecificElements(), MainWindow::LoadModel(), RandomlyEliminateSourceSamples(), MainWindow::ReadExcel(), and ReplaceSourceAsTarget().

◆ BetweenGroupCovarianceMatrix()

CMatrix SourceSinkData::BetweenGroupCovarianceMatrix ( )
private

Computes between-group covariance matrix.

Calculates covariance matrix based on deviations of group means from the overall mean. Represents the "signal" or between-group scatter.

Formula: S_B = Σ[n_i × (μ_i - μ_overall)(μ_i - μ_overall)ᵀ] / N

Returns
Between-group covariance matrix (num_elements × num_elements)
Note
Target group excluded

Definition at line 4474 of file sourcesinkdata.cpp.

References GetElementNames(), MeanElementalContent(), CMBVector::size(), and target_group_.

Referenced by DFA_eigvector(), and WilksLambda().

◆ BootStrap() [1/2]

CMBTimeSeriesSet SourceSinkData::BootStrap ( const double &  percentage,
unsigned int  num_iterations,
string  target_sample,
bool  use_softmax 
)

Performs bootstrap uncertainty analysis on source contributions.

Conducts bootstrap resampling to estimate uncertainty in source contribution estimates. Each bootstrap iteration randomly excludes a percentage of source samples, re-solves the CMB model, and records the resulting contributions.

Parameters
percentagePercentage of source samples to exclude per iteration (0-100)
num_iterationsNumber of bootstrap iterations
target_sampleName of target sample to apportion
use_softmaxIf true, use softmax transformation for contributions
Returns
CMBTimeSeriesSet containing contribution estimates from all iterations
Note
Progress updates sent to rtw_ if available

Definition at line 3699 of file sourcesinkdata.cpp.

References GetContributionVector(), InitializeParametersAndObservations(), linear, numberofsourcesamplesets_, RandomlyEliminateSourceSamples(), rtw_, samplesetsorder_, ProgressWindow::SetProgress(), softmax, and SolveLevenberg_Marquardt().

Referenced by Conductor::ExecuteErrorAnalysis().

◆ BootStrap() [2/2]

bool SourceSinkData::BootStrap ( Results results,
const double &  percentage,
unsigned int  num_iterations,
string  target_sample,
bool  use_softmax 
)

Performs bootstrap analysis and generates comprehensive uncertainty results.

Conducts bootstrap resampling with full statistical analysis including:

  • Time series of contribution estimates
  • Posterior distributions of contributions
  • 95% credible intervals (2.5th to 97.5th percentiles)
  • Mean and median contribution estimates
Parameters
resultsPointer to Results object to populate with analysis outputs
percentagePercentage of source samples to exclude per iteration (0-100)
num_iterationsNumber of bootstrap iterations
target_sampleName of target sample to apportion
use_softmaxIf true, use softmax transformation
Returns
true if analysis completed successfully
Note
Generates stacked bar chart for contributions (if iterations ≤ 100)
Computes posterior distributions with 100 bins

Definition at line 3744 of file sourcesinkdata.cpp.

References Results::Append(), counter, distribution, GetContributionVector(), GetSourceOrder(), high, InitializeParametersAndObservations(), linear, low, normal, numberofsourcesamplesets_, RandomlyEliminateSourceSamples(), rangeset, rtw_, samplesetsorder_, Range::Set(), Range::SetMean(), Range::SetMedian(), ResultItem::SetName(), Results::SetName(), ProgressWindow::SetProgress(), ResultItem::SetResult(), ResultItem::SetShowAsString(), ResultItem::SetShowGraph(), ResultItem::SetShowTable(), ResultItem::SetType(), ResultItem::SetXAxisMode(), ResultItem::setXAxisTitle(), ResultItem::SetYAxisMode(), ResultItem::setYAxisTitle(), ResultItem::SetYLimit(), softmax, SolveLevenberg_Marquardt(), and stacked_bar_chart.

◆ BoxCoxTransformed()

SourceSinkData SourceSinkData::BoxCoxTransformed ( bool  calculate_optimal_lambda = false)

Applies Box-Cox transformation to all source groups for normalization.

Transforms elemental concentrations using the Box-Cox power transformation to improve normality of distributions. This is useful for statistical analyses that assume normally distributed data (e.g., t-tests, ANOVA, discriminant analysis).

Box-Cox transformation: y = (x^λ - 1) / λ (or ln(x) if λ = 0)

The optimal λ parameter for each element is determined by maximum likelihood estimation to best achieve normality.

Parameters
calculate_optimal_lambdaIf true, compute optimal λ for each element; if false, use default transformation
Returns
New SourceSinkData object with transformed concentrations
Note
Target group is not transformed (only sources)
Element distributions are recalculated after transformation
Original data is preserved (returns new object)
See also
OptimalBoxCoxParameters() for λ parameter computation

Definition at line 3117 of file sourcesinkdata.cpp.

References AssignAllDistributions(), OptimalBoxCoxParameters(), PopulateElementDistributions(), and target_group_.

Referenced by Conductor::ExecuteANOVA(), Conductor::ExecuteDFA(), Conductor::ExecuteDFAM(), Conductor::ExecuteDFAOnevsRest(), Conductor::ExecuteDistributionFitting(), Conductor::ExecuteEDP(), Conductor::ExecuteEDPM(), Conductor::ExecuteSDFA(), Conductor::ExecuteSDFAM(), and Conductor::ExecuteSDFAOnevsRest().

◆ BracketTest() [1/2]

CMBMatrix SourceSinkData::BracketTest ( bool  correct_based_on_om_n_size,
bool  exclude_elements,
bool  exclude_samples 
)

Performs bracket test on all target samples.

Applies the bracket test to every sample in the target group, producing a matrix showing which elements in which samples fall outside source concentration ranges.

Matrix structure:

  • Rows: Elements
  • Columns: Target samples
  • Values: 0 = pass (within range), 1 = fail (outside range)
Parameters
correct_based_on_om_n_sizeIf true, apply OM/size corrections before testing
exclude_elementsIf true, filter out elements marked for exclusion
exclude_samplesIf true, filter out samples marked for exclusion
Returns
CMBMatrix of bracket test results for all target samples
Note
Each target sample is tested independently
Matrix dimensions: (num_elements × num_target_samples)

Definition at line 3067 of file sourcesinkdata.cpp.

References BracketTest(), CountElements(), CreateCorrectedAndFilteredDataset(), GetElementNames(), CMBMatrix::SetColumnLabel(), CMBMatrix::SetRowLabel(), CMBVector::size(), target_group_, and CMBVector::valueAt().

◆ BracketTest() [2/2]

CMBVector SourceSinkData::BracketTest ( const string &  target_sample,
bool  correct_based_on_om_n_size 
)

Performs bracket test to check if target concentrations fall within source ranges.

Tests whether each element's concentration in the target sample falls within the range (min to max) observed across all source samples. Elements outside source ranges indicate potential issues: missing sources, measurement errors, or non-conservative behavior.

Test criteria for each element:

  • Pass (0): Target concentration within [min_sources, max_sources]
  • Fail (1): Target concentration outside source ranges
Parameters
target_sampleName of the target sample to test
correct_based_on_om_n_sizeIf true, apply OM/size corrections before testing
Returns
CMBVector of pass/fail flags (0 = pass, 1 = fail) for each element
Note
Flags are labeled with element names
Failed elements are documented in target sample notes
Test assumes conservative mixing (no gains/losses)

Definition at line 2994 of file sourcesinkdata.cpp.

References CreateCorrectedAndFilteredDataset(), GetElementDistribution(), GetElementNames(), ConcentrationSet::GetMaximum(), CMBVector::SetLabel(), and target_group_.

Referenced by BracketTest(), Conductor::ExecuteBracketingAnalysis(), and MainWindow::onIncludeExcludeSample().

◆ BuildSourceMeanMatrix()

CMatrix SourceSinkData::BuildSourceMeanMatrix ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)
private

Builds the source mean concentration matrix for chemical elements.

Constructs a matrix where each entry [i,j] represents the mean concentration of element i in source j. Used in the mixing model equation: C_target = S × f

Parameters
param_modeControls whether to use parametric or empirical means
Returns
Matrix of size (num_elements × num_sources) containing mean concentrations
Note
Elements are ordered according to element_order_ vector
Sources are ordered according to samplesetsorder_ vector

Definition at line 1492 of file sourcesinkdata.cpp.

References based_on_fitted_distribution, Distribution::DataMean(), element_order_, Elemental_Profile_Set::GetEstimatedDistribution(), GetSampleSet(), Distribution::Mean(), numberofsourcesamplesets_, and samplesetsorder_.

Referenced by PredictTarget(), and PredictTarget_Isotope_delta().

◆ BuildSourceMeanMatrix_Isotopes()

CMatrix SourceSinkData::BuildSourceMeanMatrix_Isotopes ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)
private

Builds the source mean concentration matrix for isotopes.

Constructs a matrix where each entry [i,j] represents the mean absolute concentration of isotope i in source j. Converts from delta notation to absolute concentrations.

Conversion formula: [isotope] = (δ/1000 + 1) × R_standard × [base_element]

Parameters
param_modeControls whether to use parametric or empirical means
Returns
Matrix of size (num_isotopes × num_sources)
Note
Mixing occurs in concentration space, not delta space

Definition at line 1530 of file sourcesinkdata.cpp.

References element_information::base_element, based_on_fitted_distribution, Distribution::DataMean(), element_information_, Elemental_Profile_Set::GetEstimatedDistribution(), GetSampleSet(), isotope_order_, Distribution::Mean(), numberofsourcesamplesets_, samplesetsorder_, and element_information::standard_ratio.

Referenced by PredictTarget_Isotope(), and PredictTarget_Isotope_delta().

◆ Clear()

void SourceSinkData::Clear ( )

Clear all data from the object.

Resets the SourceSinkData object to its initial empty state by:

  • Clearing all profile sets (sources and targets)
  • Clearing element information and distributions
  • Resetting all counters to zero
  • Clearing parameters and observations
  • Clearing all ordering vectors
  • Resetting file paths and identifiers to empty strings
  • Clearing tools usage history

Definition at line 332 of file sourcesinkdata.cpp.

References constituent_order_, element_distributions_, element_information_, element_order_, isotope_order_, numberofconstituents_, numberofisotopes_, numberofsourcesamplesets_, observations_, outputpath_, parameters_, samplesetsorder_, selected_target_sample_, size_om_order_, target_group_, and tools_used_.

Referenced by MainWindow::ReadExcel(), and ReadFromFile().

◆ ConstituentOrder()

vector< string > SourceSinkData::ConstituentOrder ( )
private

Retrieves the ordering of all constituents.

Returns
Vector of all constituent names

Definition at line 5090 of file sourcesinkdata.cpp.

References constituent_order_.

◆ CountElements()

int SourceSinkData::CountElements ( bool  exclude_elements) const

Count the number of elements in the dataset.

Counts elements based on their inclusion status and role. Can count either:

  • All elements (if exclude_elements = false)
  • Only elements marked for analysis, excluding OM, particle size, and do_not_include roles
Parameters
exclude_elementsIf true, only count elements marked for analysis with valid roles
Returns
Number of elements meeting the criteria

Definition at line 191 of file sourcesinkdata.cpp.

References element_information::do_not_include, element_information_, element_information::organic_carbon, and element_information::particle_size.

Referenced by BracketTest().

◆ CreateCorrectedAndFilteredDataset()

SourceSinkData SourceSinkData::CreateCorrectedAndFilteredDataset ( bool  exclude_samples,
bool  exclude_elements,
bool  omnsizecorrect,
const string &  target = "" 
) const

Create a corrected and filtered copy of the dataset.

Creates a new SourceSinkData object with optional filtering and corrections:

  • Can exclude samples not marked for analysis
  • Can exclude elements not marked for analysis
  • Can apply organic matter and particle size corrections
  • Target group is never corrected (only source groups)

This is the main method for preparing data before analysis, allowing fine control over which samples/elements to include and whether to apply normalizations.

Parameters
exclude_samplesIf true, exclude samples not marked for analysis
exclude_elementsIf true, exclude elements not marked for analysis
omnsizecorrectIf true, apply OM and particle size corrections to sources
targetTarget sample name (empty to use current selected_target_sample_)
Returns
New corrected and filtered SourceSinkData object

Definition at line 213 of file sourcesinkdata.cpp.

References AssignAllDistributions(), element_information_, omconstituent_, options_, PopulateElementDistributions(), PopulateElementInformation(), regression_p_value_threshold_, selected_target_sample_, sizeconsituent_, and target_group_.

Referenced by BracketTest(), BracketTest(), Conductor::ExecuteANOVA(), Conductor::ExecuteAutoSelect(), Conductor::ExecuteBracketingAnalysis(), Conductor::ExecuteCorrelationMatrix(), Conductor::ExecuteDFA(), Conductor::ExecuteDFAM(), Conductor::ExecuteDFAOnevsRest(), Conductor::ExecuteDistributionFitting(), Conductor::ExecuteEDP(), Conductor::ExecuteEDPM(), Conductor::ExecuteMLR(), Conductor::ExecuteOMSizeCorrect(), Conductor::ExecuteOutlierAnalysis(), Conductor::ExecuteSDFA(), Conductor::ExecuteSDFAM(), and Conductor::ExecuteSDFAOnevsRest().

◆ CreateCorrectedDataset()

SourceSinkData SourceSinkData::CreateCorrectedDataset ( const string &  target,
bool  omnsizecorrect,
map< string, element_information > *  elementinfo 
)

Create a corrected copy of the dataset for a specific target sample.

Creates a new SourceSinkData object with:

  • Only samples marked for inclusion in analysis
  • Optional organic matter and particle size corrections applied
  • Element information filtered based on analysis flags
  • All distributions populated and assigned

This method is typically used to prepare data for source apportionment of a specific target sample.

Parameters
targetName of the target sample to analyze
omnsizecorrectIf true, apply OM and size corrections to source profiles
elementinfoElement metadata for filtering (nullptr to use internal metadata)
Returns
New SourceSinkData object ready for analysis

Definition at line 111 of file sourcesinkdata.cpp.

References AssignAllDistributions(), constituent_order_, element_information::do_not_include, element_distributions_, element_information_, element_order_, isotope_order_, numberofconstituents_, numberofisotopes_, numberofsourcesamplesets_, observations_, omconstituent_, options_, element_information::organic_carbon, outputpath_, parameter_estimation_mode_, element_information::particle_size, PopulateElementDistributions(), regression_p_value_threshold_, samplesetsorder_, selected_target_sample_, size_om_order_, sizeconsituent_, and target_group_.

Referenced by Conductor::ExecuteANOVA(), Conductor::ExecuteAutoSelect(), Conductor::ExecuteCorrelationMatrix(), Conductor::ExecuteDFA(), Conductor::ExecuteDFAM(), Conductor::ExecuteDFAOnevsRest(), Conductor::ExecuteDistributionFitting(), Conductor::ExecuteEDP(), Conductor::ExecuteEDPM(), Conductor::ExecuteErrorAnalysis(), Conductor::ExecuteGA(), Conductor::ExecuteGA_FixedProfile(), Conductor::ExecuteLevenbergMarquardt(), Conductor::ExecuteSDFA(), Conductor::ExecuteSDFAM(), Conductor::ExecuteSDFAOnevsRest(), LM_Batch(), MCMC(), and VerifySource().

◆ DFA_eigvector()

CMBVector SourceSinkData::DFA_eigvector ( )
private

Computes the primary discriminant function eigenvector.

Calculates the eigenvector corresponding to the largest eigenvalue of S_W⁻¹ × S_B, which defines the discriminant function axis.

Returns
CMBVector containing discriminant function coefficients
Note
Returns empty vector if S_W is singular
Uses largest eigenvalue by absolute value

Definition at line 4664 of file sourcesinkdata.cpp.

References BetweenGroupCovarianceMatrix(), GetElementNames(), CMBVector::SetLabels(), and WithinGroupCovarianceMatrix().

Referenced by DFA_Projected(), DFA_Projected(), DFA_Projected(), DiscriminantFunctionAnalysis(), and DiscriminantFunctionAnalysis().

◆ DFA_P_Value()

double SourceSinkData::DFA_P_Value ( )
private

Computes p-value for discriminant function analysis.

Tests the null hypothesis that all source groups have the same mean elemental composition using Wilks' Lambda transformed to chi-squared.

Chi-squared transformation: χ² = -[N - 1 - (p + k)/2] × ln(Λ)

Returns
P-value for test of group equality
Note
P-value < 0.05 indicates significant differences

Definition at line 4568 of file sourcesinkdata.cpp.

References GetElementNames(), log, numberofsourcesamplesets_, target_group_, TotalNumberofSourceSamples(), and WilksLambda().

Referenced by DiscriminantFunctionAnalysis(), DiscriminantFunctionAnalysis(), and StepwiseDiscriminantFunctionAnalysis().

◆ DFA_Projected() [1/3]

CMBVectorSet SourceSinkData::DFA_Projected ( )
private

Projects all groups onto the discriminant function axis.

Computes discriminant scores for all samples in all groups by projecting elemental profiles onto the primary discriminant eigenvector.

Returns
CMBVectorSet with discriminant scores for each group

Definition at line 4599 of file sourcesinkdata.cpp.

References CMBVectorSet::Append(), and DFA_eigvector().

Referenced by DiscriminantFunctionAnalysis(), DiscriminantFunctionAnalysis(), and StepwiseDiscriminantFunctionAnalysis().

◆ DFA_Projected() [2/3]

CMBVectorSet SourceSinkData::DFA_Projected ( const string &  source1,
const string &  source2 
)
private

Projects two specific groups onto the discriminant function axis.

Parameters
source1Name of first source group
source2Name of second source group
Returns
CMBVectorSet with discriminant scores
Note
Current implementation projects all groups

Definition at line 4619 of file sourcesinkdata.cpp.

References CMBVectorSet::Append(), and DFA_eigvector().

◆ DFA_Projected() [3/3]

CMBVectorSet SourceSinkData::DFA_Projected ( const string &  source1,
SourceSinkData original 
)
private

Projects samples from original dataset onto discriminant function.

Uses discriminant function computed from current dataset to project samples from the original dataset. Useful for validating on held-out data.

Parameters
source1Name of source used in discriminant function
originalPointer to original dataset
Returns
CMBVectorSet with discriminant scores for original samples
Note
Target group from original dataset is excluded

Definition at line 4640 of file sourcesinkdata.cpp.

References CMBVectorSet::Append(), DFA_eigvector(), and target_group_.

◆ DFA_weight_vector()

CMBVector SourceSinkData::DFA_weight_vector ( const string &  source1,
const string &  source2 
)
private

Computes discriminant weight vector for two-group comparison.

Calculates the linear discriminant weights for separating two specific source groups using Fisher's linear discriminant analysis.

Formula: w = (μ₂ - μ₁) / (Σ₁ + Σ₂)

Parameters
source1Name of first source group
source2Name of second source group
Returns
Normalized CMBVector of discriminant weights (unit length)

Definition at line 4702 of file sourcesinkdata.cpp.

References GetElementNames(), and CMBVector::SetLabels().

◆ DFATransformed()

CMBVector SourceSinkData::DFATransformed ( const CMBVector eigenvector,
const string &  source_group 
)
private

Projects samples onto a discriminant function axis.

Transforms elemental profiles from a source group by computing their projections (dot products) with a discriminant eigenvector.

Projection formula: score_i = Σ(x_ij × w_j)

Parameters
eigenvectorDiscriminant function coefficients
source_groupName of the source group to project
Returns
CMBVector containing discriminant scores, labeled with sample names

Definition at line 2947 of file sourcesinkdata.cpp.

References CMBVector::SetLabel().

◆ DifferentiationPower() [1/2]

Elemental_Profile_Set SourceSinkData::DifferentiationPower ( bool  use_log,
bool  include_target 
)

Computes differentiation power for all source pairs.

Performs pairwise differentiation power analysis for all combinations of source groups, generating a comprehensive matrix of source separability.

Formula: D = 2 × |μ₁ - μ₂| / (σ₁ + σ₂)

Interpretation:

  • D > 2: Strong differentiation
  • D ≈ 1: Moderate differentiation
  • D < 0.5: Weak differentiation
Parameters
use_logIf true, compute using log-space statistics; if false, use linear-space statistics
include_targetIf true, include target group in comparisons
Returns
Elemental_Profile_Set with differentiation profiles for each source pair

Definition at line 3296 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), DifferentiationPower(), and target_group_.

Referenced by DifferentiationPower(), Conductor::ExecuteEDP(), and Conductor::ExecuteEDPM().

◆ DifferentiationPower() [2/2]

Elemental_Profile SourceSinkData::DifferentiationPower ( const string &  source1,
const string &  source2,
bool  use_log 
)

Computes differentiation power metric between two sources.

Calculates a standardized measure of how well each element differentiates between two sources. The metric quantifies separation in units of pooled standard deviations.

Formula: D = 2 × |μ₁ - μ₂| / (σ₁ + σ₂)

Interpretation:

  • D > 2: Strong differentiation (means differ by >1 pooled std dev)
  • D ≈ 1: Moderate differentiation
  • D < 0.5: Weak differentiation (substantial overlap)
Parameters
source1Name of first source group
source2Name of second source group
use_logIf true, compute using log-space statistics; if false, use linear-space statistics
Returns
Elemental_Profile containing differentiation power for each element
Note
Higher values indicate better discrimination ability
Complementary to p-values (considers effect size, not just significance)
See also
DifferentiationPower(bool, bool) for all pairwise comparisons

Definition at line 3256 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), ConcentrationSet::CalculateMean(), ConcentrationSet::CalculateMeanLog(), ConcentrationSet::CalculateStdDev(), ConcentrationSet::CalculateStdDevLog(), and GetElementNames().

◆ DifferentiationPower_P_value()

Elemental_Profile_Set SourceSinkData::DifferentiationPower_P_value ( bool  include_target)

Computes t-test p-values for all source pairs.

Performs pairwise t-test analysis for all combinations of source groups, generating a comprehensive matrix of statistical significance values.

Parameters
include_targetIf true, include target group in comparisons
Returns
Elemental_Profile_Set with p-value profiles for each source pair
Note
Lower p-values indicate statistically significant differences

Definition at line 3379 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), t_TestPValue(), and target_group_.

Referenced by Conductor::ExecuteAutoSelect(), and Conductor::ExecuteEDPM().

◆ DifferentiationPower_Percentage() [1/2]

Elemental_Profile_Set SourceSinkData::DifferentiationPower_Percentage ( bool  include_target)

Computes rank-based differentiation percentage for all source pairs.

Performs pairwise rank-based differentiation analysis for all combinations of source groups. Provides a non-parametric measure of source separability.

Parameters
include_targetIf true, include target group in comparisons
Returns
Elemental_Profile_Set with differentiation percentages for each source pair
Note
Values near 1.0 indicate excellent separation
Values near 0.5 indicate no separation

Definition at line 3356 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), DifferentiationPower_Percentage(), and target_group_.

Referenced by DifferentiationPower_Percentage(), Conductor::ExecuteEDP(), and Conductor::ExecuteEDPM().

◆ DifferentiationPower_Percentage() [2/2]

Elemental_Profile SourceSinkData::DifferentiationPower_Percentage ( const string &  source1,
const string &  source2 
)

Computes rank-based differentiation percentage between two sources.

Calculates the percentage of samples that can be correctly classified based on element concentrations using a rank-based approach. Provides a distribution-free measure of source separability.

Method:

  1. Pool samples from both sources
  2. Rank all concentrations for each element
  3. Count correct classifications (Source1 samples with low ranks + Source2 samples with high ranks, or vice versa)
  4. Return classification success percentage
Parameters
source1Name of first source group
source2Name of second source group
Returns
Elemental_Profile containing classification percentages (0-1) for each element
Note
Values near 1.0 indicate excellent separation
Values near 0.5 indicate no separation (random classification)
Non-parametric (no distributional assumptions)
See also
DifferentiationPower_Percentage(bool) for all pairwise comparisons

Definition at line 3319 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), ConcentrationSet::AppendSet(), ConcentrationSet::CalculateRanks(), and GetElementNames().

◆ DiscriminantFunctionAnalysis() [1/3]

DFA_result SourceSinkData::DiscriminantFunctionAnalysis ( )

Performs discriminant function analysis for all source groups.

Conducts pairwise discriminant function analysis (DFA) comparing each source group against all others combined. DFA identifies the linear combination of elemental concentrations that best separates each source from the rest, which helps assess source uniqueness and potential confounding.

For each source, computes:

  • Wilks' Lambda (measure of group separation)
  • F-test p-value (significance of separation)
  • Discriminant p-value (multivariate normality test)
  • Eigenvector (discriminant function coefficients)
  • Projected samples (scores along discriminant axis)
Returns
DFA_result containing statistics and projections for all sources
Note
Target group is excluded from analysis
Each source is compared against all others combined ("one vs rest")
Lower Wilks' Lambda indicates better separation

Definition at line 2814 of file sourcesinkdata.cpp.

References CMBVectorSet::Append(), CMBVectorSetSet::Append(), counter, DiscriminantFunctionAnalysis(), DFA_result::eigen_vectors, DFA_result::F_test_P_value, DFA_result::multi_projected, DFA_result::p_values, DFA_result::projected, CMBVector::SetLabel(), target_group_, and DFA_result::wilkslambda.

Referenced by DiscriminantFunctionAnalysis(), Conductor::ExecuteDFA(), Conductor::ExecuteDFAM(), Conductor::ExecuteDFAOnevsRest(), StepwiseDiscriminantFunctionAnalysis(), and StepwiseDiscriminantFunctionAnalysis().

◆ DiscriminantFunctionAnalysis() [2/3]

DFA_result SourceSinkData::DiscriminantFunctionAnalysis ( const string &  source1)

Performs discriminant function analysis for one source vs all others.

Conducts DFA comparing a single source group against all other sources combined ("one vs rest" comparison).

Parameters
source1Name of source group to test
Returns
DFA_result containing separation statistics and discriminant function
Note
All other source groups are pooled into an "Others" category

Definition at line 2894 of file sourcesinkdata.cpp.

References CMBVectorSet::Append(), AppendSampleSet(), DFA_eigvector(), DFA_P_Value(), DFA_Projected(), DFA_result::eigen_vectors, element_information_, DFA_result::F_test_P_value, CMBVectorSet::FTest_p_value(), DFA_result::p_values, PopulateElementInformation(), DFA_result::projected, TheRest(), DFA_result::wilkslambda, and WilksLambda().

◆ DiscriminantFunctionAnalysis() [3/3]

DFA_result SourceSinkData::DiscriminantFunctionAnalysis ( const string &  source1,
const string &  source2 
)

Performs discriminant function analysis between two specific sources.

Conducts pairwise DFA to assess how well two source groups can be distinguished based on their elemental compositions.

Parameters
source1Name of first source group
source2Name of second source group
Returns
DFA_result containing separation statistics and discriminant function
Note
Creates temporary dataset with only the two specified sources
Returns empty result if eigenvector computation fails

Definition at line 2854 of file sourcesinkdata.cpp.

References CMBVectorSet::Append(), AppendSampleSet(), DFA_eigvector(), DFA_P_Value(), DFA_Projected(), DFA_result::eigen_vectors, element_information_, DFA_result::F_test_P_value, CMBVectorSet::FTest_p_value(), DFA_result::p_values, PopulateElementInformation(), DFA_result::projected, CMBVector::size(), DFA_result::wilkslambda, and WilksLambda().

◆ ElementDataToJsonObject()

QJsonObject SourceSinkData::ElementDataToJsonObject ( ) const

Exports all elemental profile data to a JSON object.

Serializes all sample groups and their elemental profiles to JSON format.

Returns
QJsonObject containing all elemental profile sets

Definition at line 2673 of file sourcesinkdata.cpp.

Referenced by MainWindow::buildProjectJson().

◆ ElementInformationToJsonObject()

QJsonObject SourceSinkData::ElementInformationToJsonObject ( ) const

Exports element information metadata to a JSON object.

Serializes all element metadata (role, standard ratio, base element, inclusion flag) to a JSON object for saving or transmission.

Returns
QJsonObject containing all element information

Definition at line 2726 of file sourcesinkdata.cpp.

References element_information_, and Role().

Referenced by MainWindow::buildProjectJson().

◆ ElementOrder()

vector< string > SourceSinkData::ElementOrder ( )
private

Retrieves the ordering of chemical elements.

Returns
Vector of element names in analysis order

Definition at line 5095 of file sourcesinkdata.cpp.

References element_order_.

Referenced by GetObservedElementalProfile(), GetPredictedElementalProfile(), and MCMC().

◆ ElementsToBeUsedInCMB()

vector< string > SourceSinkData::ElementsToBeUsedInCMB ( )

Identifies chemical elements to be used in CMB analysis.

Scans the element information map and collects all elements marked with the 'element' role. Updates constituent count and ordering vectors.

Returns
Vector of element names to be included in CMB analysis
Note
Updates constituent_order_ and numberofconstituents_

Definition at line 2070 of file sourcesinkdata.cpp.

References constituent_order_, element_information::element, element_information_, and numberofconstituents_.

◆ ExtractChemicalElements()

SourceSinkData SourceSinkData::ExtractChemicalElements ( bool  isotopes) const

Extract only chemical elements (and optionally isotopes)

Creates a new SourceSinkData containing only elements with role 'element' (and optionally 'isotope'), excluding particle size, organic matter, and other non-element constituents.

Parameters
isotopesIf true, also include isotope ratios
Returns
New SourceSinkData with only chemical elements

Definition at line 287 of file sourcesinkdata.cpp.

References AssignAllDistributions(), element_information_, ExtractChemicalElements(), omconstituent_, PopulateElementDistributions(), PopulateElementInformation(), regression_p_value_threshold_, sizeconsituent_, and target_group_.

Referenced by Conductor::ExecuteAutoSelect(), and ExtractChemicalElements().

◆ ExtractConcentrationData()

profiles_data SourceSinkData::ExtractConcentrationData ( const vector< vector< string > > &  indicators) const

Extract concentration data for specified samples.

Extracts elemental concentration data for a list of samples identified by [group_name, sample_name] pairs. Returns data in a structured format suitable for analysis.

Parameters
indicatorsVector of [group_name, sample_name] pairs identifying samples
Returns
profiles_data structure containing element names, sample names, and concentration values

Definition at line 445 of file sourcesinkdata.cpp.

References profiles_data::element_names, Elemental_Profile_Set::GetConcentrationsForSample(), GetElementNames(), profiles_data::sample_names, and profiles_data::values.

Referenced by MainWindow::on_tree_selectionChanged().

◆ ExtractConcentrationSet()

map< string, ConcentrationSet > SourceSinkData::ExtractConcentrationSet ( )

Extracts concentration distributions for all elements across sources.

Collects all concentration values for each element across all source samples (excluding target) into ConcentrationSet objects. This aggregates data for statistical analysis of elemental distributions across the entire source dataset.

Returns
Map of element names to ConcentrationSet objects containing all source sample concentrations for that element
Note
Target group samples are excluded
Each ConcentrationSet contains values from all sources combined

Definition at line 3151 of file sourcesinkdata.cpp.

References ConcentrationSet::AppendValue(), GetElementNames(), and target_group_.

Referenced by OptimalBoxCoxParameters().

◆ ExtractElementConcentrations()

element_data SourceSinkData::ExtractElementConcentrations ( const string &  element,
const string &  group 
) const

Extract concentration data for a specific element from a group.

Retrieves all concentration values for a single element across all samples within a specified group. Useful for univariate analysis of a single element's distribution within a source or target group.

Parameters
elementElement name to extract
groupGroup name to extract from
Returns
element_data structure containing group name, sample names, and concentration values

Definition at line 495 of file sourcesinkdata.cpp.

References element_data::group_name, element_data::sample_names, and element_data::values.

Referenced by ExtractElementDataByGroup().

◆ ExtractElementDataByGroup()

map< string, vector< double > > SourceSinkData::ExtractElementDataByGroup ( const string &  element) const

Extract concentration data for a specific element from all groups.

Retrieves all concentration values for a single element organized by group. Returns a map where keys are group names and values are vectors of concentrations for that element within each group.

Parameters
elementElement name to extract
Returns
Map of group_name -> vector of concentration values

Definition at line 542 of file sourcesinkdata.cpp.

References ExtractElementConcentrations(), GetGroupNames(), and element_data::values.

Referenced by MainWindow::on_tree_selectionChanged().

◆ ExtractSamplesAsProfileSet()

Elemental_Profile_Set SourceSinkData::ExtractSamplesAsProfileSet ( const vector< vector< string > > &  indicators) const

Extract samples as an Elemental_Profile_Set.

Extracts specified samples and combines them into a single profile set. Sample names are prefixed with their group name (e.g., "Agricultural-Sample1") to ensure uniqueness when combining samples from different groups.

Parameters
indicatorsVector of [group_name, sample_name] pairs identifying samples
Returns
Elemental_Profile_Set containing the extracted samples

Definition at line 472 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile().

Referenced by MainWindow::on_tree_selectionChanged().

◆ ExtractSpecificElements()

SourceSinkData SourceSinkData::ExtractSpecificElements ( const vector< string > &  element_list) const

Extract specific elements from source groups.

Creates a new SourceSinkData containing only the specified elements from source groups. Target group is excluded. Useful for subset analysis or element selection optimization.

Parameters
element_listList of element names to extract
Returns
New SourceSinkData with only specified elements from sources

Definition at line 311 of file sourcesinkdata.cpp.

References AssignAllDistributions(), element_information_, PopulateElementDistributions(), PopulateElementInformation(), and target_group_.

Referenced by StepwiseDiscriminantFunctionAnalysis(), StepwiseDiscriminantFunctionAnalysis(), and StepwiseDiscriminantFunctionAnalysis().

◆ FirstOMConstituent()

string SourceSinkData::FirstOMConstituent ( )

Retrieves the name of the first organic matter constituent.

Searches element information for the first element designated as organic carbon/matter.

Returns
Name of first OM constituent, or empty string if none found
Note
Returns first match only

Definition at line 4416 of file sourcesinkdata.cpp.

References element_information_, and element_information::organic_carbon.

◆ FirstSizeConstituent()

string SourceSinkData::FirstSizeConstituent ( )

Retrieves the name of the first particle size constituent.

Searches element information for the first element designated as particle size.

Returns
Name of first size constituent, or empty string if none found
Note
Returns first match only

Definition at line 4433 of file sourcesinkdata.cpp.

References element_information_, and element_information::particle_size.

◆ GetCalculatedElementMeans()

ResultItem SourceSinkData::GetCalculatedElementMeans ( )

Computes estimated mean concentrations for all source elements.

Calculates the mean elemental concentrations for each source group using the current estimated distributions.

Returns
ResultItem containing Elemental_Profile_Set with mean profiles for each source
Note
Only includes source groups (target excluded)
Uses estimated distributions (updated during optimization/MCMC)

Definition at line 2396 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), Elemental_Profile_Set::AppendProfile(), element_order_, elemental_profile_set, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetType(), and target_group_.

◆ GetCalculatedElementMu()

ResultItem SourceSinkData::GetCalculatedElementMu ( )

Computes μ parameters from fitted log-normal distributions for source elements.

Calculates the μ (log-space mean) parameter for each element in each source group based on the fitted log-normal distributions from source sample data.

Returns
ResultItem containing Elemental_Profile_Set with μ values for each source
Note
Uses CalculateMeanLog() - computed from fitted distribution

Definition at line 2479 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), Elemental_Profile_Set::AppendProfile(), element_order_, elemental_profile_set, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetType(), and target_group_.

◆ GetCalculatedElementSigma()

ResultItem SourceSinkData::GetCalculatedElementSigma ( )

Computes estimated standard deviations for all source elements.

Calculates the standard deviations of elemental concentrations for each source group using the current estimated distributions.

Returns
ResultItem containing Elemental_Profile_Set with std dev profiles for each source
Note
Different calculations for normal vs log-normal distributions

Definition at line 2420 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), Elemental_Profile_Set::AppendProfile(), element_order_, elemental_profile_set, lognormal, normal, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetType(), and target_group_.

◆ GetContribution()

ResultItem SourceSinkData::GetContribution ( )

Packages source contributions into a ResultItem for output.

Creates a ResultItem containing the current source contribution estimates, formatted for export or display.

Returns
ResultItem of type 'contribution' containing source fractions
Note
Creates new Contribution object on heap (managed by ResultItem)

Definition at line 2198 of file sourcesinkdata.cpp.

References contribution, GetContributionVector(), GetSourceOrder(), ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by Conductor::ExecuteLevenbergMarquardt().

◆ GetContributionVector()

CVector SourceSinkData::GetContributionVector ( bool  include_all = true)
private

Retrieves the current source contribution fractions.

Returns a vector of contribution fractions from each source. Contributions represent the fraction of the target sample originating from each source, subject to the constraint: Σ f_i = 1.

Parameters
include_allIf true, returns all n contributions including the constrained one. If false, returns only the n-1 independent contributions used in optimization.
Returns
Vector of contribution fractions, size n or n-1
Note
All contributions satisfy: 0 ≤ f_i ≤ 1 and Σ f_i = 1

Definition at line 1583 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::GetContribution(), GetSampleSet(), numberofsourcesamplesets_, and samplesetsorder_.

Referenced by BootStrap(), BootStrap(), GetContribution(), InitializeContributionsRandomly(), LM_Batch(), PredictTarget(), PredictTarget_Isotope(), PredictTarget_Isotope_delta(), ResidualJacobian(), ResidualJacobian_arma(), SetContribution(), SetContributionSoftmax(), SetParameterValue(), SolveLevenberg_Marquardt(), and VerifySource().

◆ GetContributionVectorSoftmax()

CVector SourceSinkData::GetContributionVectorSoftmax ( )
private

Retrieves the softmax parameters for source contributions.

Returns the unconstrained softmax parameters x_i that are transformed to contribution fractions via: f_i = exp(x_i) / Σ exp(x_j)

Returns
Vector of softmax parameters, size n (all sources)
Note
Softmax parameters are unbounded: x_i ∈ (-∞, +∞)

Definition at line 1603 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::GetContributionSoftmax(), GetSampleSet(), numberofsourcesamplesets_, and samplesetsorder_.

Referenced by ResidualJacobian_softmax(), and SolveLevenberg_Marquardt().

◆ GetElementalProfile()

Elemental_Profile * SourceSinkData::GetElementalProfile ( const string &  sample_name)
private

Finds and retrieves an elemental profile by sample name.

Searches all groups (sources and target) for a sample with the given name and returns a pointer to its elemental profile. Useful when the group containing the sample is unknown.

Parameters
sample_nameName of the sample to find
Returns
Pointer to the elemental profile if found, nullptr otherwise
Note
Searches all groups sequentially until sample is found
Returns pointer to internal data - do not delete

Definition at line 2178 of file sourcesinkdata.cpp.

Referenced by InitializeParametersAndObservations().

◆ GetElementDistribution() [1/2]

ConcentrationSet * SourceSinkData::GetElementDistribution ( const string &  element_name)

Retrieves pointer to element distribution at dataset level.

Parameters
element_nameName of the element
Returns
Pointer to ConcentrationSet, or nullptr if not found

Definition at line 5055 of file sourcesinkdata.cpp.

References element_distributions_.

Referenced by BracketTest(), Conductor::ExecuteDistributionFitting(), Conductor::ExecuteKolmogorovSmirnovIndividual(), GetElementDistribution(), and SetParameterValue().

◆ GetElementDistribution() [2/2]

ConcentrationSet * SourceSinkData::GetElementDistribution ( const string &  element_name,
const string &  sample_group 
)

Retrieves pointer to element distribution for a specific group.

Parameters
element_nameName of the element
sample_groupName of the source or target group
Returns
Pointer to ConcentrationSet, or nullptr if not found

Definition at line 5063 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::GetElementDistribution(), GetElementDistribution(), and GetSampleSet().

◆ GetElementDistributionMuParameter()

Parameter * SourceSinkData::GetElementDistributionMuParameter ( size_t  element_index,
size_t  source_index 
)
private

Retrieves pointer to the μ (mean) parameter for an element distribution.

Accesses the parameter object representing the mean (μ) of the log-normal distribution for a specific element in a specific source.

Parameters
element_indexIndex of the element in element_order_ (0-based)
source_indexIndex of the source in samplesetsorder_ (0-based)
Returns
Pointer to the Parameter object, or nullptr if indices are out of bounds
Note
For log-normal distributions: actual mean = exp(μ + σ²/2)

Definition at line 1690 of file sourcesinkdata.cpp.

References numberofsourcesamplesets_, and parameters_.

Referenced by GetElementDistributionMuValue().

◆ GetElementDistributionMuValue()

double SourceSinkData::GetElementDistributionMuValue ( size_t  element_index,
size_t  source_index 
)
private

Retrieves the current value of the μ parameter for an element distribution.

Parameters
element_indexIndex of the element in element_order_ (0-based)
source_indexIndex of the source in samplesetsorder_ (0-based)
Returns
Current μ value, or 0.0 if parameter cannot be retrieved

Definition at line 1743 of file sourcesinkdata.cpp.

References GetElementDistributionMuParameter(), and Parameter::Value().

◆ GetElementDistributionSigmaParameter()

Parameter * SourceSinkData::GetElementDistributionSigmaParameter ( size_t  element_index,
size_t  source_index 
)
private

Retrieves pointer to the σ (std dev) parameter for an element distribution.

Accesses the parameter object representing the standard deviation (σ) of the log-normal distribution for a specific element in a specific source.

Parameters
element_indexIndex of the element in element_order_ (0-based)
source_indexIndex of the source in samplesetsorder_ (0-based)
Returns
Pointer to the Parameter object, or nullptr if indices are out of bounds
Note
σ represents log-space standard deviation for log-normal distributions

Definition at line 1716 of file sourcesinkdata.cpp.

References numberofconstituents_, numberofsourcesamplesets_, and parameters_.

Referenced by GetElementDistributionSigmaValue().

◆ GetElementDistributionSigmaValue()

double SourceSinkData::GetElementDistributionSigmaValue ( size_t  element_index,
size_t  source_index 
)
private

Retrieves the current value of the σ parameter for an element distribution.

Parameters
element_indexIndex of the element in element_order_ (0-based)
source_indexIndex of the source in samplesetsorder_ (0-based)
Returns
Current σ value, or 0.0 if parameter cannot be retrieved

Definition at line 1758 of file sourcesinkdata.cpp.

References GetElementDistributionSigmaParameter(), and Parameter::Value().

◆ GetElementInformation() [1/2]

map< string, element_information > * SourceSinkData::GetElementInformation ( )

Retrieves pointer to the element information map.

Provides access to element metadata including roles, standard ratios, base elements, and inclusion flags for all elements in the dataset.

Returns
Pointer to element information map

Definition at line 5042 of file sourcesinkdata.cpp.

References element_information_.

Referenced by ElementTableDelegate::createEditor(), ElementTableModel::data(), LM_Batch(), MCMC(), ElementTableModel::setData(), ElementTableDelegate::setEditorData(), and VerifySource().

◆ GetElementInformation() [2/2]

element_information * SourceSinkData::GetElementInformation ( const string &  element_name)

Retrieves pointer to element information metadata by name.

Parameters
element_nameName of the element
Returns
Pointer to element_information, or nullptr if not found

Definition at line 5047 of file sourcesinkdata.cpp.

References element_information_.

◆ GetElementNames()

◆ GetEstimatedElementMean()

ResultItem SourceSinkData::GetEstimatedElementMean ( )

Computes actual mean concentrations from estimated log-normal parameters.

Calculates the actual concentration means for each element in each source using the estimated μ and σ parameters from Bayesian inference.

Formula: Mean = exp(μ + σ²/2)

Returns
ResultItem containing Elemental_Profile_Set with mean concentrations

Definition at line 2527 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), Elemental_Profile_Set::AppendProfile(), element_order_, elemental_profile_set, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetType(), and target_group_.

◆ GetEstimatedElementMu()

ResultItem SourceSinkData::GetEstimatedElementMu ( )

Retrieves estimated μ parameters from Bayesian inference for source elements.

Returns the inferred μ (log-space mean) parameters for each element in each source group as estimated during MCMC sampling or optimization.

Returns
ResultItem containing Elemental_Profile_Set with inferred μ values
Note
Uses GetEstimatedMu() - updated during MCMC/optimization

Definition at line 2503 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), Elemental_Profile_Set::AppendProfile(), element_order_, elemental_profile_set, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetType(), and target_group_.

◆ GetEstimatedElementSigma()

ResultItem SourceSinkData::GetEstimatedElementSigma ( )

Retrieves estimated σ parameters from Bayesian inference for source elements.

Returns the inferred σ (log-space standard deviation) parameters for each element in each source group as estimated during MCMC sampling or optimization.

Returns
ResultItem containing Elemental_Profile_Set with inferred σ values
Note
Values are in log-space (not actual concentration std dev)

Definition at line 2553 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), Elemental_Profile_Set::AppendProfile(), element_order_, elemental_profile_set, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetType(), and target_group_.

◆ GetFittedDistribution()

Distribution * SourceSinkData::GetFittedDistribution ( const string &  element_name)

Get the fitted distribution for a specific element at dataset level.

Returns a pointer to the Distribution object fitted to all data for this element (across all groups). This is the distribution used for likelihood calculations in MCMC.

Parameters
element_nameName of the element
Returns
Pointer to fitted Distribution, or nullptr if element not found

Definition at line 596 of file sourcesinkdata.cpp.

References element_distributions_.

Referenced by MainWindow::showdistributionsforelements().

◆ GetGroupNames()

vector< string > SourceSinkData::GetGroupNames ( ) const

Get all group names in the dataset.

Returns the names of all sample sets (source and target groups). These are the top-level keys of the SourceSinkData map.

Returns
Vector of all group names

Definition at line 407 of file sourcesinkdata.cpp.

Referenced by MainWindow::ElementsToQStandardItem(), ExtractElementDataByGroup(), MainWindow::ToQStandardItem(), and MainWindow::ToQStandardItemModel().

◆ GetMLRResults()

vector< ResultItem > SourceSinkData::GetMLRResults ( )

Retrieves multiple linear regression results for all sample groups.

Collects the organic matter (OM) and particle size regression models for each source group. These regressions are used to correct elemental concentrations for variations in OM content and particle size distribution.

Returns
Vector of ResultItems, one per sample group, containing MLR models
Note
Each ResultItem is configured for table display
Includes both source groups and target group
Regressions must be computed first via PerformRegressionVsOMAndSize()

Definition at line 2305 of file sourcesinkdata.cpp.

References ResultItem::SetName(), and ResultItem::SetShowTable().

Referenced by Conductor::ExecuteMLR().

◆ GetObjectiveFunctionValue()

double SourceSinkData::GetObjectiveFunctionValue ( )

Returns the objective function value for optimization algorithms.

Computes the negative log-likelihood based on the current parameter values and estimation mode. Used by optimization algorithms where minimizing -log(L) is equivalent to maximizing likelihood L.

Returns
Negative log-likelihood value (lower values indicate better fit)

Definition at line 1451 of file sourcesinkdata.cpp.

References LogLikelihood(), and parameter_estimation_mode_.

◆ GetObservedElementalProfile()

ResultItem SourceSinkData::GetObservedElementalProfile ( )

Retrieves the observed elemental concentrations for the selected target sample.

Extracts the measured elemental composition of the currently selected target sample. These are the observed values that the model attempts to reproduce.

Returns
ResultItem containing the observed Elemental_Profile for chemical elements
Note
Only includes chemical elements, not isotopes

Definition at line 2350 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), ElementOrder(), ObservedDataforSelectedSample(), predicted_concentration, selected_target_sample_, ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by GetObservedvsModeledElementalProfile().

◆ GetObservedElementalProfile_Isotope()

ResultItem SourceSinkData::GetObservedElementalProfile_Isotope ( )

Retrieves the observed isotope delta values for the selected target sample.

Extracts the measured isotopic composition (δ values in ‰) of the currently selected target sample.

Returns
ResultItem containing the observed Elemental_Profile with isotope δ values
Note
Only includes isotopes, not chemical elements
Values are in delta notation (‰)

Definition at line 2373 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), IsotopeOrder(), ObservedDataforSelectedSample_Isotope_delta(), predicted_concentration, selected_target_sample_, ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by GetObservedvsModeledElementalProfile_Isotope().

◆ GetObservedvsModeledElementalProfile()

ResultItem SourceSinkData::GetObservedvsModeledElementalProfile ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)

Creates a comparison of observed vs modeled elemental profiles.

Generates a profile set containing both the observed target sample composition and the model's predicted composition for side-by-side comparison.

Parameters
param_modeControls whether to use parametric or empirical source means
Returns
ResultItem containing Elemental_Profile_Set with "Observed" and "Modeled" profiles
Note
Only includes chemical elements, not isotopes

Definition at line 2280 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), elemental_profile_set, GetObservedElementalProfile(), GetPredictedElementalProfile(), ResultItem::Result(), ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by Conductor::ExecuteLevenbergMarquardt().

◆ GetObservedvsModeledElementalProfile_Isotope()

ResultItem SourceSinkData::GetObservedvsModeledElementalProfile_Isotope ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)

Creates a comparison of observed vs modeled isotope delta values.

Generates a profile set containing both the observed target sample isotopic composition and the model's predicted isotope delta values.

Parameters
param_modeControls whether to use parametric or empirical source means
Returns
ResultItem containing Elemental_Profile_Set with "Observed" and "Modeled" isotope profiles
Note
Only includes isotopes, not chemical elements
All values are in delta notation (‰)

Definition at line 2325 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), elemental_profile_set, GetObservedElementalProfile_Isotope(), GetPredictedElementalProfile_Isotope(), ResultItem::Result(), ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by Conductor::ExecuteLevenbergMarquardt().

◆ GetOptions()

QMap< QString, double > * SourceSinkData::GetOptions ( )

Retrieves pointer to the options map.

Returns
Pointer to QMap containing configuration options

Definition at line 5141 of file sourcesinkdata.cpp.

References options_.

Referenced by MainWindow::onIncludeExcludeSample().

◆ GetOutputPath()

string SourceSinkData::GetOutputPath ( ) const

Get the output directory path.

Returns the path where analysis results and output files will be saved.

Returns
Current output path

Definition at line 5148 of file sourcesinkdata.cpp.

References outputpath_.

◆ GetParameterName()

string SourceSinkData::GetParameterName ( int  index) const

Get the name of a parameter by its index.

Retrieves the descriptive name of an optimization parameter (e.g., "Agricultural_contribution", "Urban_Al_mu") by its position in the parameters vector.

Parameters
indexParameter index (0-based)
Returns
Parameter name, or empty string if index invalid

Definition at line 635 of file sourcesinkdata.cpp.

References Parameter::Name(), and parameter().

◆ GetParameterValue() [1/2]

CVector SourceSinkData::GetParameterValue ( ) const
private

Retrieves all current parameter values as a vector.

Returns a vector containing all parameter values in the order they appear in the parameters_ vector. The parameter layout depends on estimation_mode_.

Returns
Vector of all parameter values

Definition at line 1950 of file sourcesinkdata.cpp.

References parameters_.

Referenced by GradientUpdate().

◆ GetParameterValue() [2/2]

double SourceSinkData::GetParameterValue ( size_t  index) const
private

Retrieves a single parameter value by index.

Parameters
indexParameter index in the parameters_ vector
Returns
Parameter value at the specified index
Note
No bounds checking - ensure index is valid

Definition at line 1929 of file sourcesinkdata.cpp.

References parameters_.

◆ GetPredictedElementalProfile()

ResultItem SourceSinkData::GetPredictedElementalProfile ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)

Generates predicted elemental concentrations for the target sample.

Computes the model's predicted elemental composition using the current source contributions and profiles.

Parameters
param_modeControls whether to use parametric or empirical source means
Returns
ResultItem containing the predicted Elemental_Profile
Note
Only includes chemical elements, not isotopes

Definition at line 2220 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), ElementOrder(), predicted_concentration, PredictTarget(), ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by Conductor::ExecuteLevenbergMarquardt(), and GetObservedvsModeledElementalProfile().

◆ GetPredictedElementalProfile_Isotope()

ResultItem SourceSinkData::GetPredictedElementalProfile_Isotope ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)

Generates predicted isotope delta values for the target sample.

Computes the model's predicted isotopic composition (δ values in ‰) using current source contributions and isotope profiles.

Parameters
param_modeControls whether to use parametric or empirical source means
Returns
ResultItem containing the predicted Elemental_Profile with isotope δ values
Note
Only includes isotopes, not chemical elements
Values are in delta notation (‰)

Definition at line 2257 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), IsotopeOrder(), predicted_concentration, PredictTarget_Isotope_delta(), ResultItem::SetName(), ResultItem::SetResult(), and ResultItem::SetType().

Referenced by GetObservedvsModeledElementalProfile_Isotope().

◆ GetPredictedValues()

CVector SourceSinkData::GetPredictedValues ( )

Retrieves predicted values for all observations.

Collects the predicted values from all observation objects for comparison with actual observations.

Returns
Vector of predicted values matching the observations vector

Definition at line 2243 of file sourcesinkdata.cpp.

References observation(), ObservationsCount(), and Observation::PredictedValue().

◆ GetSampleNames()

vector< string > SourceSinkData::GetSampleNames ( const string &  group_name) const

Get all sample names within a specific group.

Returns the names of all samples (elemental profiles) within a specified source or target group.

Parameters
group_nameName of the group to query
Returns
Vector of sample names, or empty vector if group not found

Definition at line 395 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::GetSampleNames().

Referenced by GenericForm::GenericForm(), SelectSampleTableModel::data(), SelectSampleTableModel::GetProfileSet(), and SelectSampleTableModel::GetProfileSet().

◆ GetSampleSet()

◆ GetSourceContributions()

CVector SourceSinkData::GetSourceContributions ( )
private

Retrieves the contributions from all sources.

Calculates source contributions where the first (size-2) sources have their contributions stored as parameters, and the last source's contribution is calculated as the remainder to ensure all contributions sum to 1.

Returns
CVector of size (size()-1) containing contribution values for each source
Note
The last element is computed as (1 - sum of other contributions)

Definition at line 941 of file sourcesinkdata.cpp.

References parameter(), and Parameter::Value().

Referenced by LogPriorContributions().

◆ GetSourceOrder()

vector< string > SourceSinkData::GetSourceOrder ( ) const
private

Retrieves the ordering of source groups.

Returns
Vector of source group names in parameter order

Definition at line 5080 of file sourcesinkdata.cpp.

References samplesetsorder_.

Referenced by BootStrap(), GetContribution(), InitializeContributionsRandomly(), InitializeContributionsRandomlySoftmax(), MCMC(), ResidualJacobian(), ResidualJacobian_arma(), and ResidualJacobian_softmax().

◆ GetSourceProfiles()

vector< ResultItem > SourceSinkData::GetSourceProfiles ( )

Retrieves elemental profiles for all source groups.

Collects the complete elemental profile sets for each source group, packaged as ResultItems for display.

Returns
Vector of ResultItems, one per source group
Note
Target group is excluded

Definition at line 2448 of file sourcesinkdata.cpp.

References elemental_profile_set, ResultItem::SetName(), ResultItem::SetResult(), ResultItem::SetShowAsString(), ResultItem::SetShowGraph(), ResultItem::SetShowTable(), ResultItem::SetType(), and target_group_.

Referenced by Conductor::ExecuteOMSizeCorrect().

◆ GetTargetGroup()

string SourceSinkData::GetTargetGroup ( ) const

Retrieves the name of the target group.

Returns
Name of the target group, or empty string if not set

Definition at line 5022 of file sourcesinkdata.cpp.

References target_group_.

Referenced by Conductor::ExecuteMLR(), InitializeParametersAndObservations(), ObservedDataforSelectedSample(), ObservedDataforSelectedSample_Isotope(), ObservedDataforSelectedSample_Isotope_delta(), and SelectSamples::SetData().

◆ Gradient()

CVector SourceSinkData::Gradient ( const CVector &  parameters,
estimation_mode  est_mode 
)
private

Computes the normalized gradient of the log-likelihood function.

Calculates the gradient vector ∇log(L) using numerical differentiation (finite differences). The gradient points in the direction of steepest ascent for the log-likelihood.

Numerical Differentiation: ∂log(L)/∂θ_i ≈ [log(L(θ + ε·e_i)) - log(L(θ))] / ε

Parameters
parametersParameter vector at which to evaluate the gradient
est_modeEstimation mode determining which likelihood components to include
Returns
Normalized gradient vector (unit length: ||∇log(L)|| = 1)
Note
The gradient is normalized by its L2 norm for numerical stability

Definition at line 1963 of file sourcesinkdata.cpp.

References epsilon_, LogLikelihood(), and SetParameterValue().

Referenced by GradientUpdate().

◆ GradientUpdate()

CVector SourceSinkData::GradientUpdate ( estimation_mode  estmode = estimation_mode::elemental_profile_and_contribution)

Performs one gradient ascent step with adaptive step size.

Executes a single iteration of gradient ascent optimization on the log-likelihood function using an adaptive step size (distance_coeff_).

Algorithm:

  1. Compute gradient direction at current parameters
  2. Try step sizes: distance_coeff_ and 2×distance_coeff_
  3. Accept step that improves likelihood
  4. Adjust step size for next iteration
Parameters
estmodeEstimation mode determining which likelihood components to include
Returns
Updated parameter vector after the gradient step
Note
Modifies distance_coeff_ member variable for next iteration

Definition at line 1993 of file sourcesinkdata.cpp.

References distance_coeff_, GetParameterValue(), Gradient(), LogLikelihood(), and SetParameterValue().

◆ GrandMean()

double SourceSinkData::GrandMean ( const string &  element,
bool  use_log 
)
private

Computes grand mean concentration for an element across all sources.

Calculates the overall mean concentration weighted by sample sizes across all source groups (excluding target).

Formula: μ_grand = Σ(n_i × μ_i) / Σ(n_i)

Parameters
elementName of the element
use_logIf true, compute using log-space means
Returns
Weighted grand mean concentration
Note
Target group is excluded

Definition at line 3437 of file sourcesinkdata.cpp.

References ConcentrationSet::CalculateMean(), ConcentrationSet::CalculateMeanLog(), and target_group_.

◆ IncludeExcludeAllElements()

void SourceSinkData::IncludeExcludeAllElements ( bool  include_in_analysis)

Sets inclusion flag for all elements.

Enables or disables all elements for analysis in batch.

Parameters
include_in_analysisIf true, include all; if false, exclude all
Note
Affects all elements regardless of role

Definition at line 3426 of file sourcesinkdata.cpp.

References element_information_.

◆ IncludeExcludeElementsBasedOn()

void SourceSinkData::IncludeExcludeElementsBasedOn ( const vector< string > &  elements)

Sets element inclusion based on a specified list.

First excludes all elements from analysis, then includes only those specified in the provided list. Useful for restricting analysis to a subset of elements (e.g., elements with sufficient data quality).

Parameters
elementsVector of element names to include in analysis
Note
All elements not in the list are excluded
Elements in the list that don't exist are silently ignored
Does not affect element roles, only the inclusion flag

Definition at line 3603 of file sourcesinkdata.cpp.

References element_information_.

Referenced by Conductor::ExecuteANOVA(), Conductor::ExecuteAutoSelect(), and Conductor::ExecuteSDFAM().

◆ InitializeContributionsRandomly()

bool SourceSinkData::InitializeContributionsRandomly ( )
private

Initialize source contributions randomly (linear constraint)

Randomly initializes contribution values for all sources such that they sum to 1.0 and all values are non-negative. Uses uniform random sampling with rejection until valid contributions are found.

Returns
Always returns true

Definition at line 644 of file sourcesinkdata.cpp.

References GetContributionVector(), GetSampleSet(), GetSourceOrder(), samplesetsorder_, Elemental_Profile_Set::SetContribution(), and SetContribution().

Referenced by SolveLevenberg_Marquardt().

◆ InitializeContributionsRandomlySoftmax()

bool SourceSinkData::InitializeContributionsRandomlySoftmax ( )
private

Initialize source contributions randomly (softmax transformation)

Randomly initializes contribution values using softmax transformation of normally distributed random variables. This ensures contributions automatically sum to 1.0 and are non-negative without rejection sampling.

Softmax transformation: contribution_i = exp(X_i) / sum(exp(X_j)) where X ~ N(0,1)

Returns
Always returns true

Definition at line 661 of file sourcesinkdata.cpp.

References GetSampleSet(), GetSourceOrder(), samplesetsorder_, Elemental_Profile_Set::SetContribution(), and SetContributionSoftmax().

Referenced by SolveLevenberg_Marquardt().

◆ InitializeParametersAndObservations()

bool SourceSinkData::InitializeParametersAndObservations ( const string &  targetsamplename,
estimation_mode  est_mode = estimation_mode::elemental_profile_and_contribution 
)

Initialize parameters and observations for MCMC optimization.

Sets up the complete parameter space and observation vector for Bayesian inference of source contributions and/or source profiles. The exact parameters created depend on the estimation mode:

  • only_contributions: Only source contribution parameters
  • elemental_profile_and_contribution: Contributions + mu/sigma for each source-element
  • source_elemental_profiles_based_on_source_data: Only source profile parameters
Parameters
targetsamplenameName of the target sample to unmix
est_modeEstimation mode controlling which parameters to optimize
Returns
true if successful, false if data not loaded
Note
Must be called before running MCMC or optimization

Definition at line 676 of file sourcesinkdata.cpp.

References Observation::AppendValues(), dirichlet, element_information::element, element_information_, GetElementalProfile(), GetTargetGroup(), Elemental_Profile::GetValue(), element_information::isotope, lognormal, normal, numberofconstituents_, numberofisotopes_, numberofsourcesamplesets_, observations_, only_contributions, Distribution::parameters, parameters_, PopulateConstituentOrders(), samplesetsorder_, selected_target_sample_, Observation::SetName(), Parameter::SetName(), Parameter::SetPriorDistribution(), Parameter::SetRange(), source_elemental_profiles_based_on_source_data, and target_group_.

Referenced by BootStrap(), BootStrap(), Conductor::ExecuteErrorAnalysis(), Conductor::ExecuteGA(), Conductor::ExecuteGA_FixedProfile(), Conductor::ExecuteGA_NoTargets(), Conductor::ExecuteLevenbergMarquardt(), LM_Batch(), MCMC(), MCMC_Batch(), and VerifySource().

◆ IsotopeOrder()

vector< string > SourceSinkData::IsotopeOrder ( )
private

Retrieves the ordering of isotopes.

Returns
Vector of isotope names in analysis order

Definition at line 5100 of file sourcesinkdata.cpp.

References isotope_order_.

Referenced by GetObservedElementalProfile_Isotope(), GetPredictedElementalProfile_Isotope(), and MCMC().

◆ IsotopesToBeUsedInCMB()

vector< string > SourceSinkData::IsotopesToBeUsedInCMB ( )

Identifies isotopes to be used in CMB analysis.

Scans the element information map and collects all isotopes marked with the 'isotope' role AND flagged for inclusion in analysis.

Returns
Vector of isotope names to be included in CMB analysis
Note
Updates isotope_order_ and numberofisotopes_
Only includes isotopes where include_in_analysis = true

Definition at line 2089 of file sourcesinkdata.cpp.

References element_information_, element_information::isotope, isotope_order_, and numberofisotopes_.

◆ LM_Batch()

CMBTimeSeriesSet SourceSinkData::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.

Performs batch source apportionment on all samples in the target group, solving the CMB model via Levenberg-Marquardt optimization for each sample.

Parameters
transformTransformation type (linear or softmax) for contributions
apply_om_size_correctionIf true, apply OM and size corrections before solving
negative_elements[out] Map of sample names to vectors of elements with negative values
Returns
CMBTimeSeriesSet containing contribution estimates for all valid samples
Note
Samples with negative values are skipped and recorded
Progress updates sent to rtw_ if available

Definition at line 3934 of file sourcesinkdata.cpp.

References CreateCorrectedDataset(), GetContributionVector(), GetElementInformation(), GetSampleSet(), InitializeParametersAndObservations(), NegativeValueCheck(), numberofsourcesamplesets_, rtw_, samplesetsorder_, ProgressWindow::SetLabel(), CMBTimeSeriesSet::SetLabel(), ProgressWindow::SetProgress(), SolveLevenberg_Marquardt(), and target_group_.

◆ LogLikelihood()

double SourceSinkData::LogLikelihood ( estimation_mode  est_mode = estimation_mode::elemental_profile_and_contribution)

Calculates the total log-likelihood for Bayesian source apportionment.

Computes the posterior log-likelihood by summing multiple components based on the estimation mode. Components include source data likelihood, observation likelihood (elements and isotopes), and contribution priors.

Parameters
est_modeEstimation mode determining which likelihood terms to include
Returns
Total log-likelihood (higher values indicate better model fit)

Definition at line 1456 of file sourcesinkdata.cpp.

References LogLikelihoodModelvsMeasured(), LogLikelihoodModelvsMeasured_Isotope(), LogLikelihoodSourceElementalDistributions(), LogPriorContributions(), only_contributions, and source_elemental_profiles_based_on_source_data.

Referenced by GetObjectiveFunctionValue(), Gradient(), and GradientUpdate().

◆ LogLikelihoodModelvsMeasured()

double SourceSinkData::LogLikelihoodModelvsMeasured ( estimation_mode  est_mode = estimation_mode::elemental_profile_and_contribution)
private

Calculates the log-likelihood of the model prediction versus measured data.

Compares the model's predicted elemental concentrations against the observed data for the selected target sample. Computed in log-space assuming log-normally distributed errors.

Formula: log(L) = -n*log(σ) - ||log(C_pred) - log(C_obs)||² / (2σ²)

Parameters
est_modeEstimation mode determining how predictions are made
Returns
Log-likelihood value (or -1e10 if any predicted concentration is non-positive)

Definition at line 1020 of file sourcesinkdata.cpp.

References based_on_fitted_distribution, direct, elemental_profile_and_contribution, error_stdev_, log, ObservedDataforSelectedSample(), PredictTarget(), and selected_target_sample_.

Referenced by LogLikelihood().

◆ LogLikelihoodModelvsMeasured_Isotope()

double SourceSinkData::LogLikelihoodModelvsMeasured_Isotope ( estimation_mode  est_mode = estimation_mode::elemental_profile_and_contribution)
private

Calculates the log-likelihood of model versus measured isotopic data.

Compares the model's predicted isotopic delta values against the observed isotopic data for the selected target sample. Operates in linear space assuming normally distributed errors in delta values.

Formula: log(L) = -n*log(σ_iso) - ||δ_pred - δ_obs||² / (2σ_iso²)

Parameters
est_modeEstimation mode determining how predictions are made
Returns
Log-likelihood value

Definition at line 1051 of file sourcesinkdata.cpp.

References based_on_fitted_distribution, direct, elemental_profile_and_contribution, error_stdev_isotope_, log, ObservedDataforSelectedSample_Isotope_delta(), PredictTarget_Isotope_delta(), and selected_target_sample_.

Referenced by LogLikelihood().

◆ LogLikelihoodSourceElementalDistributions()

double SourceSinkData::LogLikelihoodSourceElementalDistributions ( )
private

Calculates the log-likelihood of source elemental distributions.

Computes the total log-likelihood by evaluating how well each source sample's observed elemental concentrations fit their respective estimated distributions.

Returns
Sum of log-probabilities across all elements, all source groups, and all samples

Definition at line 961 of file sourcesinkdata.cpp.

References element_order_, Distribution::EvalLog(), Elemental_Profile_Set::GetElementDistribution(), ConcentrationSet::GetEstimatedDistribution(), GetSampleSet(), numberofsourcesamplesets_, and samplesetsorder_.

Referenced by LogLikelihood().

◆ LogPriorContributions()

double SourceSinkData::LogPriorContributions ( )
private

Calculates the log prior probability for source contributions.

Evaluates whether the current source contributions are physically valid by checking if all contributions are non-negative. Acts as a constraint in Bayesian inference.

Returns
-1e10 if any contribution is negative, 0 if all valid

Definition at line 953 of file sourcesinkdata.cpp.

References GetSourceContributions().

Referenced by LogLikelihood().

◆ LumpAllProfileSets()

Elemental_Profile_Set SourceSinkData::LumpAllProfileSets ( )
private

Combines all source samples into a single profile set.

Pools samples from all source groups into one unified Elemental_Profile_Set.

Returns
Elemental_Profile_Set containing all source samples combined
Note
Target group is excluded

Definition at line 3470 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfiles(), target_group_, and Elemental_Profile_Set::UpdateElementDistributions().

Referenced by ANOVA().

◆ MCMC()

Results SourceSinkData::MCMC ( const string &  target_sample,
map< string, string >  arguments,
CMCMC< SourceSinkData > *  mcmc,
ProgressWindow progress_window,
const string &  working_folder 
)

Performs Markov Chain Monte Carlo analysis for Bayesian source apportionment.

Conducts full Bayesian inference using MCMC sampling to estimate posterior distributions of source contributions and model parameters. Generates comprehensive uncertainty quantification including credible intervals, posterior distributions, and predicted concentrations.

Parameters
target_sampleName of target sample to apportion
argumentsMap of MCMC settings (number of samples, chains, burnin, etc.)
mcmcPointer to MCMC sampler object
progress_windowPointer to progress window for updates
working_folderBase directory for output files
Returns
Results object containing all MCMC outputs and credible intervals
Note
Burnin samples excluded from posterior statistics
Last contribution computed from sum constraint

Definition at line 4047 of file sourcesinkdata.cpp.

References Results::Append(), Results::AppendError(), CreateCorrectedDataset(), distribution, distribution_with_observed, element_information::element, ElementOrder(), GetElementInformation(), GetSourceOrder(), high, CMCMC< T >::initialize(), InitializeParametersAndObservations(), element_information::isotope, IsotopeOrder(), log, low, mcmc_samples, Range::mean, CMCMC< T >::Model, NegativeValueCheck(), normal, observation(), CMCMC< T >::predicted, rangeset, rangeset_with_observed, Range::Set(), Results::SetError(), Range::SetMean(), Range::SetMedian(), ResultItem::SetName(), Results::SetName(), CMBTimeSeriesSet::SetObservedValue(), ProgressWindow::SetProgress(), CMCMC< T >::SetProperty(), ResultItem::SetResult(), ResultItem::SetShowAsString(), ResultItem::SetShowTable(), ProgressWindow::SetTitle(), ResultItem::SetType(), Range::SetValue(), ResultItem::SetYAxisMode(), ProgressWindow::SetYAxisTitle(), ResultItem::SetYLimit(), SourceGroupNames(), CMCMC< T >::step(), and Observation::Value().

Referenced by Conductor::ExecuteCMBBayesian(), and MCMC_Batch().

◆ MCMC_Batch()

CMBMatrix SourceSinkData::MCMC_Batch ( map< string, string >  arguments,
CMCMC< SourceSinkData > *  mcmc,
ProgressWindow progress_window,
const string &  working_folder 
)

Performs batch MCMC analysis on all target samples.

Conducts full Bayesian MCMC analysis for every sample in the target group, generating comprehensive results for each sample and summarizing credible intervals in a matrix.

Output matrix structure:

  • Rows: Target samples
  • Columns (4 per source): [source]_low, [source]_high, [source]_median, [source]_mean
Parameters
argumentsMap of MCMC settings
mcmcPointer to MCMC sampler object
progress_windowPointer to progress window for updates
working_folderBase directory for output folders
Returns
CMBMatrix containing credible interval statistics for all samples
Note
Creates subdirectory for each target sample
All ResultItems saved as text files

Definition at line 4314 of file sourcesinkdata.cpp.

References ProgressWindow::ClearGraph(), Range::Get(), high, InitializeParametersAndObservations(), low, MCMC(), Range::Mean(), Range::Median(), numberofsourcesamplesets_, samplesetsorder_, CMBMatrix::SetColumnLabel(), ProgressWindow::SetLabel(), ProgressWindow::SetProgress2(), CMBMatrix::SetRowLabel(), and target_group_.

◆ MeanElementalContent() [1/2]

CMBVector SourceSinkData::MeanElementalContent ( )
private

Computes weighted mean elemental concentrations across all sources.

Calculates the overall mean concentration for each element, weighted by the number of samples in each source group.

Formula: μ_overall = Σ(n_i × μ_i) / Σ(n_i)

Returns
CMBVector of weighted mean concentrations, labeled with element names
Note
Target group excluded
Weighting ensures larger groups have proportional influence

Definition at line 4744 of file sourcesinkdata.cpp.

References element_order_, GetElementNames(), MeanElementalContent(), CMBVector::SetLabels(), and target_group_.

Referenced by BetweenGroupCovarianceMatrix(), MeanElementalContent(), and TotalScatterMatrix().

◆ MeanElementalContent() [2/2]

CMBVector SourceSinkData::MeanElementalContent ( const string &  group_name)
private

Computes mean elemental concentrations for a specific group.

Calculates the mean concentration for each element within a specified source or target group.

Parameters
group_nameName of the group (source or target)
Returns
CMBVector of mean concentrations, labeled with element names
Note
Returns empty vector if group doesn't exist

Definition at line 4728 of file sourcesinkdata.cpp.

References GetElementNames(), and CMBVector::SetLabels().

◆ NegativeValueCheck()

vector< string > SourceSinkData::NegativeValueCheck ( )

Checks for zero or negative concentration values across all sources.

Scans all source groups for elements with zero or negative concentrations, which are problematic for log-normal distributions and certain statistical analyses. Returns detailed error messages identifying problematic elements and their source groups.

Returns
Vector of error messages describing zero/negative values found
Note
Returns empty vector if no issues found
Only checks source groups (target excluded)

Definition at line 3402 of file sourcesinkdata.cpp.

References element_order_, and PopulateConstituentOrders().

Referenced by Conductor::CheckNegativeElements(), LM_Batch(), MCMC(), and VerifySource().

◆ observation()

Observation * SourceSinkData::observation ( size_t  i)

Retrieves pointer to an observation by index.

Parameters
iObservation index (0-based)
Returns
Pointer to Observation, or nullptr if invalid index

Definition at line 5008 of file sourcesinkdata.cpp.

References observations_.

Referenced by GetPredictedValues(), MCMC(), PredictTarget(), and PredictTarget_Isotope_delta().

◆ ObservationsCount()

size_t SourceSinkData::ObservationsCount ( )

Returns the number of observations.

Returns
Number of observations (measured values)

Definition at line 4987 of file sourcesinkdata.cpp.

References observations_.

Referenced by GetPredictedValues().

◆ ObservedDataforSelectedSample()

CVector SourceSinkData::ObservedDataforSelectedSample ( const string &  SelectedTargetSample = "")
private

Retrieves the observed elemental data for a selected target sample.

Extracts the elemental concentration values for a specific target sample, returning them in the order specified by element_order_.

Parameters
SelectedTargetSampleName of the target sample (empty = use selected_target_sample_)
Returns
CVector containing elemental concentration values

Definition at line 981 of file sourcesinkdata.cpp.

References element_order_, Elemental_Profile_Set::GetProfile(), GetSampleSet(), GetTargetGroup(), Elemental_Profile::GetValue(), selected_target_sample_, and SelectedTargetSample().

Referenced by GetObservedElementalProfile(), LogLikelihoodModelvsMeasured(), ResidualVector(), and ResidualVector_arma().

◆ ObservedDataforSelectedSample_Isotope()

CVector SourceSinkData::ObservedDataforSelectedSample_Isotope ( const string &  SelectedTargetSample = "")
private

Retrieves the observed isotopic data for a selected target sample.

Extracts and converts isotopic ratio values for a specific target sample into absolute concentrations using the delta notation formula: concentration = (δ/1000 + 1) × standard_ratio × base_element_concentration

Parameters
SelectedTargetSampleName of the target sample (empty = use selected_target_sample_)
Returns
CVector containing converted isotopic concentration values

Definition at line 993 of file sourcesinkdata.cpp.

References element_information_, Elemental_Profile_Set::GetProfile(), GetSampleSet(), GetTargetGroup(), Elemental_Profile::GetValue(), isotope_order_, selected_target_sample_, and SelectedTargetSample().

◆ ObservedDataforSelectedSample_Isotope_delta()

CVector SourceSinkData::ObservedDataforSelectedSample_Isotope_delta ( const string &  SelectedTargetSample = "")
private

Retrieves the observed isotopic data in delta notation.

Extracts isotopic ratio values for a specific target sample in their original delta notation (‰) format, without conversion to absolute concentrations.

Parameters
SelectedTargetSampleName of the target sample (empty = use selected_target_sample_)
Returns
CVector containing isotopic delta values (‰)

Definition at line 1006 of file sourcesinkdata.cpp.

References element_information_, Elemental_Profile_Set::GetProfile(), GetSampleSet(), GetTargetGroup(), Elemental_Profile::GetValue(), isotope_order_, selected_target_sample_, and SelectedTargetSample().

Referenced by GetObservedElementalProfile_Isotope(), LogLikelihoodModelvsMeasured_Isotope(), ResidualVector(), and ResidualVector_arma().

◆ OMandSizeConstituents()

vector< string > SourceSinkData::OMandSizeConstituents ( )

Retrieves the names of OM and particle size constituents.

Returns a vector containing the names of the organic matter and particle size constituents set via PerformRegressionVsOMAndSize().

Returns
Vector with [0]=OM constituent name, [1]=size constituent name

Definition at line 5131 of file sourcesinkdata.cpp.

References omconstituent_, and sizeconsituent_.

Referenced by Conductor::ExecuteANOVA(), Conductor::ExecuteBracketingAnalysisBatch(), Conductor::ExecuteDistributionFitting(), Conductor::ExecuteEDP(), Conductor::ExecuteEDPM(), Conductor::ExecuteSDFA(), Conductor::ExecuteSDFAM(), Conductor::ExecuteSDFAOnevsRest(), and MainWindow::onOMSizeCorrection().

◆ OneStepLevenberg_Marquardt()

CVector SourceSinkData::OneStepLevenberg_Marquardt ( double  lambda)
private

Performs one iteration of the Levenberg-Marquardt optimization algorithm.

Computes the parameter update step for source contributions using the Levenberg-Marquardt algorithm, which interpolates between Gauss-Newton and gradient descent methods.

The algorithm solves: (J^T J + λ diag(J^T J)) dx = -J^T r

Parameters
lambdaDamping parameter controlling trade-off (typical: 0.001 to 1000)
Returns
CVector parameter update vector dx of size (n-1)
Note
Uses standard contribution parameterization (last source implicit)

Definition at line 1238 of file sourcesinkdata.cpp.

References ResidualJacobian(), and ResidualVector().

Referenced by SolveLevenberg_Marquardt().

◆ OneStepLevenberg_Marquardt_softmax()

CVector SourceSinkData::OneStepLevenberg_Marquardt_softmax ( double  lambda)
private

Performs one iteration of Levenberg-Marquardt using softmax parameterization.

Computes the parameter update step for softmax-parameterized source contributions.

Parameters
lambdaDamping parameter
Returns
CVector parameter update vector dx of size n
Note
Uses softmax parameterization where all n sources are independent

Definition at line 1268 of file sourcesinkdata.cpp.

References ResidualJacobian_softmax(), and ResidualVector().

Referenced by SolveLevenberg_Marquardt().

◆ operator=()

SourceSinkData & SourceSinkData::operator= ( const SourceSinkData other)

Assignment operator.

Assigns all data from another SourceSinkData object to this one. Performs deep copy of all member variables.

Parameters
otherThe SourceSinkData object to assign from
Returns
Reference to this object

Definition at line 74 of file sourcesinkdata.cpp.

References constituent_order_, distance_coeff_, element_distributions_, element_information_, element_order_, isotope_order_, numberofconstituents_, numberofisotopes_, numberofsourcesamplesets_, observations_, omconstituent_, options_, outputpath_, parameter_estimation_mode_, parameters_, regression_p_value_threshold_, samplesetsorder_, selected_target_sample_, size_om_order_, sizeconsituent_, target_group_, and tools_used_.

◆ OptimalBoxCoxParameters()

CMBVector SourceSinkData::OptimalBoxCoxParameters ( )
private

Computes optimal Box-Cox transformation parameters for all elements.

Determines the optimal λ (lambda) parameter for each element's Box-Cox transformation by maximizing the log-likelihood of achieving normality.

Box-Cox transformation: y = (x^λ - 1) / λ (or ln(x) if λ = 0)

Special cases:

  • λ = 1: No transformation (linear)
  • λ = 0.5: Square root transformation
  • λ = 0: Log transformation
  • λ = -1: Reciprocal transformation
Returns
CMBVector of optimal λ parameters, labeled with element names
Note
Search range: λ ∈ [-5, 5]
Optimization iterations: 10

Definition at line 3183 of file sourcesinkdata.cpp.

References ExtractConcentrationSet(), GetElementNames(), and CMBVector::SetLabels().

Referenced by BoxCoxTransformed().

◆ OptionsToJsonObject()

QJsonObject SourceSinkData::OptionsToJsonObject ( ) const

Exports analysis options/settings to a JSON object.

Serializes all analysis configuration options (numerical parameters, thresholds, flags) as key-value pairs.

Returns
QJsonObject containing option names and values

Definition at line 2593 of file sourcesinkdata.cpp.

References options_.

Referenced by MainWindow::buildProjectJson().

◆ OutlierAnalysisForAll()

void SourceSinkData::OutlierAnalysisForAll ( const double &  lower_threshold = -3,
const double &  upper_threshold = 3 
)

Performs outlier detection on all source groups.

Applies Box-Cox transformation and identifies outliers based on standardized residuals. Samples with standardized values outside the threshold range are flagged as outliers in their notes.

Detection method:

  1. Box-Cox transform each element's distribution
  2. Calculate z-scores: z = (x_transformed - μ) / σ
  3. Flag outliers: z < lower_threshold OR z > upper_threshold
Parameters
lower_thresholdLower bound for standardized values (e.g., -3.0)
upper_thresholdUpper bound for standardized values (e.g., +3.0)
Note
Only analyzes source groups (target group excluded)
Outliers are flagged in sample notes, not removed
Uses Box-Cox transformation for normalization

Definition at line 2801 of file sourcesinkdata.cpp.

References target_group_.

Referenced by MainWindow::onIncludeExcludeSample().

◆ parameter() [1/2]

Parameter * SourceSinkData::parameter ( size_t  i)

Retrieves pointer to a parameter by index.

Parameters
iParameter index (0-based)
Returns
Pointer to Parameter, or nullptr if invalid index

Definition at line 4992 of file sourcesinkdata.cpp.

References parameters_.

Referenced by GetParameterName(), and GetSourceContributions().

◆ parameter() [2/2]

const Parameter * SourceSinkData::parameter ( size_t  i) const

Retrieves const pointer to a parameter by index.

Parameters
iParameter index (0-based)
Returns
Const pointer to Parameter, or nullptr if invalid index

Definition at line 5000 of file sourcesinkdata.cpp.

References parameters_.

◆ ParameterEstimationMode()

estimation_mode SourceSinkData::ParameterEstimationMode ( )

Retrieves the current estimation mode.

Returns
Current estimation mode setting

Definition at line 5032 of file sourcesinkdata.cpp.

References parameter_estimation_mode_.

◆ Parameters()

vector< Parameter > & SourceSinkData::Parameters ( )

Retrieves reference to the parameters vector.

Returns
Reference to parameters vector

Definition at line 4977 of file sourcesinkdata.cpp.

References parameters_.

◆ ParametersCount()

size_t SourceSinkData::ParametersCount ( )

Returns the number of parameters.

Returns
Number of parameters in the optimization

Definition at line 4982 of file sourcesinkdata.cpp.

References parameters_.

◆ PerformRegressionVsOMAndSize()

bool SourceSinkData::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.

Computes regression models for all sample groups to quantify how elemental concentrations vary with organic matter (OM) content and particle size. These models are used to correct elemental profiles for OM/size variations.

Regression forms:

  • Linear: C_corrected = C + β₁(OM_ref - OM) + β₂(Size_ref - Size)
  • Multiplicative: C_corrected = C × (OM_ref/OM)^β₁ × (Size_ref/Size)^β₂
Parameters
omName of the organic matter constituent (e.g., "OC", "OM")
particle_sizeName of the particle size constituent (e.g., "D50", "PM2.5")
formRegression form (linear or multiplicative)
p_value_thresholdSignificance threshold for including predictors (default: 0.05)
Returns
true if regressions were computed successfully
Note
Stores OM and size constituent names for later correction
Regressions are computed for all groups (sources and target)
Predictors with p > threshold are excluded from the model
See also
GetMLRResults() to retrieve regression results

Definition at line 2781 of file sourcesinkdata.cpp.

References omconstituent_, regression_p_value_threshold_, and sizeconsituent_.

Referenced by Conductor::ExecuteMLR().

◆ PopulateConstituentOrders()

void SourceSinkData::PopulateConstituentOrders ( )

Populates all element ordering vectors used throughout CMB analysis.

Scans the element information map and organizes elements into separate ordering vectors based on their roles. These vectors define the order in which elements appear in matrices, parameter vectors, and observations.

Populated Vectors:

  • constituent_order_: All species in the dataset
  • element_order_: Chemical elements flagged for analysis
  • isotope_order_: Isotopes flagged for analysis
  • size_om_order_: Particle size and organic carbon parameters
Note
Must be called before InitializeParametersAndObservations()

Definition at line 2108 of file sourcesinkdata.cpp.

References constituent_order_, element_information::element, element_information_, element_order_, element_information::isotope, isotope_order_, numberofconstituents_, element_information::organic_carbon, element_information::particle_size, and size_om_order_.

Referenced by InitializeParametersAndObservations(), and NegativeValueCheck().

◆ PopulateElementDistributions()

void SourceSinkData::PopulateElementDistributions ( )

Populate element distributions from all groups.

Builds concentration distributions for each element by collecting all concentration values across all groups (sources and target). First updates distributions within each group, then aggregates them into the overall element_distributions_ map.

Note
Should be called after loading data or modifying profiles

Definition at line 521 of file sourcesinkdata.cpp.

References element_distributions_, and GetElementNames().

Referenced by BoxCoxTransformed(), CreateCorrectedAndFilteredDataset(), CreateCorrectedDataset(), ExtractChemicalElements(), ExtractSpecificElements(), MainWindow::LoadModel(), RandomlyEliminateSourceSamples(), MainWindow::ReadExcel(), and ReplaceSourceAsTarget().

◆ PopulateElementInformation()

void SourceSinkData::PopulateElementInformation ( const map< string, element_information > *  ElementInfo = nullptr)

Populate element information metadata.

Initializes or updates the element_information_ map with metadata for all elements in the dataset. If ElementInfo is provided, copies metadata from it; otherwise initializes with default values.

Also updates the count of source sample sets (total groups minus target group if present).

Parameters
ElementInfoOptional source of element metadata (nullptr for defaults)

Definition at line 605 of file sourcesinkdata.cpp.

References element_information_, GetElementNames(), numberofsourcesamplesets_, and target_group_.

Referenced by CreateCorrectedAndFilteredDataset(), DiscriminantFunctionAnalysis(), DiscriminantFunctionAnalysis(), ExtractChemicalElements(), ExtractSpecificElements(), RandomlyEliminateSourceSamples(), MainWindow::ReadExcel(), and ReplaceSourceAsTarget().

◆ PredictTarget()

CVector SourceSinkData::PredictTarget ( parameter_mode  param_mode = parameter_mode::direct)
private

Predicts target sample elemental concentrations based on source contributions.

Calculates the predicted elemental composition of the target sample as a linear combination of source profiles weighted by their contributions: C_predicted = Σ (source_mean_i × contribution_i)

Parameters
param_modeParameter mode for obtaining source mean values
Returns
CVector of predicted elemental concentrations

Definition at line 1403 of file sourcesinkdata.cpp.

References BuildSourceMeanMatrix(), element_order_, GetContributionVector(), observation(), and Observation::SetPredictedValue().

Referenced by GetPredictedElementalProfile(), LogLikelihoodModelvsMeasured(), ResidualVector(), and ResidualVector_arma().

◆ PredictTarget_Isotope()

CVector SourceSinkData::PredictTarget_Isotope ( parameter_mode  param_mode = parameter_mode::direct)
private

Predicts target sample isotopic compositions based on source contributions.

Calculates the predicted isotopic composition (as absolute concentrations) of the target sample as a linear combination of source isotopic profiles.

Parameters
param_modeParameter mode for obtaining source mean values
Returns
CVector of predicted isotopic concentrations (absolute values)

Definition at line 1419 of file sourcesinkdata.cpp.

References BuildSourceMeanMatrix_Isotopes(), and GetContributionVector().

◆ PredictTarget_Isotope_delta()

CVector SourceSinkData::PredictTarget_Isotope_delta ( parameter_mode  param_mode = parameter_mode::based_on_fitted_distribution)
private

Predicts target sample isotopic compositions in delta notation.

Calculates the predicted isotopic composition in delta notation (‰) by first computing absolute concentrations, then converting back to delta values.

Parameters
param_modeParameter mode for obtaining source mean values
Returns
CVector of predicted isotopic delta values (‰)

Definition at line 1429 of file sourcesinkdata.cpp.

References BuildSourceMeanMatrix(), BuildSourceMeanMatrix_Isotopes(), element_information_, element_order_, GetContributionVector(), isotope_order_, numberofisotopes_, observation(), and Observation::SetPredictedValue().

Referenced by GetPredictedElementalProfile_Isotope(), LogLikelihoodModelvsMeasured_Isotope(), ResidualVector(), and ResidualVector_arma().

◆ RandomlyEliminateSourceSamples()

SourceSinkData SourceSinkData::RandomlyEliminateSourceSamples ( const double &  percentage)
private

Creates dataset with randomly excluded source samples for validation.

Generates a new dataset with a specified percentage of source samples randomly removed. Useful for bootstrap validation and uncertainty analysis.

Parameters
percentagePercentage of samples to exclude (0-100)
Returns
New SourceSinkData object with reduced source samples
Note
Target group samples are preserved
Element distributions are recalculated

Definition at line 3623 of file sourcesinkdata.cpp.

References AssignAllDistributions(), element_information_, omconstituent_, PopulateElementDistributions(), PopulateElementInformation(), RandomlypickSamples(), sizeconsituent_, and target_group_.

Referenced by BootStrap(), and BootStrap().

◆ RandomlypickSamples()

vector< string > SourceSinkData::RandomlypickSamples ( const double &  percentage) const
private

Randomly selects a subset of source samples.

Performs Bernoulli sampling on all source samples, where each sample is independently included with the specified probability.

Parameters
percentageProbability of selecting each sample (0.0 to 1.0)
Returns
Vector of randomly selected sample names
Note
Expected number of samples: N × percentage
Each sample is selected independently

Definition at line 4025 of file sourcesinkdata.cpp.

References AllSourceSampleNames(), and GADistribution::GetRndUniF().

Referenced by RandomlyEliminateSourceSamples().

◆ ReadElementDatafromJsonObject()

bool SourceSinkData::ReadElementDatafromJsonObject ( const QJsonObject &  jsonobject)

Deserializes elemental profile data from a JSON object.

Loads all sample groups and their elemental profiles from JSON format. Clears existing data before loading.

Parameters
jsonobjectJSON object containing elemental profile sets
Returns
true if successfully loaded
Note
Clears all existing data before loading

Definition at line 2646 of file sourcesinkdata.cpp.

References elemental_profile_set, and Elemental_Profile_Set::ReadFromJsonObject().

Referenced by ReadFromFile().

◆ ReadElementInformationfromJsonObject()

bool SourceSinkData::ReadElementInformationfromJsonObject ( const QJsonObject &  jsonobject)

Deserializes element information metadata from a JSON object.

Loads element roles, standard ratios, base elements, and inclusion flags from JSON format. Clears existing element information before loading.

Parameters
jsonobjectJSON object containing element metadata
Returns
true if successfully loaded
Note
Clears element_information_ before loading

Definition at line 2626 of file sourcesinkdata.cpp.

References element_information::base_element, element_information_, element_information::include_in_analysis, element_information::Role, Role(), and element_information::standard_ratio.

Referenced by ReadFromFile().

◆ ReadFromFile()

bool SourceSinkData::ReadFromFile ( QFile *  fil)

Loads complete dataset from a JSON file.

Deserializes all dataset components from a JSON file: elemental profiles, element information, tools used, options, and target group designation. Clears existing data before loading.

Parameters
filPointer to an open QFile for reading
Returns
true if successfully loaded
Note
Clears all existing data before loading

Definition at line 2708 of file sourcesinkdata.cpp.

References Clear(), ReadElementDatafromJsonObject(), ReadElementInformationfromJsonObject(), ReadOptionsfromJsonObject(), ReadToolsUsedFromJsonObject(), and target_group_.

Referenced by MainWindow::LoadModel().

◆ ReadOptionsfromJsonObject()

bool SourceSinkData::ReadOptionsfromJsonObject ( const QJsonObject &  jsonobject)

Deserializes analysis options from a JSON object.

Loads configuration options and settings from JSON format.

Parameters
jsonobjectJSON object containing option key-value pairs
Returns
true if successfully loaded

Definition at line 2662 of file sourcesinkdata.cpp.

References options_.

Referenced by ReadFromFile().

◆ ReadToolsUsedFromJsonObject()

bool SourceSinkData::ReadToolsUsedFromJsonObject ( const QJsonArray &  jsonarray)

Deserializes the list of analysis tools from a JSON array.

Parameters
jsonarrayJSON array containing tool names
Returns
true if successfully loaded

Definition at line 2615 of file sourcesinkdata.cpp.

References AddtoToolsUsed().

Referenced by ReadFromFile().

◆ ReplaceSourceAsTarget()

SourceSinkData SourceSinkData::ReplaceSourceAsTarget ( const string &  source_sample_name) const
private

Creates a new dataset with a source sample designated as the target.

Generates a modified dataset where a specified source sample becomes the new target sample. Useful for leave-one-out validation.

Parameters
source_sample_nameName of the source sample to use as new target
Returns
New SourceSinkData object with specified sample as target
Note
Source sample is copied to target group (not moved)

Definition at line 3673 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), AssignAllDistributions(), element_information_, omconstituent_, PopulateElementDistributions(), PopulateElementInformation(), Sample(), sizeconsituent_, and target_group_.

Referenced by VerifySource().

◆ ResidualJacobian()

CMatrix SourceSinkData::ResidualJacobian ( )
private

Calculates the Jacobian matrix of residuals with respect to contributions.

Computes the numerical derivative of the residual vector with respect to the first (n-1) source contributions using finite differences.

Returns
CMatrix Jacobian matrix
Note
Uses adaptive epsilon based on distance from contribution = 0.5

Definition at line 1172 of file sourcesinkdata.cpp.

References element_order_, GetContributionVector(), GetSourceOrder(), isotope_order_, ResidualVector(), and SetContribution().

Referenced by OneStepLevenberg_Marquardt().

◆ ResidualJacobian_arma()

CMatrix_arma SourceSinkData::ResidualJacobian_arma ( )
private

Calculates the Jacobian matrix of residuals with respect to contributions (Armadillo)

Computes the numerical derivative of the residual vector with respect to the first (n-1) source contributions using finite differences.

The Jacobian matrix J has dimensions [(n-1) sources × (elements + isotopes)], where J[i,j] = ∂residual_j / ∂contribution_i

Returns
CMatrix_arma Jacobian matrix in Armadillo format
Note
Uses adaptive epsilon based on distance from contribution = 0.5

Definition at line 1140 of file sourcesinkdata.cpp.

References element_order_, GetContributionVector(), GetSourceOrder(), isotope_order_, ResidualVector_arma(), and SetContribution().

◆ ResidualJacobian_softmax()

CMatrix SourceSinkData::ResidualJacobian_softmax ( )
private

Calculates the Jacobian using softmax parameterization of contributions.

Computes the numerical derivative of residuals with respect to unconstrained softmax parameters. Includes all n sources since softmax transformation ensures contributions sum to 1 automatically.

Returns
CMatrix Jacobian matrix (n sources × m observations)
Note
Uses sign-dependent epsilon for better numerical behavior

Definition at line 1204 of file sourcesinkdata.cpp.

References element_order_, GetContributionVectorSoftmax(), GetSourceOrder(), isotope_order_, ResidualVector(), and SetContributionSoftmax().

Referenced by OneStepLevenberg_Marquardt_softmax().

◆ ResidualVector()

CVector SourceSinkData::ResidualVector ( )
private

Calculates the combined residual vector for elemental and isotopic predictions.

Computes residuals between predicted and observed values for both elemental concentrations (in log-space) and isotopic delta values (in linear space).

Combined residual vector structure: [log(C_pred/C_obs) for each element, δ_pred - δ_obs for each isotope]

Returns
CVector of combined residuals
Note
Returns vector with non-finite values if predictions are invalid

Definition at line 1077 of file sourcesinkdata.cpp.

References direct, ObservedDataforSelectedSample(), ObservedDataforSelectedSample_Isotope_delta(), PredictTarget(), PredictTarget_Isotope_delta(), and selected_target_sample_.

Referenced by OneStepLevenberg_Marquardt(), OneStepLevenberg_Marquardt_softmax(), ResidualJacobian(), ResidualJacobian_softmax(), and SolveLevenberg_Marquardt().

◆ ResidualVector_arma()

CVector_arma SourceSinkData::ResidualVector_arma ( )
private

Calculates the combined residual vector using Armadillo vector format.

Armadillo-based implementation of residual calculation for compatibility with linear algebra operations and optimization routines that use Armadillo types.

Returns
CVector_arma of combined residuals in Armadillo format

Definition at line 1115 of file sourcesinkdata.cpp.

References ObservedDataforSelectedSample(), ObservedDataforSelectedSample_Isotope_delta(), PredictTarget(), PredictTarget_Isotope_delta(), and selected_target_sample_.

Referenced by ResidualJacobian_arma().

◆ Role() [1/2]

QString SourceSinkData::Role ( const element_information::role role) const
private

Converts element role enum to string representation.

Converts the element_information::role enumeration to a human-readable string for serialization, display, or file output.

Mappings:

  • do_not_include → "DoNotInclude"
  • element → "Element"
  • isotope → "Isotope"
  • particle_size → "ParticleSize"
  • organic_carbon → "OM"
Parameters
roleElement role enumeration value
Returns
QString representation of the role
Note
Returns "DoNotInclude" for unrecognized values

Definition at line 2745 of file sourcesinkdata.cpp.

References element_information::do_not_include, element_information::element, element_information::isotope, element_information::organic_carbon, and element_information::particle_size.

Referenced by AssignAllDistributions(), ElementInformationToJsonObject(), and ReadElementInformationfromJsonObject().

◆ Role() [2/2]

element_information::role SourceSinkData::Role ( const QString &  role_string) const
private

Converts string representation to element role enum.

Parses a string and returns the corresponding element_information::role enumeration for deserialization or configuration loading.

Mappings:

  • "DoNotInclude" → do_not_include
  • "Element" → element
  • "Isotope" → isotope
  • "ParticleSize" → particle_size
  • "OM" → organic_carbon
Parameters
role_stringQString representation of the role
Returns
element_information::role enumeration value
Note
Returns do_not_include for unrecognized strings

Definition at line 2763 of file sourcesinkdata.cpp.

References element_information::do_not_include, element_information::element, element_information::isotope, element_information::organic_carbon, and element_information::particle_size.

◆ Sample()

Elemental_Profile SourceSinkData::Sample ( const string &  sample_name) const

Retrieves an elemental profile by sample name.

Searches all groups (sources and target) for a sample with the specified name and returns its elemental profile. Returns empty profile if not found.

Parameters
sample_nameName of the sample to retrieve
Returns
Elemental_Profile for the sample, or empty profile if not found
Note
Searches all groups sequentially
Returns copy of profile, not reference
If multiple samples have the same name, returns first match

Definition at line 3659 of file sourcesinkdata.cpp.

Referenced by ReplaceSourceAsTarget().

◆ SamplesetsOrder()

vector< string > SourceSinkData::SamplesetsOrder ( )
private

Retrieves the ordering of sample sets.

Returns
Vector of sample set names

Definition at line 5085 of file sourcesinkdata.cpp.

References samplesetsorder_.

◆ SelectedTargetSample()

string SourceSinkData::SelectedTargetSample ( ) const

Retrieves the name of the currently selected target sample.

Returns
Name of the target sample being analyzed

Definition at line 5174 of file sourcesinkdata.cpp.

References selected_target_sample_.

Referenced by ObservedDataforSelectedSample(), ObservedDataforSelectedSample_Isotope(), and ObservedDataforSelectedSample_Isotope_delta().

◆ SetContribution() [1/2]

void SourceSinkData::SetContribution ( const CVector &  contributions)
private

Sets all source contributions from a vector.

Updates contributions for multiple sources. If the vector has n-1 elements, the last contribution is computed automatically.

Parameters
contributionsVector of contribution values
Note
Validates that all contributions are non-negative

Definition at line 1646 of file sourcesinkdata.cpp.

References SetContribution().

◆ SetContribution() [2/2]

void SourceSinkData::SetContribution ( size_t  source_index,
double  contribution_value 
)
private

Sets a single source contribution value.

Updates the contribution fraction for the specified source and automatically recalculates the last source's contribution to maintain the sum constraint.

Parameters
source_indexIndex of the source to update (0-based)
contribution_valueNew contribution fraction (must satisfy 0 ≤ f ≤ 1)
Note
Last contribution is automatically updated: f_n = 1 - Σ(f_1...f_{n-1})

Definition at line 1622 of file sourcesinkdata.cpp.

References GetContributionVector(), GetSampleSet(), samplesetsorder_, and Elemental_Profile_Set::SetContribution().

Referenced by InitializeContributionsRandomly(), ResidualJacobian(), ResidualJacobian_arma(), SetContribution(), SetContributionSoftmax(), and SolveLevenberg_Marquardt().

◆ SetContributionSoftmax() [1/2]

void SourceSinkData::SetContributionSoftmax ( const CVector &  softmax_params)
private

Sets all source contributions using softmax transformation.

Applies the softmax transformation to convert unconstrained parameters to valid contribution fractions: f_i = exp(x_i) / Σ exp(x_j)

Parameters
softmax_paramsVector of unconstrained softmax parameters
Note
This is the correct way to update contributions in softmax mode

Definition at line 1661 of file sourcesinkdata.cpp.

References contribution, GetContributionVector(), SetContribution(), and SetContributionSoftmax().

◆ SetContributionSoftmax() [2/2]

void SourceSinkData::SetContributionSoftmax ( size_t  source_index,
double  softmax_value 
)
private

Sets a single softmax parameter value.

Updates the unconstrained softmax parameter for the specified source. Does NOT automatically update the actual contribution fractions.

Parameters
source_indexIndex of the source to update (0-based)
softmax_valueNew softmax parameter (unbounded: x ∈ ℝ)
Note
This only updates the softmax parameter, not the contribution

Definition at line 1639 of file sourcesinkdata.cpp.

References GetSampleSet(), samplesetsorder_, and Elemental_Profile_Set::SetContributionSoftmax().

Referenced by InitializeContributionsRandomlySoftmax(), ResidualJacobian_softmax(), SetContributionSoftmax(), and SolveLevenberg_Marquardt().

◆ SetOMandSizeConstituents() [1/2]

void SourceSinkData::SetOMandSizeConstituents ( const string &  _omconstituent,
const string &  _sizeconsituent 
)

Sets the names of OM and particle size constituents.

Parameters
_omconstituentName of organic matter constituent
_sizeconsituentName of particle size constituent

Definition at line 5112 of file sourcesinkdata.cpp.

References omconstituent_, and sizeconsituent_.

Referenced by Conductor::ExecuteMLR(), and MainWindow::LoadModel().

◆ SetOMandSizeConstituents() [2/2]

void SourceSinkData::SetOMandSizeConstituents ( const vector< string > &  _omsizeconstituents)

Sets the names of OM and particle size constituents from a vector.

Parameters
_omsizeconstituentsVector with [0]=OM name, [1]=size name

Definition at line 5118 of file sourcesinkdata.cpp.

References omconstituent_, and sizeconsituent_.

◆ SetOutputPath()

bool SourceSinkData::SetOutputPath ( const string &  output_path)

Set the output directory path.

Specifies the directory where analysis results and output files should be saved.

Parameters
output_pathPath to output directory
Returns
Always returns true

Definition at line 5153 of file sourcesinkdata.cpp.

References outputpath_.

◆ SetParameterEstimationMode()

void SourceSinkData::SetParameterEstimationMode ( estimation_mode  est_mode)

Sets the estimation mode for parameter optimization.

Specifies which parameters will be optimized during inference:

  • only_contributions: Estimate only source contributions (fixed source profiles)
  • elemental_profile_and_contribution: Estimate both contributions and source profiles
  • source_elemental_profiles_based_on_source_data: Estimate only source profiles
Parameters
est_modeEstimation mode to use

Definition at line 5027 of file sourcesinkdata.cpp.

References parameter_estimation_mode_.

Referenced by Conductor::ExecuteGA_FixedProfile(), and Conductor::ExecuteGA_NoTargets().

◆ SetParameterValue() [1/2]

bool SourceSinkData::SetParameterValue ( const CVector &  values)
private

Sets multiple parameter values from a vector.

Updates all parameters using values from the provided vector. Each parameter update triggers synchronization with the corresponding model component.

Parameters
valuesVector containing new parameter values
Returns
true if all parameters were successfully updated, false if any update failed
Note
Updates are applied sequentially; partial updates possible if one fails

Definition at line 1934 of file sourcesinkdata.cpp.

References SetParameterValue().

◆ SetParameterValue() [2/2]

bool SourceSinkData::SetParameterValue ( size_t  index,
double  value 
)

Sets a parameter value and updates corresponding model components.

Updates a parameter in the parameter vector and synchronizes the change with the appropriate model component (contributions, distribution parameters, or error terms). The parameter vector layout depends on the estimation mode.

Parameter Vector Layout (full mode: elemental_profile_and_contribution): [0 to n-2]: Contribution parameters (n-1 sources) [n-1 to end of element μ]: Element μ parameters [element μ to end of isotope μ]: Isotope μ parameters [isotope μ to end of element σ]: Element σ parameters [element σ to end of isotope σ]: Isotope σ parameters [end-1]: Error std dev for elements [end]: Error std dev for isotopes

Parameters
indexParameter index in the parameters_ vector
valueNew parameter value
Returns
true if parameter was successfully updated, false if index is invalid
Note
Automatically updates last contribution to maintain sum constraint
Validates that standard deviations are non-negative

Definition at line 1773 of file sourcesinkdata.cpp.

References element_order_, elemental_profile_and_contribution, error_stdev_, error_stdev_isotope_, GetContributionVector(), GetElementDistribution(), GetSampleSet(), isotope_order_, numberofconstituents_, numberofisotopes_, numberofsourcesamplesets_, only_contributions, parameter_estimation_mode_, parameters_, samplesetsorder_, Elemental_Profile_Set::SetContribution(), ConcentrationSet::SetEstimatedMu(), ConcentrationSet::SetEstimatedSigma(), and source_elemental_profiles_based_on_source_data.

Referenced by Gradient(), GradientUpdate(), and SetParameterValue().

◆ SetProgressWindow()

void SourceSinkData::SetProgressWindow ( ProgressWindow _rtw)

Sets the progress window for displaying optimization progress.

Assigns a progress window that will receive updates during long-running operations like MCMC sampling, bootstrap analysis, or batch processing.

Parameters
_rtwPointer to ProgressWindow object (nullptr to disable progress display)

Definition at line 5037 of file sourcesinkdata.cpp.

References rtw_.

Referenced by Conductor::ExecuteDFA(), Conductor::ExecuteDFAM(), Conductor::ExecuteDFAOnevsRest(), Conductor::ExecuteErrorAnalysis(), Conductor::ExecuteLevenbergMarquardt(), Conductor::ExecuteLevenbergMarquardtBatch(), Conductor::ExecuteSDFA(), Conductor::ExecuteSDFAM(), Conductor::ExecuteSDFAOnevsRest(), Conductor::ExecuteSourceVerify(), and VerifySource().

◆ SetSelectedTargetSample()

bool SourceSinkData::SetSelectedTargetSample ( const string &  sample_name)

Sets the currently selected target sample for analysis.

Specifies which sample from the target group will be used as the receptor in CMB calculations. Validates that the sample exists before setting.

Parameters
sample_nameName of the target sample to analyze
Returns
true if sample exists and was selected, false if sample not found
Note
Must be called before InitializeParametersAndObservations()

Definition at line 5161 of file sourcesinkdata.cpp.

References selected_target_sample_, and target_group_.

Referenced by Conductor::ExecuteOMSizeCorrect().

◆ SetTargetGroup()

bool SourceSinkData::SetTargetGroup ( const string &  targroup)

Sets the target/sink group designation.

Specifies which group in the dataset represents the target samples (receptor sites to be unmixed via source apportionment).

Parameters
targroupName of the target group
Returns
Always returns true

Definition at line 5016 of file sourcesinkdata.cpp.

References target_group_.

◆ SizeOMOrder()

vector< string > SourceSinkData::SizeOMOrder ( )
private

Retrieves the ordering of size and OM constituents.

Returns
Vector of size/OM constituent names

Definition at line 5105 of file sourcesinkdata.cpp.

References size_om_order_.

◆ SolveLevenberg_Marquardt()

bool SourceSinkData::SolveLevenberg_Marquardt ( transformation  trans = transformation::linear)

Solves for optimal source contributions using the Levenberg-Marquardt algorithm.

Iteratively optimizes source contributions to minimize the residual between predicted and observed elemental/isotopic compositions. The algorithm adaptively adjusts the damping parameter based on convergence behavior.

Convergence criteria (any of):

  • Residual norm < tolerance (1e-10)
  • Parameter change norm < tolerance (1e-10)
  • Maximum iterations reached (1000)
Parameters
transParameterization method:
Returns
bool Currently always returns false (legacy)
Note
Updates internal state with optimized contributions
Progress displayed in rtw_ if set

Definition at line 1298 of file sourcesinkdata.cpp.

References ProgressWindow::AppendPoint(), GetContributionVector(), GetContributionVectorSoftmax(), InitializeContributionsRandomly(), InitializeContributionsRandomlySoftmax(), linear, OneStepLevenberg_Marquardt(), OneStepLevenberg_Marquardt_softmax(), ResidualVector(), rtw_, SetContribution(), SetContributionSoftmax(), ProgressWindow::SetProgress(), ProgressWindow::SetXRange(), and softmax.

Referenced by BootStrap(), BootStrap(), Conductor::ExecuteLevenbergMarquardt(), LM_Batch(), and VerifySource().

◆ SourceGroupNames()

vector< string > SourceSinkData::SourceGroupNames ( ) const

Retrieves the names of all source groups (excluding target)

Returns a list of source group names, which are the pollution/emission sources being apportioned in the CMB analysis.

Returns
Vector of source group names
Note
Target group is filtered out

Definition at line 2162 of file sourcesinkdata.cpp.

References target_group_.

Referenced by GenericForm::GenericForm(), and MCMC().

◆ StepwiseDiscriminantFunctionAnalysis() [1/3]

vector< CMBVector > SourceSinkData::StepwiseDiscriminantFunctionAnalysis ( )

Performs stepwise discriminant analysis across all source groups.

Iteratively selects elements that best discriminate among all source groups using forward selection.

Returns
Vector of 3 CMBVectors containing selection order with: [0] = p-values at each step [1] = Wilks' Lambda at each step [2] = F-test p-values at each step
Note
Uses multi-group DFA statistics

Definition at line 4843 of file sourcesinkdata.cpp.

References DFA_P_Value(), DFA_Projected(), ExtractSpecificElements(), CMBVectorSet::FTest_p_value(), GetElementNames(), rtw_, ProgressWindow::SetProgress(), and WilksLambda().

◆ StepwiseDiscriminantFunctionAnalysis() [2/3]

vector< CMBVector > SourceSinkData::StepwiseDiscriminantFunctionAnalysis ( const string &  source1)

Performs stepwise discriminant analysis for one source vs all others.

Iteratively selects elements that best discriminate one source from all other sources combined using forward selection.

Parameters
source1Name of source group to test against others
Returns
Vector of 3 CMBVectors containing selection order
Note
Other sources pooled into "Others" group

Definition at line 4908 of file sourcesinkdata.cpp.

References CMBVector::append(), DiscriminantFunctionAnalysis(), ExtractSpecificElements(), DFA_result::F_test_P_value, GetElementNames(), DFA_result::p_values, rtw_, ProgressWindow::SetProgress(), and DFA_result::wilkslambda.

◆ StepwiseDiscriminantFunctionAnalysis() [3/3]

vector< CMBVector > SourceSinkData::StepwiseDiscriminantFunctionAnalysis ( const string &  source1,
const string &  source2 
)

Performs stepwise discriminant analysis between two specific sources.

Iteratively selects elements that best discriminate between two source groups using a forward selection procedure. At each step, adds the element that most improves group separation (lowest p-value).

Parameters
source1Name of first source group
source2Name of second source group
Returns
Vector of 3 CMBVectors containing selection order with: [0] = p-values at each step [1] = Wilks' Lambda at each step [2] = F-test p-values at each step
Note
Elements ordered by discriminating power (best first)
Progress updates sent to rtw_ if available

Definition at line 4773 of file sourcesinkdata.cpp.

References CMBVector::append(), DiscriminantFunctionAnalysis(), DFA_result::eigen_vectors, ExtractSpecificElements(), DFA_result::F_test_P_value, GetElementNames(), DFA_result::p_values, rtw_, ProgressWindow::SetProgress(), and DFA_result::wilkslambda.

Referenced by Conductor::ExecuteSDFA(), Conductor::ExecuteSDFAM(), and Conductor::ExecuteSDFAOnevsRest().

◆ t_TestPValue()

Elemental_Profile SourceSinkData::t_TestPValue ( const string &  source1,
const string &  source2,
bool  use_log 
)

Computes t-test p-values for element-wise differences between two sources.

Performs independent two-sample t-tests for each element to assess whether concentrations differ significantly between two source groups. Lower p-values indicate stronger evidence that the sources differ for that element.

T-statistic: t = (μ₁ - μ₂) / √(σ₁²/n₁ + σ₂²/n₂)

Parameters
source1Name of first source group
source2Name of second source group
use_logIf true, perform test on log-transformed concentrations; if false, use linear-space concentrations
Returns
Elemental_Profile containing two-tailed p-values for each element
Note
P-values are two-tailed (tests for any difference, not directional)
Lower p-values indicate better source differentiation
Log-space testing appropriate for log-normally distributed data
See also
DifferentiationPower_P_value() for all pairwise comparisons

Definition at line 3204 of file sourcesinkdata.cpp.

References Elemental_Profile::AppendElement(), ConcentrationSet::CalculateMean(), ConcentrationSet::CalculateMeanLog(), ConcentrationSet::CalculateStdDev(), ConcentrationSet::CalculateStdDevLog(), and GetElementNames().

Referenced by DifferentiationPower_P_value(), and Conductor::ExecuteEDP().

◆ TheRest()

Elemental_Profile_Set SourceSinkData::TheRest ( const string &  excluded_source)
private

Collects all source samples except those from a specified source group.

Creates a combined profile set containing samples from all source groups except the specified one and the target group. Useful for "one vs rest" comparisons.

Parameters
excluded_sourceName of the source group to exclude
Returns
Elemental_Profile_Set containing all samples from other sources
Note
Target group is always excluded

Definition at line 2968 of file sourcesinkdata.cpp.

References Elemental_Profile_Set::AppendProfile(), and target_group_.

Referenced by DiscriminantFunctionAnalysis().

◆ ToolsUsed()

bool SourceSinkData::ToolsUsed ( const string &  tool_name)

Checks if a specific analysis tool has been used.

Queries the tools_used list to determine if a particular analysis method or tool has been applied to this dataset.

Parameters
tool_nameName of the tool to check (e.g., "MCMC", "Bootstrap")
Returns
true if tool has been used, false otherwise

Definition at line 4407 of file sourcesinkdata.cpp.

References tools_used_.

Referenced by AddtoToolsUsed(), and ToolBoxItem::data().

◆ ToolsUsedToJsonObject()

QJsonArray SourceSinkData::ToolsUsedToJsonObject ( ) const

Exports the list of analysis tools used to a JSON array.

Serializes the names of all statistical/analytical tools that have been applied to this dataset (e.g., "MCMC", "Levenberg-Marquardt", "BoxCox").

Returns
QJsonArray containing tool names as strings

Definition at line 2580 of file sourcesinkdata.cpp.

References tools_used_.

Referenced by MainWindow::buildProjectJson().

◆ TotalNumberofSourceSamples()

int SourceSinkData::TotalNumberofSourceSamples ( ) const
private

Counts the total number of source samples across all source groups.

Sums the number of samples in all source groups, excluding the target group.

Returns
Total number of source samples
Note
Target group samples are excluded

Definition at line 2930 of file sourcesinkdata.cpp.

References target_group_.

Referenced by DFA_P_Value().

◆ TotalScatterMatrix()

CMatrix SourceSinkData::TotalScatterMatrix ( )
private

Computes total scatter matrix.

Calculates the overall covariance matrix treating all source samples as a single population. Represents total variability.

Formula: S_T = Σ Σ[(x_ij - μ_overall)(x_ij - μ_overall)ᵀ] / N

Relationship: S_T = S_W + S_B

Returns
Total scatter matrix (num_elements × num_elements)
Note
Target group excluded

Definition at line 4512 of file sourcesinkdata.cpp.

References GetElementNames(), MeanElementalContent(), CMBVector::size(), and target_group_.

◆ VerifySource()

CMBTimeSeriesSet SourceSinkData::VerifySource ( const string &  source_group,
bool  use_softmax,
bool  apply_om_size_correction 
)

Performs leave-one-out validation on a source group.

Tests source apportionment accuracy by iteratively treating each sample from a source group as an unknown target, solving the CMB model, and comparing estimated contributions against the known true source.

Ideal result: Sample shows ~100% contribution from its true source

Parameters
source_groupName of source group to validate
use_softmaxIf true, use softmax transformation for contributions
apply_om_size_correctionIf true, apply OM and size corrections
Returns
CMBTimeSeriesSet containing contribution estimates for each sample
Note
Samples with negative values after correction are skipped
Progress updates sent to rtw_ if available

Definition at line 3861 of file sourcesinkdata.cpp.

References CreateCorrectedDataset(), GetContributionVector(), GetElementInformation(), GetSampleSet(), InitializeParametersAndObservations(), linear, NegativeValueCheck(), numberofsourcesamplesets_, ReplaceSourceAsTarget(), rtw_, samplesetsorder_, CMBTimeSeriesSet::SetLabel(), ProgressWindow::SetProgress(), SetProgressWindow(), softmax, SolveLevenberg_Marquardt(), and target_group_.

Referenced by Conductor::ExecuteSourceVerify().

◆ WilksLambda()

double SourceSinkData::WilksLambda ( )
private

Computes Wilks' Lambda statistic for multivariate group separation.

Calculates Wilks' Lambda, a multivariate test statistic measuring the ratio of within-group to total variance.

Formula: Λ = |S_W| / |S_T| = |S_W| / |S_W + S_B|

Interpretation:

  • Λ = 1: No group separation
  • Λ → 0: Perfect separation
Returns
Wilks' Lambda statistic (0 to 1)
Note
Uses absolute values of determinants for numerical stability

Definition at line 4553 of file sourcesinkdata.cpp.

References BetweenGroupCovarianceMatrix(), and WithinGroupCovarianceMatrix().

Referenced by DFA_P_Value(), DiscriminantFunctionAnalysis(), DiscriminantFunctionAnalysis(), and StepwiseDiscriminantFunctionAnalysis().

◆ WithinGroupCovarianceMatrix()

CMatrix SourceSinkData::WithinGroupCovarianceMatrix ( )
private

Computes pooled within-group covariance matrix.

Calculates the weighted average of covariance matrices within each source group. Represents the "error" or within-group scatter in discriminant analysis.

Formula: S_W = Σ[(n_i - 1) × Σ_i] / Σ(n_i - 1)

Returns
Within-group covariance matrix (num_elements × num_elements)
Note
Target group excluded
Weighted by degrees of freedom (n_i - 1)

Definition at line 4450 of file sourcesinkdata.cpp.

References GetElementNames(), and target_group_.

Referenced by DFA_eigvector(), and WilksLambda().

◆ WriteDataToFile()

bool SourceSinkData::WriteDataToFile ( QFile *  file)

Writes elemental profile data to a text file.

Outputs all sample groups and their elemental profiles in tab-delimited text format for documentation or debugging purposes.

Parameters
filePointer to an open QFile for writing
Returns
true if write operation succeeded
Note
File must be opened in write mode before calling

Definition at line 2686 of file sourcesinkdata.cpp.

Referenced by WriteToFile().

◆ WriteToFile()

bool SourceSinkData::WriteToFile ( QFile *  file)

Writes dataset to a text file.

Public interface for writing elemental profile data to a file.

Parameters
filePointer to an open QFile for writing
Returns
true if write operation succeeded

Definition at line 2703 of file sourcesinkdata.cpp.

References WriteDataToFile().

Member Data Documentation

◆ constituent_order_

vector<string> SourceSinkData::constituent_order_
private

◆ distance_coeff_

double SourceSinkData::distance_coeff_
private

Definition at line 1808 of file sourcesinkdata.h.

Referenced by GradientUpdate(), and operator=().

◆ element_distributions_

map<string, ConcentrationSet> SourceSinkData::element_distributions_
private

◆ element_information_

◆ element_order_

◆ epsilon_

double SourceSinkData::epsilon_
private

Definition at line 1811 of file sourcesinkdata.h.

Referenced by Gradient().

◆ error_stdev_

double SourceSinkData::error_stdev_
private

Definition at line 1809 of file sourcesinkdata.h.

Referenced by LogLikelihoodModelvsMeasured(), and SetParameterValue().

◆ error_stdev_isotope_

double SourceSinkData::error_stdev_isotope_
private

Definition at line 1810 of file sourcesinkdata.h.

Referenced by LogLikelihoodModelvsMeasured_Isotope(), and SetParameterValue().

◆ isotope_order_

◆ numberofconstituents_

◆ numberofisotopes_

◆ numberofsourcesamplesets_

◆ observations_

vector<Observation> SourceSinkData::observations_
private

◆ omconstituent_

◆ options_

QMap<QString, double> SourceSinkData::options_
private

◆ outputpath_

string SourceSinkData::outputpath_
private

◆ parameter_estimation_mode_

estimation_mode SourceSinkData::parameter_estimation_mode_
private

◆ parameters_

◆ regression_p_value_threshold_

double SourceSinkData::regression_p_value_threshold_
private

◆ rtw_

◆ samplesetsorder_

◆ selected_target_sample_

◆ size_om_order_

vector<string> SourceSinkData::size_om_order_
private

◆ sizeconsituent_

◆ target_group_

◆ tools_used_

list<string> SourceSinkData::tools_used_
private

Definition at line 1815 of file sourcesinkdata.h.

Referenced by AddtoToolsUsed(), Clear(), operator=(), ToolsUsed(), and ToolsUsedToJsonObject().


The documentation for this class was generated from the following files: