SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
conductor.cpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
4#include "conductor.h"
5#include <algorithm>
6#include <set>
7#include "randomstream.h"
8#include "analysishost.h"
9#include "progressreporter.h"
10#include "results.h"
11#include "contribution.h"
12#include "resultitem.h"
13#include "testmcmc.h"
14#include "rangeset.h"
15#include "numericparsing.h"
16
17
19 : data(nullptr),
20 host(host)
21{
22}
23
24bool Conductor::Execute(const string &command, const map<string,string>& arguments)
25{
26 results.clear();
28 return false;
29
30 // Fingerprinting needs each included isotope's base element to turn the
31 // delta value into a concentration; without it the analysis used to crash
32 static const std::set<string> fingerprinting_commands = {
33 "Levenberg-Marquardt", "Levenberg-Marquardt-Batch",
34 "GA", "GA (fixed elemental contribution)", "GA (disregarding targets)",
35 "CMB Bayesian", "CMB Bayesian-Batch", "Test CMB Bayesian",
36 "Error_Analysis", "Source_Verify"};
37 if (fingerprinting_commands.count(command) > 0)
38 {
39 const vector<string> problems = Data()->IsotopesWithUnusableBaseElement();
40 if (!problems.empty())
41 {
42 string message;
43 for (const string& problem : problems)
44 message += problem + "\n";
45 message += "\nInclude the base element in the analysis (Settings > Constituent Properties), "
46 "or exclude the isotope.";
47 host->ShowWarning(message);
48 return false;
49 }
50 }
51
52#ifdef SEDSAT3_ENABLE_GA
53 if (command == "GA")
54 {
55 return ExecuteGA(arguments);
56 }
57 if (command == "GA (fixed elemental contribution)")
58 {
59 return ExecuteGA_FixedProfile(arguments);
60 }
61 if (command == "GA (disregarding targets)")
62 {
63 return ExecuteGA_NoTargets(arguments);
64 }
65#else
66 if (command.rfind("GA", 0) == 0)
67 {
68 host->ShowWarning("The genetic algorithm is not included in this build of SedSAT3. "
69 "Use Levenberg-Marquardt, or build with ENABLE_GA (CMake) or CONFIG+=ga (qmake).");
70 return false;
71 }
72#endif
73 if (command == "Levenberg-Marquardt")
74 {
75 return ExecuteLevenbergMarquardt(arguments);
76 }
77 if (command == "Levenberg-Marquardt-Batch")
78 {
79 return ExecuteLevenbergMarquardtBatch(arguments);
80 }
81 if (command == "OM-Size Correct")
82 {
83 return ExecuteOMSizeCorrect(arguments);
84 }
85 if (command == "MLR")
86 {
87 return ExecuteMLR(arguments);
88 }
89 if (command == "CovMat")
90 {
91 return ExecuteCovarianceMatrix(arguments);
92 }
93 if (command == "CorMat")
94 {
95 return ExecuteCorrelationMatrix(arguments);
96 }
97 if (command == "DFA")
98 {
99 return ExecuteDFA(arguments);
100 }
101
102 if (command == "DFAOnevsRest")
103 {
104 return ExecuteDFAOnevsRest(arguments);
105 }
106 if (command == "DFAM")
107 {
108 return ExecuteDFAM(arguments);
109 }
110 if (command == "SDFA")
111 {
112 return ExecuteSDFA(arguments);
113 }
114
115 if (command == "SDFAM")
116 {
117 return ExecuteSDFAM(arguments);
118 }
119
120 if (command == "SDFAOnevsRest")
121 {
122 return ExecuteSDFAOnevsRest(arguments);
123 }
124
125 if (command == "KS")
126 {
127 return ExecuteKolmogorovSmirnov(arguments);
128 }
129 if (command == "KS-individual")
130 {
131 return ExecuteKolmogorovSmirnovIndividual(arguments);
132 }
133 if (command == "CMB Bayesian")
134 {
135 return ExecuteCMBBayesian(arguments);
136 }
137 if (command == "CMB Bayesian-Batch")
138 {
139 return ExecuteCMBBayesianBatch(arguments);
140 }
141 if (command == "Test CMB Bayesian")
142 {
143 return ExecuteTestCMBBayesian(arguments);
144 }
145
146 if (command == "DF")
147 {
148 return ExecuteDistributionFitting(arguments);
149 }
150
151 if (command == "Bracketing Analysis")
152 {
153 return ExecuteBracketingAnalysis(arguments);
154 }
155 if (command == "Bracketing Analysis Batch")
156 {
157 return ExecuteBracketingAnalysisBatch(arguments);
158 }
159 if (command == "BoxCox")
160 {
161 return ExecuteBoxCox(arguments);
162 }
163
164 if (command == "Outlier")
165 {
166 return ExecuteOutlierAnalysis(arguments);
167 }
168
169 if (command == "EDP")
170 {
171 return ExecuteEDP(arguments);
172 }
173
174 if (command == "EDPM")
175 {
176 return ExecuteEDPM(arguments);
177 }
178 if (command == "ANOVA")
179 {
180 return ExecuteANOVA(arguments);
181 }
182
183 if (command == "Error_Analysis")
184 {
185 return ExecuteErrorAnalysis(arguments);
186 }
187
188 if (command == "Source_Verify")
189 {
190 return ExecuteSourceVerify(arguments);
191 }
192
193 if (command == "AutoSelect")
194 {
195 return ExecuteAutoSelect(arguments);
196 }
197 Data()->AddtoToolsUsed(command);
198 return true;
199}
200
202{
203 if (_data==nullptr)
204 _data = Data();
205 vector<string> NegativeCheckResults =_data->NegativeValueCheck();
206
207 if (NegativeCheckResults.size()>0)
208 {
209 // A dataset derived for the analysis (corrected or filtered) can have
210 // negatives the imported data does not, made by the organic-matter
211 // and size correction; say so rather than blaming the input
212 vector<string> imported_results;
213 if (_data != Data() && Data() != nullptr)
214 imported_results = Data()->NegativeValueCheck();
215
216 QString message;
217 for (unsigned int i=0; i<NegativeCheckResults.size(); i++)
218 {
219 message += QString::fromStdString(NegativeCheckResults[i]);
220 if (_data != Data() &&
221 std::find(imported_results.begin(), imported_results.end(), NegativeCheckResults[i]) == imported_results.end())
222 message += " (after the organic matter and size correction; the imported values are positive)";
223 message += "\n";
224 }
225 host->ShowWarning(message.toStdString());
226 return false;
227 }
228 return true;
229
230}
231
232bool Conductor::CheckNegativeElements(map<string,vector<string>> negative_elements)
233{
234 QString message;
235 for (map<string,vector<string>>::iterator it = negative_elements.begin(); it!=negative_elements.end(); it++)
236 {
237 if (it->second.size()>0)
238 { message += "For target sample '" + QString::fromStdString(it->first) + ":\n";
239 for (unsigned int i=0; i<it->second.size(); i++)
240 {
241 message += QString::fromStdString("\t" + it->second[i]) + "\n";
242 }
243 }
244
245 }
246
247 if (message!="")
248 { host->ShowWarning(message.toStdString());
249 return false;
250 }
251
252 return true;
253}
254
255void Conductor::ReportNegativeContributions(const vector<string>& offenders)
256{
257 if (offenders.empty())
258 return;
259
260 string message =
261 "The fit returned a negative contribution, which is not a physically "
262 "possible result - a source cannot supply a negative share of the "
263 "target sample:\n\n";
264
265 // A batch run over many target samples can produce a long list; show enough
266 // to identify the problem without a dialog that runs off the screen.
267 const unsigned int most_to_list = 20;
268 for (unsigned int i = 0; i < offenders.size() && i < most_to_list; i++)
269 message += "\t" + offenders[i] + "\n";
270
271 if (offenders.size() > most_to_list)
272 {
273 message += "\t... and " +
274 aquiutils::numbertostring(static_cast<unsigned int>(offenders.size() - most_to_list)) +
275 " more\n";
276 }
277
278 message +=
279 "\nWithout the softmax transformation the contributions are only "
280 "constrained to sum to one, so the optimization is free to drive one "
281 "below zero to fit the remaining sources more closely. Re-run with "
282 "'Softmax transformation' enabled, which makes a negative contribution "
283 "impossible; a source that is not present then comes out at or near "
284 "zero instead.\n\n"
285 "Expect the reported error to be slightly larger with the softmax "
286 "transformation. That is the cost of a solution that stays physically "
287 "possible.";
288
289 host->ShowWarning(message);
290}
291
292void Conductor::ReportBoxCoxSkips(SourceSinkData& dataset, const std::string& group, const std::string& consequence)
293{
294 std::string message;
295 for (auto& [group_name, profile_set] : dataset)
296 {
297 if (!group.empty() && group_name != group)
298 continue;
299 for (const std::string& element : profile_set.ElementsNotBoxCoxTransformable())
300 message += "\t" + element + " in group '" + group_name + "'\n";
301 }
302 if (!message.empty())
303 host->ShowWarning("The Box-Cox transformation needs positive values, so these constituents "
304 "with zero or negative values were not transformed; " + consequence + ":\n" + message);
305}
306
307bool Conductor::ResolveRandomSeed(std::map<std::string, std::string>& arguments, std::uint64_t& seed)
308{
309 const std::string text = arguments.count("Random seed") ? arguments.at("Random seed") : "";
310 if (!ParseRandomSeed(text, seed))
311 {
312 host->ShowWarning("The random seed '" + text + "' is not a whole number between 0 and "
313 "18446744073709551615. Leave it blank to have one chosen.");
314 return false;
315 }
316 arguments["Random seed"] = std::to_string(seed);
317 return true;
318}
319
321{
322 ReportBoxCoxSkips(dataset, "", "they were used untransformed");
323 return dataset.BoxCoxTransformed(true);
324}
325
326#ifdef SEDSAT3_ENABLE_GA
327bool Conductor::ExecuteGA(const std::map<std::string, std::string>& arguments)
328{
330
331 bool organic_size_correction = false;
332 if (arguments.at("Apply size and organic matter correction") == "true")
333 {
334 organic_size_correction = true;
335 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
336 {
337 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
338 return false;
339 }
340 }
341 else
342 {
343 organic_size_correction = false;
344 }
345
346 SourceSinkData corrected_data = Data()->CreateCorrectedDataset(
347 arguments.at("Sample"),
348 organic_size_correction,
349 Data()->GetElementInformation()
350 );
351
352 rtw->Start();
353 corrected_data.InitializeParametersAndObservations(arguments.at("Sample"));
354
355 if (!CheckNegativeElements(&corrected_data))
356 return false;
357
358 GA = std::make_unique<CGA<SourceSinkData>>(&corrected_data);
359 GA->filenames.pathname = workingfolder.toStdString() + "/";
360 GA->SetRunTimeWindow(rtw);
361 GA->SetProperties(arguments);
362 GA->InitiatePopulation();
363 GA->optimize();
364
365 results.SetName("GA " + arguments.at("Sample"));
366
367 ResultItem result_contribution = GA->Model_out.GetContribution();
368 result_contribution.SetShowTable(true);
369 result_contribution.SetType(result_type::contribution);
370 result_contribution.SetShowGraph(true);
371 results.Append(result_contribution);
372
373 ResultItem result_modeled_vs_measured = GA->Model_out.GetObservedvsModeledElementalProfile();
374 result_modeled_vs_measured.SetShowGraph(true);
375 result_modeled_vs_measured.SetShowTable(true);
376 results.Append(result_modeled_vs_measured);
377
378 ResultItem result_modeled_vs_measured_isotope = GA->Model_out.GetObservedvsModeledElementalProfile_Isotope();
379 result_modeled_vs_measured_isotope.SetShowGraph(true);
380 result_modeled_vs_measured_isotope.SetShowTable(true);
381 results.Append(result_modeled_vs_measured_isotope);
382
383 ResultItem result_calculated_means = GA->Model_out.GetCalculatedElementMeans();
384 result_calculated_means.SetShowTable(true);
385 result_calculated_means.SetShowGraph(false);
386 results.Append(result_calculated_means);
387
388 ResultItem result_estimated_means = GA->Model_out.GetEstimatedElementMean();
389 result_estimated_means.SetShowTable(true);
390 result_estimated_means.SetShowGraph(false);
391 results.Append(result_estimated_means);
392
393 ResultItem result_calculated_mu = GA->Model_out.GetCalculatedElementMu();
394 result_calculated_mu.SetShowTable(true);
395 result_calculated_mu.SetShowGraph(false);
396 results.Append(result_calculated_mu);
397
398 ResultItem result_estimated_mu = GA->Model_out.GetEstimatedElementMu();
399 result_estimated_mu.SetShowTable(true);
400 result_estimated_mu.SetShowGraph(false);
401 results.Append(result_estimated_mu);
402
403 ResultItem result_calculated_sigma = GA->Model_out.GetCalculatedElementSigma();
404 result_calculated_sigma.SetShowTable(true);
405 result_calculated_sigma.SetShowGraph(false);
406 results.Append(result_calculated_sigma);
407
408 ResultItem result_estimated_sigma = GA->Model_out.GetEstimatedElementSigma();
409 result_estimated_sigma.SetShowTable(true);
410 result_estimated_sigma.SetShowGraph(false);
411 results.Append(result_estimated_sigma);
412
413 return true;
414}
415
416
417bool Conductor::ExecuteGA_FixedProfile(const std::map<std::string, std::string>& arguments)
418{
419 ScopedProgressReporter rtw(host);
420 rtw->SetTitle("Fitness", 0);
421 rtw->SetYAxisTitle("Fitness", 0);
422
423 bool organic_size_correction = false;
424 if (arguments.at("Apply size and organic matter correction") == "true")
425 {
426 organic_size_correction = true;
427 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
428 {
429 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
430 return false;
431 }
432 }
433 else
434 {
435 organic_size_correction = false;
436 }
437
438 SourceSinkData corrected_data = Data()->CreateCorrectedDataset(
439 arguments.at("Sample"),
440 organic_size_correction,
441 Data()->GetElementInformation()
442 );
443
444 if (!CheckNegativeElements(&corrected_data))
445 return false;
446
447 rtw->Start();
449 arguments.at("Sample"),
451 );
453
454 GA = std::make_unique<CGA<SourceSinkData>>(&corrected_data);
455 GA->filenames.pathname = workingfolder.toStdString() + "/";
456 GA->SetRunTimeWindow(rtw);
457 GA->SetProperties(arguments);
458 GA->InitiatePopulation();
459 GA->optimize();
460
461 results.SetName("GA (fixed profile) " + arguments.at("Sample"));
462
463 ResultItem result_contribution = GA->Model_out.GetContribution();
464 results.Append(result_contribution);
465
466 ResultItem result_modeled_vs_measured = GA->Model_out.GetObservedvsModeledElementalProfile(parameter_mode::direct);
467 results.Append(result_modeled_vs_measured);
468
469 ResultItem result_modeled_vs_measured_isotope = GA->Model_out.GetObservedvsModeledElementalProfile_Isotope(parameter_mode::direct);
470 results.Append(result_modeled_vs_measured_isotope);
471
472 return true;
473}
474
475bool Conductor::ExecuteGA_NoTargets(const std::map<std::string, std::string>& arguments)
476{
477 ScopedProgressReporter rtw(host);
478 rtw->Start();
479
481 arguments.at("Sample"),
483 );
485
486 GA = std::make_unique<CGA<SourceSinkData>>(Data());
487 GA->filenames.pathname = workingfolder.toStdString() + "/";
488 GA->SetRunTimeWindow(rtw);
489 GA->SetProperties(arguments);
490 GA->InitiatePopulation();
491 GA->optimize();
492
493 results.SetName("GA (no targets) " + arguments.at("Sample"));
494
495 ResultItem result_calculated_means = GA->Model_out.GetCalculatedElementMeans();
496 results.Append(result_calculated_means);
497
498 ResultItem result_estimated_means = GA->Model_out.GetEstimatedElementMean();
499 results.Append(result_estimated_means);
500
501 ResultItem result_calculated_stds = GA->Model_out.GetCalculatedElementSigma();
502 results.Append(result_calculated_stds);
503
504 ResultItem result_estimated_stds = GA->Model_out.GetEstimatedElementSigma();
505 results.Append(result_estimated_stds);
506
507 return true;
508}
509
510#endif // SEDSAT3_ENABLE_GA
511
512bool Conductor::ExecuteLevenbergMarquardt(const std::map<std::string, std::string>& arguments)
513{
515
516 bool organic_size_correction = false;
517 if (arguments.at("Apply size and organic matter correction") == "true")
518 {
519 organic_size_correction = true;
520 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
521 {
522 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
523 return false;
524 }
525 }
526 else
527 {
528 organic_size_correction = false;
529 }
530
531 rtw->Start();
532
533 SourceSinkData corrected_data = Data()->CreateCorrectedDataset(
534 arguments.at("Sample"),
535 organic_size_correction,
536 Data()->GetElementInformation()
537 );
538
539 if (!CheckNegativeElements(&corrected_data))
540 return false;
541
542 corrected_data.InitializeParametersAndObservations(arguments.at("Sample"));
543 corrected_data.SetProgressReporter(rtw);
544
545 if (arguments.at("Softmax transformation") == "true")
546 {
548 }
549 else
550 {
552 }
553
554 // A negative contribution is reported rather than suppressed: the results
555 // below still show the fit, and the warning says why it is not a usable
556 // answer. Only the linear parameterization can produce one.
558
559 results.SetName("LM " + arguments.at("Sample"));
560
561 ResultItem result_contribution = corrected_data.GetContribution();
562 result_contribution.SetShowTable(true);
563 results.Append(result_contribution);
564
565 ResultItem result_modeled = corrected_data.GetPredictedElementalProfile(parameter_mode::direct);
566 result_modeled.SetShowTable(true);
567 results.Append(result_modeled);
568
569 ResultItem result_modeled_vs_measured = corrected_data.GetObservedvsModeledElementalProfile();
570 result_modeled_vs_measured.SetShowTable(true);
571 results.Append(result_modeled_vs_measured);
572
573 ResultItem result_modeled_vs_measured_isotope = corrected_data.GetObservedvsModeledElementalProfile_Isotope(parameter_mode::direct);
574 result_modeled_vs_measured_isotope.SetShowTable(true);
575 results.Append(result_modeled_vs_measured_isotope);
576
577 return true;
578}
579
580bool Conductor::ExecuteLevenbergMarquardtBatch(const std::map<std::string, std::string>& arguments)
581{
583
584 bool organic_size_correction = false;
585 if (arguments.at("Apply size and organic matter correction") == "true")
586 {
587 organic_size_correction = true;
588 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
589 {
590 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
591 return false;
592 }
593 }
594 else
595 {
596 organic_size_correction = false;
597 }
598
599 rtw->Start();
600
602
603 CMBTimeSeriesSet* contributions = nullptr;
604 std::map<std::string, std::vector<std::string>> negative_elements;
605
606 if (arguments.at("Softmax transformation") == "true")
607 {
608 contributions = new CMBTimeSeriesSet(Data()->LM_Batch(
610 organic_size_correction,
611 negative_elements
612 ));
613 }
614 else
615 {
616 contributions = new CMBTimeSeriesSet(Data()->LM_Batch(
618 organic_size_correction,
619 negative_elements
620 ));
621 }
622
623 if (negative_elements.size() > 0)
624 {
625 CheckNegativeElements(negative_elements);
626 }
627
628 // The same check the single-sample tool makes, over every target sample.
629 // The contributions are read back from the result set rather than from the
630 // dataset, because each sample was solved on its own corrected copy.
631 {
632 const double round_off = -1e-9;
633 vector<string> negative_contributions;
634
635 for (unsigned int source = 0; source < contributions->size(); source++)
636 {
637 for (unsigned int sample = 0; sample < contributions->at(source).size(); sample++)
638 {
639 const double contribution = contributions->at(source).getValue(sample);
640 if (contribution < round_off)
641 {
642 negative_contributions.push_back(
643 contributions->Label(sample, source) + " / " +
644 contributions->getSeriesName(source) + ": " +
645 aquiutils::numbertostring(contribution));
646 }
647 }
648 }
649
650 ReportNegativeContributions(negative_contributions);
651 }
652
653 results.SetName("LM-Batch");
654
655 contributions->GetOptions().X_suffix = "";
656 contributions->GetOptions().Y_suffix = "";
657 contributions->SetOption(options_key::single_column_x, true);
658
659 ResultItem contributions_result_item;
660 contributions_result_item.SetName("Levenberg-Marquardt-Batch");
661 contributions_result_item.SetResult(contributions);
662 contributions_result_item.SetType(result_type::stacked_bar_chart);
663 contributions_result_item.SetShowAsString(true);
664 contributions_result_item.SetShowTable(true);
665 contributions_result_item.SetShowGraph(true);
666 contributions_result_item.SetYLimit(_range::high, 1);
667 contributions_result_item.SetXAxisMode(xaxis_mode::counter);
668 contributions_result_item.setYAxisTitle("Contribution");
669 contributions_result_item.setXAxisTitle("Sample");
670 contributions_result_item.SetYLimit(_range::low, 0);
671
672 results.Append(contributions_result_item);
673
674 return true;
675}
676
677bool Conductor::ExecuteOMSizeCorrect(const std::map<std::string, std::string>& arguments)
678{
679 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
680 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
681
682 Data()->SetSelectedTargetSample(arguments.at("Sample"));
683
685 exclude_samples,
686 exclude_elements,
687 true,
688 arguments.at("Sample")
689 );
690
691 std::vector<ResultItem> result_items = transformed_data.GetSourceProfiles();
692
693 results.SetName("Corrected Elemental Profiles for Target" + arguments.at("Sample"));
694
695 for (size_t i = 0; i < result_items.size(); i++)
696 {
697 results.Append(result_items[i]);
698 }
699
700 return true;
701}
702
703bool Conductor::ExecuteMLR(const std::map<std::string, std::string>& arguments)
704{
705 if (arguments.at("Organic Matter constituent") == "" &&
706 arguments.at("Particle Size constituent") == "")
707 {
708 host->ShowWarning("At least one of Organic Matter constituent and "
709 "Particle Size constituent must be selected");
710 return false;
711 }
712
713 results.SetName("MLR_vs_OM&Size ");
714
715 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
716
718 exclude_samples,
719 false,
720 false
721 );
722
723 double p_value_threshold = QString::fromStdString(arguments.at("P-value threshold")).toDouble();
724
725 if (arguments.at("Equation") == "Linear")
726 {
727 transformed_data.PerformRegressionVsOMAndSize(
728 arguments.at("Organic Matter constituent"),
729 arguments.at("Particle Size constituent"),
731 p_value_threshold
732 );
733 }
734 else
735 {
736 transformed_data.PerformRegressionVsOMAndSize(
737 arguments.at("Organic Matter constituent"),
738 arguments.at("Particle Size constituent"),
740 p_value_threshold
741 );
742 }
743
745 arguments.at("Organic Matter constituent"),
746 arguments.at("Particle Size constituent")
747 );
748
749 for (std::map<std::string, Elemental_Profile_Set>::iterator it = Data()->begin();
750 it != Data()->end();
751 ++it)
752 {
753 if (it->first != Data()->GetTargetGroup())
754 {
755 it->second.SetRegressionModels(transformed_data[it->first].GetRegressionModels());
756 }
757 }
758
759 std::vector<ResultItem> regression_results = transformed_data.GetMLRResults();
760
761 for (size_t i = 0; i < regression_results.size(); i++)
762 {
763 results.Append(regression_results[i]);
764 }
765
766 return true;
767}
768
769bool Conductor::ExecuteCovarianceMatrix(const std::map<std::string, std::string>& arguments)
770{
771 results.SetName("Covariance Matrix for " + arguments.at("Source/Target group"));
772
773 ResultItem covariance_matrix_item;
774 covariance_matrix_item.SetName("Covariance Matrix for " + arguments.at("Source/Target group"));
775 covariance_matrix_item.SetShowTable(true);
776 covariance_matrix_item.SetType(result_type::matrix);
777 covariance_matrix_item.SetShowGraph(false);
778
779 CMBMatrix* covariance_matrix = new CMBMatrix(
780 Data()->at(arguments.at("Source/Target group")).CalculateCovarianceMatrix()
781 );
782
783 covariance_matrix_item.SetResult(covariance_matrix);
784 results.Append(covariance_matrix_item);
785
786 return true;
787}
788
789
790bool Conductor::ExecuteCorrelationMatrix(const std::map<std::string, std::string>& arguments)
791{
792 results.SetName("Correlation Matrix for " + arguments.at("Source/Target group"));
793
794 ResultItem correlation_matrix_item;
795 correlation_matrix_item.SetName("Correlation Matrix");
796 correlation_matrix_item.SetShowTable(true);
797 correlation_matrix_item.setTableTitle("Correlation Matrix for source group '" +
798 arguments.at("Source/Target group") + "'");
799 correlation_matrix_item.SetType(result_type::matrix);
800 correlation_matrix_item.SetShowAsString(false); // a full matrix as text is unreadable; use the table
801 correlation_matrix_item.SetShowGraph(false);
802
803 double threshold = QString::fromStdString(arguments.at("Threshold")).toDouble();
804 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
805 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
806
807 // Correct first, then filter: filtering drops the organic matter and size
808 // constituents the correction needs (with "Use only selected elements"
809 // the correction used to fail)
810 SourceSinkData transformed_data;
811 if (arguments.at("OM and Size Correct based on target sample") != "")
812 {
813 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
814 {
815 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
816 return false;
817 }
818 transformed_data = Data()->CreateCorrectedDataset(
819 arguments.at("OM and Size Correct based on target sample"),
820 true,
821 Data()->GetElementInformation()
822 ).CreateCorrectedAndFilteredDataset(exclude_samples, exclude_elements, false);
823 }
824 else
825 {
826 transformed_data = Data()->CreateCorrectedAndFilteredDataset(
827 exclude_samples,
828 exclude_elements,
829 false
830 );
831 }
832
833 CMBMatrix* correlation_matrix = new CMBMatrix(
834 transformed_data.at(arguments.at("Source/Target group")).CalculateCorrelationMatrix()
835 );
836
837 correlation_matrix->SetLimit(_range::high, threshold);
838 correlation_matrix->SetLimit(_range::low, -threshold);
839
840 correlation_matrix_item.SetResult(correlation_matrix);
841 results.Append(correlation_matrix_item);
842
843 return true;
844}
845
846bool Conductor::ExecuteDFA(const std::map<std::string, std::string>& arguments)
847{
848 if (arguments.at("Source/Target group I") == arguments.at("Source/Target group II"))
849 {
850 host->ShowWarning("The selected sources must be different");
851 return false;
852 }
853
855 rtw->Start();
856
857 results.SetName("DFA between " + arguments.at("Source/Target group I") +
858 "&" + arguments.at("Source/Target group II"));
859
860 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
861 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
862
863 SourceSinkData transformed_data = *Data();
864
865 if (arguments.at("OM and Size Correct based on target sample") != "")
866 {
867 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
868 {
869 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
870 return false;
871 }
872 transformed_data = transformed_data.CreateCorrectedDataset(
873 arguments.at("OM and Size Correct based on target sample"),
874 true,
875 Data()->GetElementInformation()
876 );
877 }
878
879 transformed_data = transformed_data.CreateTracerDataset(
880 exclude_samples,
881 exclude_elements,
882 false
883 );
884
885 transformed_data.SetProgressReporter(rtw);
886
887 if (arguments.at("Box-cox transformation") == "true")
888 {
889 transformed_data = BoxCoxTransformedWithReport(transformed_data);
890 }
891
892 DFA_result dfa_result = transformed_data.DiscriminantFunctionAnalysis(
893 arguments.at("Source/Target group I"),
894 arguments.at("Source/Target group II")
895 );
896
897 if (dfa_result.eigen_vectors.size() == 0)
898 {
899 host->ShowWarning("Singular matrix in within group scatter matrix!\n");
900 return false;
901 }
902
903 // Chi-squared P-Value result
904 CMBVector* p_value = new CMBVector(dfa_result.p_values);
905 ResultItem dfa_p_value;
906 dfa_p_value.SetName("Chi-squared P-Value");
907 dfa_p_value.SetType(result_type::vector);
908 dfa_p_value.SetShowTable(true);
909 dfa_p_value.SetShowGraph(false);
910 dfa_p_value.SetResult(p_value);
911 results.Append(dfa_p_value);
912
913 // F-test P-Value result
914 CMBVector* f_test_p_value = new CMBVector(dfa_result.F_test_P_value);
915 ResultItem dfa_f_test_p_value;
916 dfa_f_test_p_value.SetName("F-test P-Value");
917 dfa_f_test_p_value.SetType(result_type::vector);
918 dfa_f_test_p_value.SetShowTable(true);
919 dfa_f_test_p_value.SetShowGraph(false);
920 dfa_f_test_p_value.SetResult(f_test_p_value);
921 results.Append(dfa_f_test_p_value);
922
923 // Projected Elemental Profiles result
924 ResultItem dfa_projected;
925 dfa_projected.SetName("Projected Elemental Profiles");
927 dfa_projected.SetShowTable(true);
928 dfa_projected.SetShowGraph(true);
929 dfa_projected.SetYAxisMode(yaxis_mode::normal);
930 CMBVectorSet* projected = new CMBVectorSet(dfa_result.projected);
931 dfa_projected.SetResult(projected);
932 results.Append(dfa_projected);
933
934 // Eigen vector result
935 ResultItem dfa_eigen_vector;
936 dfa_eigen_vector.SetName("Eigen vector");
937 dfa_eigen_vector.SetType(result_type::vector);
938 dfa_eigen_vector.SetShowTable(true);
939 dfa_eigen_vector.SetShowGraph(true);
940 dfa_eigen_vector.SetYAxisMode(yaxis_mode::normal);
941 CMBVector* eigen_vector = new CMBVector(dfa_result.eigen_vectors.begin()->second);
942 dfa_eigen_vector.SetResult(eigen_vector);
943 results.Append(dfa_eigen_vector);
944
945 rtw->SetProgress(1);
946
947 return true;
948}
949
950bool Conductor::ExecuteDFAOnevsRest(const std::map<std::string, std::string>& arguments)
951{
953 rtw->Start();
954
955 results.SetName("DFA between " + arguments.at("Source group") + "& the rest");
956
957 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
958 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
959
960 SourceSinkData transformed_data = *Data();
961
962 if (arguments.at("OM and Size Correct based on target sample") != "")
963 {
964 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
965 {
966 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
967 return false;
968 }
969 transformed_data = transformed_data.CreateCorrectedDataset(
970 arguments.at("OM and Size Correct based on target sample"),
971 true,
972 Data()->GetElementInformation()
973 );
974 }
975
976 transformed_data = transformed_data.CreateTracerDataset(
977 exclude_samples,
978 exclude_elements,
979 false
980 );
981
982 transformed_data.SetProgressReporter(rtw);
983
984 if (arguments.at("Box-cox transformation") == "true")
985 {
986 transformed_data = BoxCoxTransformedWithReport(transformed_data);
987 }
988
989 DFA_result dfa_result = transformed_data.DiscriminantFunctionAnalysis(
990 arguments.at("Source group")
991 );
992
993 if (dfa_result.eigen_vectors.size() == 0)
994 {
995 host->ShowWarning("Singular matrix in within group scatter matrix!\n");
996 return false;
997 }
998
999 // Chi-squared P-Value result
1000 CMBVector* p_value = new CMBVector(dfa_result.p_values);
1001 ResultItem dfa_p_value;
1002 dfa_p_value.SetName("Chi-squared P-Value");
1003 dfa_p_value.SetType(result_type::vector);
1004 dfa_p_value.SetShowTable(true);
1005 dfa_p_value.SetShowGraph(false);
1006 dfa_p_value.SetResult(p_value);
1007 results.Append(dfa_p_value);
1008
1009 // F-test P-Value result
1010 CMBVector* f_test_p_value = new CMBVector(dfa_result.F_test_P_value);
1011 ResultItem dfa_f_test_p_value;
1012 dfa_f_test_p_value.SetName("F-test P-Value");
1013 dfa_f_test_p_value.SetType(result_type::vector);
1014 dfa_f_test_p_value.SetShowTable(true);
1015 dfa_f_test_p_value.SetShowGraph(false);
1016 dfa_f_test_p_value.SetResult(f_test_p_value);
1017 results.Append(dfa_f_test_p_value);
1018
1019 // Projected Elemental Profiles result
1020 ResultItem dfa_projected;
1021 dfa_projected.SetName("Projected Elemental Profiles");
1023 dfa_projected.SetShowTable(true);
1024 dfa_projected.SetShowGraph(true);
1025 dfa_projected.SetYAxisMode(yaxis_mode::normal);
1026 CMBVectorSet* projected = new CMBVectorSet(dfa_result.projected);
1027 dfa_projected.SetResult(projected);
1028 results.Append(dfa_projected);
1029
1030 // Eigen vector result
1031 ResultItem dfa_eigen_vector;
1032 dfa_eigen_vector.SetName("Eigen vector");
1033 dfa_eigen_vector.SetType(result_type::vector);
1034 dfa_eigen_vector.SetShowTable(true);
1035 dfa_eigen_vector.SetShowGraph(true);
1036 dfa_eigen_vector.SetYAxisMode(yaxis_mode::normal);
1037 CMBVector* eigen_vector = new CMBVector(dfa_result.eigen_vectors.begin()->second);
1038 dfa_eigen_vector.SetResult(eigen_vector);
1039 results.Append(dfa_eigen_vector);
1040
1041 rtw->SetProgress(1);
1042
1043 return true;
1044}
1045
1046bool Conductor::ExecuteDFAM(const std::map<std::string, std::string>& arguments)
1047{
1049 rtw->Start();
1050
1051 results.SetName("Multi-way DFA analysis");
1052
1053 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1054 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
1055
1056 SourceSinkData transformed_data = *Data();
1057
1058 if (arguments.at("OM and Size Correct based on target sample") != "")
1059 {
1060 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1061 {
1062 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1063 return false;
1064 }
1065 transformed_data = transformed_data.CreateCorrectedDataset(
1066 arguments.at("OM and Size Correct based on target sample"),
1067 true,
1068 Data()->GetElementInformation()
1069 );
1070 }
1071
1072 transformed_data = transformed_data.CreateTracerDataset(
1073 exclude_samples,
1074 exclude_elements,
1075 false
1076 );
1077
1078 if (!CheckNegativeElements(&transformed_data))
1079 return false;
1080
1081 transformed_data.SetProgressReporter(rtw);
1082
1083 if (arguments.at("Box-cox transformation") == "true")
1084 {
1085 transformed_data = BoxCoxTransformedWithReport(transformed_data);
1086 }
1087
1088 DFA_result dfa_result = transformed_data.DiscriminantFunctionAnalysis();
1089
1090 if (dfa_result.eigen_vectors.size() == 0)
1091 {
1092 host->ShowWarning("Singular matrix in within group scatter matrix!\n");
1093 return false;
1094 }
1095
1096 // Chi-squared P-Value result
1097 CMBVector* p_value = new CMBVector(dfa_result.p_values);
1098 ResultItem dfa_p_value;
1099 dfa_p_value.SetName("Chi-squared P-Value");
1100 dfa_p_value.SetType(result_type::vector);
1101 dfa_p_value.SetShowTable(true);
1102 dfa_p_value.SetShowGraph(false);
1103 dfa_p_value.SetResult(p_value);
1104 results.Append(dfa_p_value);
1105
1106 // F-test P-Value result
1107 CMBVector* f_test_p_value = new CMBVector(dfa_result.F_test_P_value);
1108 ResultItem dfa_f_test_p_value;
1109 dfa_f_test_p_value.SetName("F-test P-Value");
1110 dfa_f_test_p_value.SetType(result_type::vector);
1111 dfa_f_test_p_value.SetShowTable(true);
1112 dfa_f_test_p_value.SetShowGraph(false);
1113 dfa_f_test_p_value.SetResult(f_test_p_value);
1114 results.Append(dfa_f_test_p_value);
1115
1116 // Multiway Projected Elemental Profiles result
1117 ResultItem dfa_projected;
1118 dfa_projected.SetName("Multiway Projected Elemental Profiles");
1120 dfa_projected.SetShowTable(true);
1121 dfa_projected.SetShowGraph(true);
1122 dfa_projected.SetYAxisMode(yaxis_mode::normal);
1123 CMBVectorSetSet* projected = new CMBVectorSetSet(dfa_result.multi_projected);
1124 dfa_projected.SetResult(projected);
1125 results.Append(dfa_projected);
1126
1127 // Eigen vectors result (multiple vectors for multiway)
1128 ResultItem dfa_eigen_vectors;
1129 dfa_eigen_vectors.SetName("Eigen vectors");
1130 dfa_eigen_vectors.SetType(result_type::vectorset);
1131 dfa_eigen_vectors.SetShowTable(true);
1132 dfa_eigen_vectors.SetShowGraph(true);
1133 dfa_eigen_vectors.SetYAxisMode(yaxis_mode::normal);
1134 CMBVectorSet* eigen_vectors = new CMBVectorSet(dfa_result.eigen_vectors);
1135 dfa_eigen_vectors.SetResult(eigen_vectors);
1136 results.Append(dfa_eigen_vectors);
1137
1138 rtw->SetProgress(1);
1139
1140 return true;
1141}
1142
1143bool Conductor::ExecuteSDFA(const std::map<std::string, std::string>& arguments)
1144{
1145 if (arguments.at("Source/Target group I") == arguments.at("Source/Target group II"))
1146 {
1147 host->ShowWarning("The selected sources must be different");
1148 return false;
1149 }
1150
1152 rtw->Start();
1153
1154 results.SetName("Stepwise DFA between " + arguments.at("Source/Target group I") +
1155 "&" + arguments.at("Source/Target group II"));
1156
1157 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1158 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
1159
1160 SourceSinkData transformed_data;
1161
1162 if (arguments.at("OM and Size Correct based on target sample") != "")
1163 {
1164 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1165 {
1166 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1167 return false;
1168 }
1169 transformed_data = Data()->CreateCorrectedDataset(
1170 arguments.at("OM and Size Correct based on target sample"),
1171 true,
1172 Data()->GetElementInformation()
1173 ).CreateTracerDataset(exclude_samples, exclude_elements, false);
1174 }
1175 else
1176 {
1177 transformed_data = Data()->CreateTracerDataset(
1178 exclude_samples,
1179 exclude_elements,
1180 false
1181 );
1182 }
1183
1184 if (!CheckNegativeElements(&transformed_data))
1185 return false;
1186
1187 if (arguments.at("Box-cox transformation") == "true")
1188 {
1189 transformed_data = BoxCoxTransformedWithReport(transformed_data);
1190 }
1191
1192 transformed_data.SetProgressReporter(rtw);
1193
1194 std::vector<CMBVector> sdfa_results = transformed_data.StepwiseDiscriminantFunctionAnalysis(
1195 arguments.at("Source/Target group I"),
1196 arguments.at("Source/Target group II")
1197 );
1198
1199 if (sdfa_results[0].size() == 0)
1200 {
1201 host->ShowWarning("Singular matrix in within group scatter matrix!\n");
1202 return false;
1203 }
1204
1205 // Chi-squared P-Values result
1206 CMBVector* p_vector = new CMBVector(sdfa_results[0]);
1207 ResultItem sdfa_p_values;
1208 sdfa_p_values.SetName("Chi-squared P-Values");
1209 sdfa_p_values.SetType(result_type::vector);
1210 sdfa_p_values.setXAxisTitle("Constituents, in the order added");
1211 sdfa_p_values.SetShowTable(true);
1212 sdfa_p_values.SetAbsoluteValue(true);
1213 sdfa_p_values.SetYAxisMode(yaxis_mode::log);
1214 sdfa_p_values.SetYLimit(_range::high, 1);
1215 sdfa_p_values.SetResult(p_vector);
1216 results.Append(sdfa_p_values);
1217
1218 // Wilks' Lambda result
1219 CMBVector* wilks_lambda_vector = new CMBVector(sdfa_results[1]);
1220 ResultItem sdfa_wilks_lambda;
1221 sdfa_wilks_lambda.SetName("Wilks' Lambda");
1222 sdfa_wilks_lambda.SetType(result_type::vector);
1223 sdfa_wilks_lambda.setXAxisTitle("Constituents, in the order added");
1224 sdfa_wilks_lambda.SetShowTable(true);
1225 sdfa_wilks_lambda.SetAbsoluteValue(true);
1226 sdfa_wilks_lambda.SetYAxisMode(yaxis_mode::log);
1227 sdfa_wilks_lambda.SetYLimit(_range::high, 1);
1228 sdfa_wilks_lambda.SetResult(wilks_lambda_vector);
1229 results.Append(sdfa_wilks_lambda);
1230
1231 // F-test P-Value result
1232 CMBVector* f_test_p_value = new CMBVector(sdfa_results[2]);
1233 ResultItem sdfa_f_test_p_value;
1234 sdfa_f_test_p_value.SetName("F-test P-Value");
1235 sdfa_f_test_p_value.SetType(result_type::vector);
1236 sdfa_f_test_p_value.setXAxisTitle("Constituents, in the order added");
1237 sdfa_f_test_p_value.SetShowTable(true);
1238 sdfa_f_test_p_value.SetAbsoluteValue(true);
1239 sdfa_f_test_p_value.SetYAxisMode(yaxis_mode::log);
1240 sdfa_f_test_p_value.SetYLimit(_range::high, 1);
1241 sdfa_f_test_p_value.SetResult(f_test_p_value);
1242 results.Append(sdfa_f_test_p_value);
1243
1244 return true;
1245}
1246
1247bool Conductor::ExecuteSDFAM(const std::map<std::string, std::string>& arguments)
1248{
1250 rtw->Start();
1251
1252 results.SetName("Multiway Stepwise DFA");
1253
1254 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1255 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
1256
1257 SourceSinkData transformed_data;
1258
1259 if (arguments.at("OM and Size Correct based on target sample") != "")
1260 {
1261 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1262 {
1263 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1264 return false;
1265 }
1266 transformed_data = Data()->CreateCorrectedDataset(
1267 arguments.at("OM and Size Correct based on target sample"),
1268 true,
1269 Data()->GetElementInformation()
1270 ).CreateTracerDataset(exclude_samples, exclude_elements, false);
1271 }
1272 else
1273 {
1274 transformed_data = Data()->CreateTracerDataset(
1275 exclude_samples,
1276 exclude_elements,
1277 false
1278 );
1279 }
1280
1281 if (!CheckNegativeElements(&transformed_data))
1282 return false;
1283
1284 if (arguments.at("Box-cox transformation") == "true")
1285 {
1286 transformed_data = BoxCoxTransformedWithReport(transformed_data);
1287 }
1288
1289 transformed_data.SetProgressReporter(rtw);
1290
1291 std::vector<CMBVector> sdfa_results = transformed_data.StepwiseDiscriminantFunctionAnalysis();
1292
1293 if (sdfa_results[0].size() == 0)
1294 {
1295 host->ShowWarning("Singular matrix in within group scatter matrix!\n");
1296 return false;
1297 }
1298
1299 // Chi-squared P-Values result
1300 CMBVector* p_vector = new CMBVector(sdfa_results[0]);
1301 ResultItem sdfa_p_values;
1302 sdfa_p_values.SetName("Chi-squared P-Values");
1303 sdfa_p_values.SetType(result_type::vector);
1304 sdfa_p_values.setXAxisTitle("Constituents, in the order added");
1305 sdfa_p_values.SetShowTable(true);
1306 sdfa_p_values.SetAbsoluteValue(true);
1307 sdfa_p_values.SetYAxisMode(yaxis_mode::log);
1308 sdfa_p_values.SetYLimit(_range::high, 1);
1309 sdfa_p_values.SetResult(p_vector);
1310 results.Append(sdfa_p_values);
1311
1312 // Selected elements result
1313 ResultItem sdfa_selected;
1314 sdfa_selected.SetName("Elements to be Selected");
1315 sdfa_selected.SetType(result_type::vector);
1316 sdfa_selected.setXAxisTitle("Constituents, in the order added");
1317 sdfa_selected.SetShowTable(true);
1318 sdfa_selected.SetAbsoluteValue(true);
1319 sdfa_selected.SetYAxisMode(yaxis_mode::log);
1320 sdfa_selected.SetYLimit(_range::high, 1);
1321
1322 CMBVector* p_vector_selected = new CMBVector();
1323 std::vector<std::string> selected = p_vector->ExtractUpToMinimum().Labels();
1324
1325 if (arguments.at("Modify the included elements based on the results") == "true")
1326 {
1328 }
1329
1330 for (size_t i = 0; i < selected.size(); i++)
1331 {
1332 p_vector_selected->append(selected[i], p_vector->valueAt(i));
1333 }
1334
1335 sdfa_selected.SetResult(p_vector_selected);
1336 results.Append(sdfa_selected);
1337
1338 // Wilks' Lambda result
1339 CMBVector* wilks_lambda_vector = new CMBVector(sdfa_results[1]);
1340 ResultItem sdfa_wilks_lambda;
1341 sdfa_wilks_lambda.SetName("Wilks' Lambda");
1342 sdfa_wilks_lambda.SetType(result_type::vector);
1343 sdfa_wilks_lambda.setXAxisTitle("Constituents, in the order added");
1344 sdfa_wilks_lambda.SetShowTable(true);
1345 sdfa_wilks_lambda.SetAbsoluteValue(true);
1346 sdfa_wilks_lambda.SetYAxisMode(yaxis_mode::log);
1347 sdfa_wilks_lambda.SetYLimit(_range::high, 1);
1348 sdfa_wilks_lambda.SetResult(wilks_lambda_vector);
1349 results.Append(sdfa_wilks_lambda);
1350
1351 // F-test P-Value result
1352 CMBVector* f_test_p_value = new CMBVector(sdfa_results[2]);
1353 ResultItem sdfa_f_test_p_value;
1354 sdfa_f_test_p_value.SetName("F-test P-Value");
1355 sdfa_f_test_p_value.SetType(result_type::vector);
1356 sdfa_f_test_p_value.setXAxisTitle("Constituents, in the order added");
1357 sdfa_f_test_p_value.SetShowTable(true);
1358 sdfa_f_test_p_value.SetAbsoluteValue(true);
1359 sdfa_f_test_p_value.SetYAxisMode(yaxis_mode::log);
1360 sdfa_f_test_p_value.SetYLimit(_range::high, 1);
1361 sdfa_f_test_p_value.SetResult(f_test_p_value);
1362 results.Append(sdfa_f_test_p_value);
1363
1364 // Discriminant scores and eigenvectors for the selected constituents (the
1365 // multi-way DFA of Other Statistical Tools, run on this step's selection)
1366 if (selected.size() >= 2)
1367 {
1368 SourceSinkData selected_data = transformed_data;
1369 selected_data.IncludeExcludeElementsBasedOn(selected);
1370 selected_data = selected_data.CreateTracerDataset(false, true, false);
1371 DFA_result selected_dfa = selected_data.DiscriminantFunctionAnalysis();
1372 if (selected_dfa.eigen_vectors.size() > 0)
1373 {
1374 ResultItem dfa_projected;
1375 dfa_projected.SetName("Multiway Projected Elemental Profiles (selected constituents)");
1377 dfa_projected.SetShowTable(true);
1378 dfa_projected.SetShowGraph(true);
1379 dfa_projected.SetYAxisMode(yaxis_mode::normal);
1380 dfa_projected.SetResult(new CMBVectorSetSet(selected_dfa.multi_projected));
1381 results.Append(dfa_projected);
1382
1383 ResultItem dfa_eigen_vectors;
1384 dfa_eigen_vectors.SetName("Eigen vectors (selected constituents)");
1385 dfa_eigen_vectors.SetType(result_type::vectorset);
1386 dfa_eigen_vectors.SetShowTable(true);
1387 dfa_eigen_vectors.SetShowGraph(true);
1388 dfa_eigen_vectors.SetYAxisMode(yaxis_mode::normal);
1389 dfa_eigen_vectors.setYAxisTitle("Weight");
1390 dfa_eigen_vectors.SetResult(new CMBVectorSet(selected_dfa.eigen_vectors));
1391 results.Append(dfa_eigen_vectors);
1392 }
1393
1394 // How well the selected constituents classify the source samples:
1395 // leave-one-out linear discriminant classification (as Sed_SAT 1.0)
1396 ResultItem confusion;
1397 confusion.SetName("Confusion matrix (selected constituents, leave-one-out)");
1398 confusion.SetType(result_type::matrix);
1399 confusion.SetShowAsString(false);
1400 confusion.SetShowTable(true);
1401 confusion.SetShowGraph(false);
1402 confusion.setTableTitle("Confusion matrix: rows are the true source groups, columns the groups assigned");
1403 confusion.SetResult(new CMBMatrix(selected_data.DFAConfusionMatrix()));
1404 results.Append(confusion);
1405 }
1406
1407 return true;
1408}
1409
1410bool Conductor::ExecuteSDFAOnevsRest(const std::map<std::string, std::string>& arguments)
1411{
1413 rtw->Start();
1414
1415 results.SetName("Stepwise DFA between " + arguments.at("Source group") + "& the rest");
1416
1417 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1418 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
1419
1420 SourceSinkData transformed_data;
1421
1422 if (arguments.at("OM and Size Correct based on target sample") != "")
1423 {
1424 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1425 {
1426 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1427 return false;
1428 }
1429 transformed_data = Data()->CreateCorrectedDataset(
1430 arguments.at("OM and Size Correct based on target sample"),
1431 true,
1432 Data()->GetElementInformation()
1433 ).CreateTracerDataset(exclude_samples, exclude_elements, false);
1434 }
1435 else
1436 {
1437 transformed_data = Data()->CreateTracerDataset(
1438 exclude_samples,
1439 exclude_elements,
1440 false
1441 );
1442 }
1443
1444 if (!CheckNegativeElements(&transformed_data))
1445 return false;
1446
1447 if (arguments.at("Box-cox transformation") == "true")
1448 {
1449 transformed_data = BoxCoxTransformedWithReport(transformed_data);
1450 }
1451
1452 transformed_data.SetProgressReporter(rtw);
1453
1454 std::vector<CMBVector> sdfa_results = transformed_data.StepwiseDiscriminantFunctionAnalysis(
1455 arguments.at("Source group")
1456 );
1457
1458 if (sdfa_results[0].size() == 0)
1459 {
1460 host->ShowWarning("Singular matrix in within group scatter matrix!\n");
1461 return false;
1462 }
1463
1464 // Chi-squared P-Values result
1465 CMBVector* p_vector = new CMBVector(sdfa_results[0]);
1466 ResultItem sdfa_p_values;
1467 sdfa_p_values.SetName("Chi-squared P-Values");
1468 sdfa_p_values.SetType(result_type::vector);
1469 sdfa_p_values.setXAxisTitle("Constituents, in the order added");
1470 sdfa_p_values.SetShowTable(true);
1471 sdfa_p_values.SetAbsoluteValue(true);
1472 sdfa_p_values.SetYAxisMode(yaxis_mode::log);
1473 sdfa_p_values.SetYLimit(_range::high, 1);
1474 sdfa_p_values.SetResult(p_vector);
1475 results.Append(sdfa_p_values);
1476
1477 // Wilks' Lambda result
1478 CMBVector* wilks_lambda_vector = new CMBVector(sdfa_results[1]);
1479 ResultItem sdfa_wilks_lambda;
1480 sdfa_wilks_lambda.SetName("Wilks' Lambda");
1481 sdfa_wilks_lambda.SetType(result_type::vector);
1482 sdfa_wilks_lambda.setXAxisTitle("Constituents, in the order added");
1483 sdfa_wilks_lambda.SetShowTable(true);
1484 sdfa_wilks_lambda.SetAbsoluteValue(true);
1485 sdfa_wilks_lambda.SetYAxisMode(yaxis_mode::log);
1486 sdfa_wilks_lambda.SetYLimit(_range::high, 1);
1487 sdfa_wilks_lambda.SetResult(wilks_lambda_vector);
1488 results.Append(sdfa_wilks_lambda);
1489
1490 // F-test P-Value result
1491 CMBVector* f_test_p_value = new CMBVector(sdfa_results[2]);
1492 ResultItem sdfa_f_test_p_value;
1493 sdfa_f_test_p_value.SetName("F-test P-Value");
1494 sdfa_f_test_p_value.SetType(result_type::vector);
1495 sdfa_f_test_p_value.setXAxisTitle("Constituents, in the order added");
1496 sdfa_f_test_p_value.SetShowTable(true);
1497 sdfa_f_test_p_value.SetAbsoluteValue(true);
1498 sdfa_f_test_p_value.SetYAxisMode(yaxis_mode::log);
1499 sdfa_f_test_p_value.SetYLimit(_range::high, 1);
1500 sdfa_f_test_p_value.SetResult(f_test_p_value);
1501 results.Append(sdfa_f_test_p_value);
1502
1503 return true;
1504}
1505
1506bool Conductor::ExecuteKolmogorovSmirnov(const std::map<std::string, std::string>& arguments)
1507{
1508 results.SetName("Kolmogorov–Smirnov statististics for " + arguments.at("Source/Target group"));
1509
1510 ResultItem ks_item;
1511 ks_item.SetName("Kolmogorov–Smirnov statististics for " + arguments.at("Source/Target group"));
1514
1516 if (arguments.at("Distribution") == "Normal")
1517 {
1519 }
1520 else if (arguments.at("Distribution") == "Lognormal")
1521 {
1523 }
1524
1525 CMBVector* ks_output = new CMBVector(
1526 Data()->at(arguments.at("Source/Target group")).CalculateKolmogorovSmirnovStatistics(dist)
1527 );
1528
1529 ks_item.SetShowTable(true);
1530 ks_item.SetResult(ks_output);
1531 results.Append(ks_item);
1532
1533 return true;
1534}
1535
1536bool Conductor::ExecuteKolmogorovSmirnovIndividual(const std::map<std::string, std::string>& arguments)
1537{
1538 results.SetName("Kolmogorov–Smirnov statististics for constituent " +
1539 arguments.at("Constituent") + " in group " +
1540 arguments.at("Source/Target group"));
1541
1542 ResultItem ks_item;
1543 ks_item.SetName("Kolmogorov–Smirnov statististics for constituent " +
1544 arguments.at("Constituent") + " in group " +
1545 arguments.at("Source/Target group"));
1547
1549 if (arguments.at("Distribution") == "Normal")
1550 {
1552 }
1553 else if (arguments.at("Distribution") == "Lognormal")
1554 {
1556 }
1557
1558 // A log-normal CDF needs positive values; with zero or negative ones
1559 // (e.g. delta 13C) the observed curve could not be drawn
1560 ConcentrationSet* distribution = Data()->at(arguments.at("Source/Target group"))
1561 .GetElementDistribution(arguments.at("Constituent"));
1562 if (distribution == nullptr)
1563 {
1564 host->ShowWarning("'" + arguments.at("Constituent") + "' was not found in group '" +
1565 arguments.at("Source/Target group") + "'.");
1566 return false;
1567 }
1568 if (dist == distribution_type::lognormal && distribution->GetMinimum() <= 0)
1569 {
1570 host->ShowWarning("'" + arguments.at("Constituent") + "' in group '" + arguments.at("Source/Target group") +
1571 "' has zero or negative values, so it cannot be compared with a log-normal distribution.");
1572 return false;
1573 }
1574
1575 CMBTimeSeriesSet* ks_output = new CMBTimeSeriesSet(distribution->CreateCDFComparison(dist));
1576
1577 ks_item.SetResult(ks_output);
1578 ks_item.SetShowTable(false);
1579 results.Append(ks_item);
1580
1581 return true;
1582}
1583
1584bool Conductor::ExecuteCMBBayesianBatch(const std::map<std::string, std::string>& given_arguments)
1585{
1586 // Every sample uses the same seed, which is recorded in the results name
1587 std::map<std::string, std::string> arguments = given_arguments;
1588 std::uint64_t seed = 0;
1589 if (!ResolveRandomSeed(arguments, seed))
1590 return false;
1591
1592 if (arguments.at("Apply size and organic matter correction") == "true")
1593 {
1594 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1595 {
1596 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1597 return false;
1598 }
1599 }
1600
1601 // Initialize MCMC object
1602 MCMC = std::make_unique<CMCMC<SourceSinkData>>();
1603
1604 // Create progress window with 3 charts for monitoring (with batch mode enabled)
1605 ScopedProgressReporter rtw(host, 3, true);
1606 rtw->SetTitle("Acceptance Rate", 0);
1607 rtw->SetTitle("Perturbation Factor", 1);
1608 rtw->SetTitle("Log posterior value", 2);
1609 rtw->SetYAxisTitle("Acceptance Rate", 0);
1610 rtw->SetYAxisTitle("Perturbation Factor", 1);
1611 rtw->SetYAxisTitle("Log posterior value", 2);
1612 rtw->Start();
1613
1614 // Execute batch MCMC sampling
1615 std::vector<std::string> failed_writes;
1616 CMBMatrix* contributions = new CMBMatrix(
1617 Data()->MCMC_Batch(
1618 arguments,
1619 MCMC.get(),
1620 rtw,
1621 workingfolder.toStdString(),
1622 &failed_writes
1623 )
1624 );
1625
1626 if (!failed_writes.empty())
1627 {
1628 std::string message = "Some per-sample result files could not be written:\n";
1629 for (const std::string& failure : failed_writes)
1630 message += failure + "\n";
1631 host->ShowWarning(message);
1632 }
1633
1634 results.SetName("CMB Bayesian-Batch (random seed " + std::to_string(seed) + ")");
1635
1636 // Create result item for contribution range matrix
1637 ResultItem contribution_matrix_item;
1638 contribution_matrix_item.SetName("Contribution Range Matrix");
1639 contribution_matrix_item.SetType(result_type::matrix);
1640 contribution_matrix_item.SetYAxisMode(yaxis_mode::normal);
1641 contribution_matrix_item.SetResult(contributions);
1642 contribution_matrix_item.SetShowTable(true);
1643 results.Append(contribution_matrix_item);
1644
1645 rtw->SetProgress(1);
1646
1647 return true;
1648}
1649
1650bool Conductor::ExecuteTestCMBBayesian(const std::map<std::string, std::string>& given_arguments)
1651{
1652 std::map<std::string, std::string> arguments = given_arguments;
1653 std::uint64_t seed = 0;
1654 if (!ResolveRandomSeed(arguments, seed))
1655 return false;
1656
1657 results.SetName("MCMC results for testing MCMC (random seed " + std::to_string(seed) + ")");
1658
1659 // Create MCMC samples result item
1663 mcmc_samples.SetName("MCMC samples for testing MCMC'");
1664
1666
1667 // Initialize MCMC for testing with TestMCMC model
1668 CMCMC<TestMCMC>* mcmc_for_testing = new CMCMC<TestMCMC>();
1669 TestMCMC testing_model;
1670 mcmc_for_testing->Model = &testing_model;
1671
1672 // Create progress window with 3 charts
1674 rtw->SetTitle("Acceptance Rate", 0);
1675 rtw->SetTitle("Perturbation Factor", 1);
1676 rtw->SetTitle("Log posterior value", 2);
1677 rtw->SetYAxisTitle("Acceptance Rate", 0);
1678 rtw->SetYAxisTitle("Perturbation Factor", 1);
1679 rtw->SetYAxisTitle("Log posterior value", 2);
1680 rtw->Start();
1681
1682 // Set up parameter bounds for test model
1683 std::vector<double> mins;
1684 std::vector<double> maxs;
1685 mins.push_back(0.1);
1686 mins.push_back(1);
1687 maxs.push_back(1.0);
1688 maxs.push_back(10);
1689
1690 testing_model.InitializeParametersObservations(mins, maxs);
1691
1692 // Configure MCMC parameters
1693 mcmc_for_testing->SetProperty("number_of_samples", arguments.at("Number of samples"));
1694 mcmc_for_testing->SetProperty("number_of_chains", arguments.at("Number of chains"));
1695 mcmc_for_testing->SetProperty("number_of_burnout_samples", arguments.at("Samples to be discarded (burnout)"));
1696 if (arguments.count("Correlated proposal") > 0)
1697 mcmc_for_testing->SetProperty("covariance_proposal", arguments.at("Correlated proposal"));
1698
1699 mcmc_for_testing->SetRandomSeed(seed);
1700 mcmc_for_testing->initialize(samples, true);
1701
1702 // Determine output folder path
1703 std::string folder_path;
1704 if (!QString::fromStdString(arguments.at("samples_file_name")).contains("/"))
1705 {
1706 folder_path = workingfolder.toStdString() + "/";
1707 }
1708
1709 // Execute MCMC sampling
1710 mcmc_for_testing->step(
1711 QString::fromStdString(arguments.at("Number of chains")).toInt(),
1712 QString::fromStdString(arguments.at("Number of samples")).toInt(),
1713 folder_path + arguments.at("samples_file_name"),
1714 samples,
1715 rtw
1716 );
1717
1718 mcmc_samples.SetResult(samples);
1719 results.Append(mcmc_samples);
1720
1721 // Generate posterior distributions from samples
1722 ResultItem distribution_result_item;
1723 CMBTimeSeriesSet* dists = new CMBTimeSeriesSet();
1724 *dists = samples->distribution(
1725 100,
1726 QString::fromStdString(arguments.at("Samples to be discarded (burnout)")).toInt()
1727 );
1728
1729 distribution_result_item.SetName("Posterior Distributions");
1730 distribution_result_item.SetShowAsString(false);
1731 distribution_result_item.SetType(result_type::distribution);
1732 distribution_result_item.SetResult(dists);
1733 results.Append(distribution_result_item);
1734
1735 // Clean up (TestMCMC uses raw pointer)
1736 delete mcmc_for_testing;
1737
1738 return true;
1739}
1740
1741bool Conductor::ExecuteDistributionFitting(const std::map<std::string, std::string>& arguments)
1742{
1743 results.SetName("Distribution fitting results for '" + arguments.at("Constituent") +
1744 "' in '" + arguments.at("Source/Target group"));
1745
1746 // Prepare result items for PDF and CDF
1747 ResultItem distribution_item;
1748 distribution_item.SetName("Fitted PDF for '" + arguments.at("Constituent") +
1749 "' in '" + arguments.at("Source/Target group"));
1750 distribution_item.SetShowAsString(false);
1752 distribution_item.SetYAxisMode(yaxis_mode::normal);
1753 distribution_item.setXAxisTitle("Value");
1754 distribution_item.setYAxisTitle("PDF");
1755
1756 ResultItem cumulative_distribution_item;
1757 cumulative_distribution_item.SetName("Fitted CDF for '" + arguments.at("Constituent") +
1758 "' in '" + arguments.at("Source/Target group"));
1759 cumulative_distribution_item.SetShowAsString(false);
1760 cumulative_distribution_item.SetType(result_type::timeseries_set_first_symbol);
1761 cumulative_distribution_item.SetYAxisMode(yaxis_mode::normal);
1762 cumulative_distribution_item.setXAxisTitle("Value");
1763 cumulative_distribution_item.setYAxisTitle("CDF");
1764
1765 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1766
1767 SourceSinkData transformed_data;
1768
1769 if (arguments.at("OM and Size Correct based on target sample") != "")
1770 {
1771 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1772 {
1773 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1774 return false;
1775 }
1776 transformed_data = Data()->CreateCorrectedDataset(
1777 arguments.at("OM and Size Correct based on target sample"),
1778 true,
1779 Data()->GetElementInformation()
1780 ).CreateCorrectedAndFilteredDataset(exclude_samples, false, false);
1781 }
1782 else
1783 {
1784 transformed_data = Data()->CreateCorrectedAndFilteredDataset(exclude_samples, false, false);
1785 }
1786
1787 if (!CheckNegativeElements(&transformed_data))
1788 return false;
1789
1790 if (arguments.at("Box-cox transformation") == "true")
1791 {
1792 transformed_data = BoxCoxTransformedWithReport(transformed_data);
1793 }
1794
1795 const std::string& group = arguments.at("Source/Target group");
1796 const std::string& constituent = arguments.at("Constituent");
1797 const bool box_cox = (arguments.at("Box-cox transformation") == "true");
1798
1799 if (transformed_data.count(group) == 0)
1800 {
1801 host->ShowWarning("Group '" + group + "' was not found in the data.");
1802 return false;
1803 }
1804 ConcentrationSet* distribution = transformed_data.at(group).GetElementDistribution(constituent);
1805 if (distribution == nullptr)
1806 {
1807 host->ShowWarning("Constituent '" + constituent + "' was not found in group '" + group + "'.");
1808 return false;
1809 }
1810 if (distribution->size() < 2)
1811 {
1812 host->ShowWarning("Distribution fitting needs at least two samples of '" + constituent +
1813 "' in group '" + group + "'; there are " + std::to_string(distribution->size()) + ".");
1814 return false;
1815 }
1816 if (!distribution->CanFitDistribution())
1817 {
1818 host->ShowWarning("All values of '" + constituent + "' in group '" + group +
1819 "' are equal, so no distribution can be fitted.");
1820 return false;
1821 }
1822 if (!box_cox && distribution->GetMinimum() <= 0)
1823 {
1824 host->ShowWarning("'" + constituent + "' in group '" + group +
1825 "' has zero or negative values, so a log-normal distribution cannot be fitted.");
1826 return false;
1827 }
1828
1829 // Fit normal distribution
1830 CMBTimeSeriesSet fitted_normal = distribution->CreateFittedDistribution(distribution_type::normal);
1831
1832 // Fit lognormal distribution (only if not Box-Cox transformed)
1833 CMBTimeSeriesSet fitted_lognormal;
1834 if (!box_cox)
1835 {
1836 fitted_lognormal = distribution->CreateFittedDistribution(distribution_type::lognormal);
1837 }
1838
1839 // Create CDF comparisons for normal
1840 CMBTimeSeriesSet observed_fitted_normal_cdf = distribution->CreateCDFComparison(distribution_type::normal);
1841
1842 // Create CDF comparisons for lognormal (only if not Box-Cox transformed)
1843 CMBTimeSeriesSet observed_fitted_lognormal_cdf;
1844 if (!box_cox)
1845 {
1846 observed_fitted_lognormal_cdf = distribution->CreateCDFComparison(distribution_type::lognormal);
1847 }
1848
1849 // Every series used below must exist; report rather than throw if not
1850 bool complete = fitted_normal.Contains("Observed") && fitted_normal.Contains("Fitted") &&
1851 observed_fitted_normal_cdf.Contains("Observed") && observed_fitted_normal_cdf.Contains("Fitted");
1852 if (!box_cox)
1853 complete = complete && fitted_lognormal.Contains("Fitted") && observed_fitted_lognormal_cdf.Contains("Fitted");
1854 if (!complete)
1855 {
1856 host->ShowWarning("The distributions of '" + constituent + "' in group '" + group + "' could not be fitted.");
1857 return false;
1858 }
1859
1860 // Build PDF result. Each series is added under its final name: append()
1861 // refuses a name that is already in the set, so adding the two "Fitted"
1862 // series under their own names would silently drop the second one.
1864 pdf->append(fitted_normal["Observed"], "Samples");
1865 pdf->append(fitted_normal["Fitted"], "Normal");
1866 if (!box_cox)
1867 {
1868 pdf->append(fitted_lognormal["Fitted"], "Log-normal");
1869 }
1870
1871 // Build CDF result
1873 cdf->append(observed_fitted_normal_cdf["Observed"], "Observed");
1874 cdf->append(observed_fitted_normal_cdf["Fitted"], "Normal");
1875 if (!box_cox)
1876 {
1877 cdf->append(observed_fitted_lognormal_cdf["Fitted"], "Log-normal");
1878 }
1879
1880 distribution_item.SetResult(pdf);
1881 cumulative_distribution_item.SetResult(cdf);
1882
1883 results.Append(distribution_item);
1884 results.Append(cumulative_distribution_item);
1885
1886 return true;
1887}
1888
1889// Reads the bracket test's "Tolerance (%)" as a fraction; blank or absent is 0
1890static bool ReadBracketTolerance(const std::map<std::string, std::string>& arguments,
1891 AnalysisHost* host, double& tolerance)
1892{
1893 tolerance = 0;
1894 auto it = arguments.find("Tolerance (%)");
1895 if (it == arguments.end() || QString::fromStdString(it->second).trimmed().isEmpty())
1896 return true;
1897 double percent = 0;
1898 QString reason;
1899 if (!parseNumericValue(QString::fromStdString(it->second), percent, reason) || percent < 0)
1900 {
1901 host->ShowWarning("The tolerance must be a number of percent, 0 or more.\n");
1902 return false;
1903 }
1904 tolerance = percent / 100.0;
1905 return true;
1906}
1907
1908bool Conductor::ExecuteBracketingAnalysis(const std::map<std::string, std::string>& arguments)
1909{
1910 results.SetName("Bracketing analysis for sample '" + arguments.at("Sample") + "'");
1911
1912 ResultItem bracketing_result_item;
1913 bracketing_result_item.SetName("Bracketing results");
1914 bracketing_result_item.SetType(result_type::vector);
1915 bracketing_result_item.SetShowTable(true);
1916 bracketing_result_item.SetShowGraph(false);
1917
1918 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1919 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
1920 bool correct_based_on_size_and_organic_matter = (arguments.at("Correct based on size and organic matter") == "true");
1921 double tolerance = 0;
1922 if (!ReadBracketTolerance(arguments, host, tolerance))
1923 return false;
1924
1925 SourceSinkData transformed_data = Data()->CreateTracerDataset(
1926 exclude_samples,
1927 exclude_elements,
1928 correct_based_on_size_and_organic_matter,
1929 arguments.at("Sample")
1930 );
1931
1932 if (!CheckNegativeElements(&transformed_data))
1933 return false;
1934
1935 CMBVector* bracketing_result = new CMBVector(
1936 transformed_data.BracketTest(arguments.at("Sample"), false, tolerance)
1937 );
1938
1939 bracketing_result->SetBooleanValue(true);
1940 bracketing_result_item.SetResult(bracketing_result);
1941 results.Append(bracketing_result_item);
1942
1943 return true;
1944}
1945
1946bool Conductor::ExecuteBracketingAnalysisBatch(const std::map<std::string, std::string>& arguments)
1947{
1948 results.SetName("Bracketing analysis");
1949
1950 ResultItem bracketing_result_item;
1951 bracketing_result_item.SetName("Bracketing results");
1952 bracketing_result_item.SetType(result_type::matrix);
1953 bracketing_result_item.SetShowTable(true);
1954 bracketing_result_item.SetShowGraph(false);
1955 bracketing_result_item.SetShowAsString(false);
1956
1957 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
1958 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
1959 bool correct_based_on_size_and_organic_matter = (arguments.at("Correct based on size and organic matter") == "true");
1960 double tolerance = 0;
1961 if (!ReadBracketTolerance(arguments, host, tolerance))
1962 return false;
1963
1965 return false;
1966
1967 if (correct_based_on_size_and_organic_matter)
1968 {
1969 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
1970 {
1971 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
1972 return false;
1973 }
1974 }
1975
1976 CMBMatrix* bracketing_result = new CMBMatrix(
1977 Data()->BracketTest(
1978 correct_based_on_size_and_organic_matter,
1979 exclude_elements,
1980 exclude_samples,
1981 tolerance
1982 )
1983 );
1984
1985 bracketing_result->SetBooleanValue(true);
1986 bracketing_result_item.SetResult(bracketing_result);
1987 results.Append(bracketing_result_item);
1988
1989 return true;
1990}
1991
1992bool Conductor::ExecuteBoxCox(const std::map<std::string, std::string>& arguments)
1993{
1994 results.SetName("Box-Cox parameter for '" + arguments.at("Source/Target group") + "'");
1995
1996 ResultItem boxcox_result_item;
1997 boxcox_result_item.SetName("Box-Cox parameters");
1998 boxcox_result_item.SetType(result_type::vector);
1999 boxcox_result_item.SetShowTable(true);
2000 boxcox_result_item.SetShowGraph(true);
2001 boxcox_result_item.SetYAxisMode(yaxis_mode::normal);
2002
2003 ReportBoxCoxSkips(*Data(), arguments.at("Source/Target group"), "their lambda is shown as 1");
2004
2005 CMBVector* boxcox_params = new CMBVector(
2006 Data()->at(arguments.at("Source/Target group")).CalculateBoxCoxParameters()
2007 );
2008
2009 boxcox_result_item.SetResult(boxcox_params);
2010 results.Append(boxcox_result_item);
2011
2012 return true;
2013}
2014
2015bool Conductor::ExecuteOutlierAnalysis(const std::map<std::string, std::string>& arguments)
2016{
2017 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
2018 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
2019
2021 exclude_samples,
2022 exclude_elements,
2023 false
2024 );
2025
2026 if (!CheckNegativeElements(&transformed_data))
2027 return false;
2028
2029 results.SetName("Outlier analysis for '" + arguments.at("Source/Target group") + "'");
2030
2031 ResultItem outlier_result_item;
2032 outlier_result_item.SetName("Outlier Analysis");
2033 outlier_result_item.SetType(result_type::matrix);
2034 outlier_result_item.SetShowAsString(false);
2035 outlier_result_item.SetShowTable(true);
2036 outlier_result_item.SetShowGraph(false);
2037
2038 double threshold = QString::fromStdString(arguments.at("Threshold")).toDouble();
2039
2040 ReportBoxCoxSkips(transformed_data, arguments.at("Source/Target group"),
2041 "their scores are computed from the untransformed values");
2042
2043 CMBMatrix* outlier_matrix = new CMBMatrix(
2044 transformed_data.at(arguments.at("Source/Target group")).DetectOutliers(-threshold, threshold)
2045 );
2046
2047 outlier_matrix->SetLimit(_range::high, threshold);
2048 outlier_matrix->SetLimit(_range::low, -threshold);
2049
2050 outlier_result_item.SetResult(outlier_matrix);
2051 results.Append(outlier_result_item);
2052
2053 return true;
2054}
2055
2056bool Conductor::ExecuteEDP(const std::map<std::string, std::string>& arguments)
2057{
2058 results.SetName("Two-way element discriminant power between '" +
2059 arguments.at("Source/Target group I") + "' and '" +
2060 arguments.at("Source/Target group II") + "'");
2061
2062 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
2063
2064 SourceSinkData transformed_data;
2065
2066 if (arguments.at("OM and Size Correct based on target sample") != "")
2067 {
2068 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2069 {
2070 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2071 return false;
2072 }
2073 transformed_data = Data()->CreateCorrectedDataset(
2074 arguments.at("OM and Size Correct based on target sample"),
2075 true,
2076 Data()->GetElementInformation()
2077 ).CreateTracerDataset(exclude_samples, false, false);
2078 }
2079 else
2080 {
2081 transformed_data = Data()->CreateTracerDataset(exclude_samples, false, false);
2082 }
2083
2084 if (!CheckNegativeElements(&transformed_data))
2085 return false;
2086
2087 if (arguments.at("Box-cox transformation") == "true")
2088 {
2089 transformed_data = BoxCoxTransformedWithReport(transformed_data);
2090 }
2091
2092 // Discriminant difference to standard deviation ratio
2093 ResultItem edp_result_std;
2094 edp_result_std.SetName("Discreminant difference to standard deviation ratio");
2096 edp_result_std.SetShowAsString(false);
2097 edp_result_std.SetShowTable(true);
2098 edp_result_std.SetShowGraph(true);
2099
2100 Elemental_Profile* edp_profile_set = new Elemental_Profile(
2101 transformed_data.DifferentiationPower(
2102 arguments.at("Source/Target group I"),
2103 arguments.at("Source/Target group II"),
2104 false
2105 )
2106 );
2107
2108 edp_result_std.SetYAxisMode(yaxis_mode::normal);
2109 edp_result_std.setYAxisTitle("Discrimination power");
2110 edp_result_std.SetResult(edp_profile_set);
2111 edp_result_std.setXAxisTitle("Element");
2112 edp_result_std.setYAxisTitle("Standard deviation to mean ratio");
2113 results.Append(edp_result_std);
2114
2115 // Discriminant fraction
2116 ResultItem edp_result_percent;
2117 edp_result_percent.SetName("Discriminat fraction");
2119 edp_result_percent.SetShowAsString(false);
2120 edp_result_percent.setYAxisTitle("Percentage discriminated");
2121 edp_result_percent.SetShowTable(true);
2122 edp_result_percent.SetShowGraph(true);
2123
2124 Elemental_Profile* edp_profile_set_percent = new Elemental_Profile(
2125 transformed_data.DifferentiationPower_Percentage(
2126 arguments.at("Source/Target group I"),
2127 arguments.at("Source/Target group II")
2128 )
2129 );
2130
2131 edp_result_percent.SetYAxisMode(yaxis_mode::normal);
2132 edp_result_percent.SetYLimit(_range::high, 1);
2133 edp_result_percent.SetResult(edp_profile_set_percent);
2134 edp_result_percent.setXAxisTitle("Element");
2135 edp_result_percent.setYAxisTitle("Discriminant fraction");
2136 results.Append(edp_result_percent);
2137
2138 // Discriminant p-value
2139 ResultItem edp_result_p_value;
2140 edp_result_p_value.SetName("Discriminat p-value");
2142 edp_result_p_value.SetShowAsString(false);
2143 edp_result_p_value.setYAxisTitle("p-Value");
2144 edp_result_p_value.SetShowTable(true);
2145 edp_result_p_value.SetShowGraph(true);
2146
2147 Elemental_Profile* edp_profile_set_p_value = new Elemental_Profile(
2148 transformed_data.t_TestPValue(
2149 arguments.at("Source/Target group I"),
2150 arguments.at("Source/Target group II"),
2151 false
2152 )
2153 );
2154
2155 edp_result_p_value.SetYAxisMode(yaxis_mode::normal);
2156 edp_result_p_value.SetYLimit(_range::high, 1);
2157 edp_result_p_value.SetResult(edp_profile_set_p_value);
2158 edp_profile_set_p_value->SetLimit(_range::high, aquiutils::atof(arguments.at("P-value threshold")));
2159 edp_profile_set_p_value->SetLimit(_range::low, 0);
2160 edp_result_p_value.setXAxisTitle("Element");
2161 edp_result_p_value.setYAxisTitle("Discriminant fraction");
2162 results.Append(edp_result_p_value);
2163
2164 return true;
2165}
2166
2167bool Conductor::ExecuteEDPM(const std::map<std::string, std::string>& arguments)
2168{
2169 bool include_target = (arguments.at("Include target samples") == "true");
2170 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
2171
2172 SourceSinkData transformed_data;
2173
2174 if (arguments.at("OM and Size Correct based on target sample") != "")
2175 {
2176 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2177 {
2178 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2179 return false;
2180 }
2181 transformed_data = Data()->CreateCorrectedDataset(
2182 arguments.at("OM and Size Correct based on target sample"),
2183 true,
2184 Data()->GetElementInformation()
2185 ).CreateTracerDataset(exclude_samples, false, false);
2186 }
2187 else
2188 {
2189 transformed_data = Data()->CreateTracerDataset(exclude_samples, false, false);
2190 }
2191
2192 if (!CheckNegativeElements(&transformed_data))
2193 return false;
2194
2195 if (arguments.at("Box-cox transformation") == "true")
2196 {
2197 transformed_data = BoxCoxTransformedWithReport(transformed_data);
2198 }
2199
2200 // The multi-way form has no group arguments (it used to read two that do
2201 // not exist, which closed the program)
2202 results.SetName("Multi-way element discriminant power");
2203
2204 // Multi-way discriminant difference to standard deviation ratio
2205 ResultItem edp_result_std;
2206 edp_result_std.SetName("Multi-way discreminant difference to standard deviation ratio");
2208 edp_result_std.SetShowAsString(true);
2209 edp_result_std.SetShowTable(true);
2210 edp_result_std.SetShowGraph(true);
2211
2212 Elemental_Profile_Set* edp_profile_set = new Elemental_Profile_Set(
2213 transformed_data.DifferentiationPower(false, include_target)
2214 );
2215
2216 edp_result_std.SetYAxisMode(yaxis_mode::normal);
2217 edp_result_std.setYAxisTitle("Discrimination power");
2218 edp_result_std.SetResult(edp_profile_set);
2219 results.Append(edp_result_std);
2220
2221 // Multi-way discriminant fraction
2222 ResultItem edp_result_percent;
2223 edp_result_percent.SetName("Multi-way discriminat fraction");
2224 edp_result_percent.SetType(result_type::elemental_profile_set);
2225 edp_result_percent.SetShowAsString(true);
2226 edp_result_percent.setYAxisTitle("Percentage discriminated");
2227 edp_result_percent.SetShowTable(true);
2228 edp_result_percent.SetShowGraph(true);
2229
2230 Elemental_Profile_Set* edp_profile_set_percent = new Elemental_Profile_Set(
2231 transformed_data.DifferentiationPower_Percentage(include_target)
2232 );
2233
2234 edp_result_percent.SetYAxisMode(yaxis_mode::normal);
2235 edp_result_percent.SetYLimit(_range::high, 1);
2236 edp_result_percent.SetResult(edp_profile_set_percent);
2237 results.Append(edp_result_percent);
2238
2239 // Multi-way discriminant p-value
2240 ResultItem edp_p_value;
2241 edp_p_value.SetName("Multi-way discriminat p-value");
2243 edp_p_value.SetShowAsString(true);
2244 edp_p_value.setYAxisTitle("p-Value");
2245 edp_p_value.SetShowTable(true);
2246 edp_p_value.SetShowGraph(true);
2247
2248 Elemental_Profile_Set* edp_profile_set_p_value = new Elemental_Profile_Set(
2249 transformed_data.DifferentiationPower_P_value(include_target)
2250 );
2251
2252 edp_p_value.SetYAxisMode(yaxis_mode::normal);
2253 edp_p_value.SetYLimit(_range::high, 1);
2254 edp_p_value.SetResult(edp_profile_set_p_value);
2255 edp_profile_set_p_value->SetLimit(_range::high, aquiutils::atof(arguments.at("P-value threshold")));
2256 edp_profile_set_p_value->SetLimit(_range::low, 0);
2257 results.Append(edp_p_value);
2258
2259 return true;
2260}
2261
2262bool Conductor::ExecuteANOVA(const std::map<std::string, std::string>& arguments)
2263{
2264 bool log_transformation = (arguments.at("Log Transformation") == "true");
2265 bool exclude_samples = (arguments.at("Use only selected samples") == "true");
2266 bool exclude_elements = (arguments.at("Use only selected elements") == "true");
2267
2268 // The two "Use only selected" options were read and then ignored: the
2269 // selected samples were always used and every element was kept
2270 SourceSinkData transformed_data;
2271
2272 if (arguments.at("OM and Size Correct based on target sample") != "")
2273 {
2274 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2275 {
2276 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2277 return false;
2278 }
2279 transformed_data = Data()->CreateCorrectedDataset(
2280 arguments.at("OM and Size Correct based on target sample"),
2281 true,
2282 Data()->GetElementInformation()
2283 ).CreateTracerDataset(exclude_samples, exclude_elements, false);
2284 }
2285 else
2286 {
2287 transformed_data = Data()->CreateTracerDataset(exclude_samples, exclude_elements, false);
2288 }
2289
2290 if (!CheckNegativeElements(&transformed_data))
2291 return false;
2292
2293 if (arguments.at("Box-cox transformation") == "true")
2294 {
2295 transformed_data = BoxCoxTransformedWithReport(transformed_data);
2296 log_transformation = false;
2297 }
2298
2299 results.SetName("ANOVA analysis");
2300
2301 ResultItem anova_results;
2302 anova_results.SetName("ANOVA");
2303 anova_results.SetType(result_type::vector);
2304 anova_results.SetShowAsString(true);
2305 anova_results.SetShowTable(true);
2306 anova_results.SetShowGraph(true);
2307
2308 CMBVector* p_values = new CMBVector(transformed_data.ANOVA(log_transformation));
2309
2310 p_values->SetLimit(_range::high, aquiutils::atof(arguments.at("P-value threshold")));
2311 p_values->SetLimit(_range::low, 0);
2312
2313 anova_results.SetYAxisMode(yaxis_mode::normal);
2314 anova_results.SetResult(p_values);
2315 anova_results.setYAxisTitle("P-value");
2316 anova_results.setXAxisTitle("Element");
2317
2318 if (arguments.at("Modify the included elements based on the results") == "true")
2319 {
2320 std::vector<std::string> selected = p_values->ExtractWithinRange(
2321 0,
2322 aquiutils::atof(arguments.at("P-value threshold"))
2323 ).Labels();
2325 }
2326
2327 results.Append(anova_results);
2328
2329 return true;
2330}
2331
2332bool Conductor::ExecuteErrorAnalysis(const std::map<std::string, std::string>& given_arguments)
2333{
2334 // The random elimination of samples is seeded like the MCMC, and the
2335 // seed is recorded in the results name
2336 std::map<std::string, std::string> arguments = given_arguments;
2337 std::uint64_t seed = 0;
2338 if (!ResolveRandomSeed(arguments, seed))
2339 return false;
2340 results.SetName("Error Analysis (random seed " + std::to_string(seed) + ")"); // BootStrap refines it
2341
2343
2344 bool organic_size_correction = false;
2345 if (arguments.at("Apply size and organic matter correction") == "true")
2346 {
2347 organic_size_correction = true;
2348 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2349 {
2350 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2351 return false;
2352 }
2353 }
2354 else
2355 {
2356 organic_size_correction = false;
2357 }
2358
2359 rtw->Start();
2360
2361 SourceSinkData corrected_data = Data()->CreateCorrectedDataset(
2362 arguments.at("Sample"),
2363 organic_size_correction,
2364 Data()->GetElementInformation()
2365 );
2366
2367 corrected_data.SetProgressReporter(rtw);
2368
2369 if (!CheckNegativeElements(&corrected_data))
2370 return false;
2371
2372 bool softmax = (arguments.at("Softmax transformation") == "true");
2373
2374 corrected_data.InitializeParametersAndObservations(arguments.at("Sample"));
2375
2376 // The argument was named "Pecentage eliminated" until November 2026;
2377 // scripts that still use the old name keep working
2378 const std::string percentage_key =
2379 (arguments.count("Percentage eliminated") == 0 && arguments.count("Pecentage eliminated") != 0)
2380 ? "Pecentage eliminated" : "Percentage eliminated";
2381
2382 bool outcome = corrected_data.BootStrap(
2383 &results,
2384 aquiutils::atof(arguments.at(percentage_key)),
2385 aquiutils::atoi(arguments.at("Number of realizations")),
2386 arguments.at("Sample"),
2387 softmax,
2388 seed
2389 );
2390
2391 return outcome;
2392}
2393
2394bool Conductor::ExecuteSourceVerify(const std::map<std::string, std::string>& arguments)
2395{
2396 results.SetName("Source Verification");
2397
2399
2400 bool organic_size_correction = false;
2401 if (arguments.at("Apply size and organic matter correction") == "true")
2402 {
2403 organic_size_correction = true;
2404 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2405 {
2406 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2407 return false;
2408 }
2409 }
2410 else
2411 {
2412 organic_size_correction = false;
2413 }
2414
2415 // Each tested sample is left out of its group, so the group needs at least
2416 // two other included samples to estimate its statistics from
2417 int included_samples = 0;
2418 for (const auto& [sample_name, profile] : *Data()->GetSampleSet(arguments.at("Source Group")))
2419 if (!sample_name.empty() && profile.IsIncludedInAnalysis())
2420 included_samples++;
2421 if (included_samples < 3)
2422 {
2423 host->ShowWarning("Source verification needs at least 3 included samples in '" + arguments.at("Source Group") + "'.\n");
2424 return false;
2425 }
2426
2427 rtw->Start();
2428
2429 SourceSinkData corrected_data = *Data();
2430 corrected_data.SetProgressReporter(rtw);
2431
2432 if (!CheckNegativeElements(&corrected_data))
2433 return false;
2434
2435 bool softmax = (arguments.at("Softmax transformation") == "true");
2436
2437 CMBTimeSeriesSet* contributions = new CMBTimeSeriesSet(
2438 corrected_data.VerifySource(
2439 arguments.at("Source Group"),
2440 softmax,
2441 organic_size_correction
2442 )
2443 );
2444
2445 ResultItem contributions_result_item;
2446 results.SetName("Source verification for source'" + arguments.at("Source Group") + "'");
2447
2448 contributions->GetOptions().X_suffix = "";
2449 contributions->GetOptions().Y_suffix = "";
2450 contributions->SetOption(options_key::single_column_x, true);
2451
2452 contributions_result_item.SetName("Source Verification");
2453 contributions_result_item.SetResult(contributions);
2454 contributions_result_item.SetType(result_type::stacked_bar_chart);
2455 contributions_result_item.SetShowAsString(true);
2456 contributions_result_item.SetShowTable(true);
2457 contributions_result_item.SetShowGraph(true);
2458 contributions_result_item.SetYLimit(_range::high, 1);
2459 contributions_result_item.SetXAxisMode(xaxis_mode::counter);
2460 contributions_result_item.setYAxisTitle("Contribution");
2461 contributions_result_item.setXAxisTitle("Source Sample");
2462 contributions_result_item.SetYLimit(_range::low, 0);
2463
2464 results.Append(contributions_result_item);
2465
2466 rtw->SetProgress(1);
2467
2468 return true;
2469}
2470
2471bool Conductor::ExecuteAutoSelect(const std::map<std::string, std::string>& arguments)
2472{
2473 results.SetName("Auto-select elements");
2474
2475 SourceSinkData transformed_data;
2476
2477 if (arguments.at("OM and Size Correct based on target sample") != "")
2478 {
2479 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2480 {
2481 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2482 return false;
2483 }
2484 transformed_data = Data()->CreateCorrectedDataset(
2485 arguments.at("OM and Size Correct based on target sample"),
2486 true,
2487 Data()->GetElementInformation()
2488 ).CreateTracerDataset(true, false, false);
2489 }
2490 else
2491 {
2492 transformed_data = Data()->CreateTracerDataset(true, false, false);
2493 }
2494
2495 if (!CheckNegativeElements(&transformed_data))
2496 return false;
2497
2498 bool isotopes = (arguments.at("Include Isotopes") == "true");
2499
2500 transformed_data = transformed_data.ExtractChemicalElements(isotopes);
2501
2502 // Multi-way discriminant p-value result
2503 ResultItem edp_p_value;
2504 edp_p_value.SetName("Multi-way discriminat p-value");
2506 edp_p_value.SetShowAsString(true);
2507 edp_p_value.setYAxisTitle("p-Value");
2508 edp_p_value.SetShowTable(true);
2509 edp_p_value.SetShowGraph(true);
2510
2511 Elemental_Profile_Set* edp_profile_set_p_value = new Elemental_Profile_Set(
2512 transformed_data.DifferentiationPower_P_value(false)
2513 );
2514
2515 edp_p_value.SetYAxisMode(yaxis_mode::normal);
2516 edp_p_value.SetYLimit(_range::high, 1);
2517 edp_p_value.SetResult(edp_profile_set_p_value);
2518 results.Append(edp_p_value);
2519
2520 // Selected elements result
2521 Elemental_Profile* selected = new Elemental_Profile(
2522 edp_profile_set_p_value->SelectTopElementsAggregate(
2523 aquiutils::atoi(arguments.at("Number of elements from each pair"))
2524 )
2525 );
2526
2527 ResultItem selected_elements;
2528 selected_elements.SetResult(selected);
2529 selected_elements.SetName("Selected Elements");
2531 selected_elements.SetShowAsString(true);
2532 selected_elements.setYAxisTitle("p-Value");
2533 selected_elements.SetShowTable(true);
2534 selected_elements.SetShowGraph(true);
2535 results.Append(selected_elements);
2536
2537 if (arguments.at("Modify the included elements based on the results") == "true")
2538 {
2540 }
2541
2542 return true;
2543}
2544
2545bool Conductor::ExecuteCMBBayesian(const std::map<std::string, std::string>& given_arguments)
2546{
2547 std::map<std::string, std::string> arguments = given_arguments;
2548 std::uint64_t seed = 0;
2549 if (!ResolveRandomSeed(arguments, seed))
2550 return false;
2551
2552 if (arguments.at("Apply size and organic matter correction") == "true")
2553 {
2554 if (Data()->OMandSizeConstituents()[0] == "" && Data()->OMandSizeConstituents()[1] == "")
2555 {
2556 host->ShowWarning("Perform Organic Matter and Size Correction first!\n");
2557 return false;
2558 }
2559 }
2560
2561 // Initialize MCMC object
2562 MCMC = std::make_unique<CMCMC<SourceSinkData>>();
2563
2564 // Create progress window with 3 charts for monitoring
2566 rtw->SetTitle("Acceptance Rate", 0);
2567 rtw->SetTitle("Perturbation Factor", 1);
2568 rtw->SetTitle("Log posterior value", 2);
2569 rtw->SetYAxisTitle("Acceptance Rate", 0);
2570 rtw->SetYAxisTitle("Perturbation Factor", 1);
2571 rtw->SetYAxisTitle("Log posterior value", 2);
2572 rtw->Start();
2573
2574 // Execute MCMC sampling
2575 results = Data()->MCMC(
2576 arguments.at("Sample"),
2577 arguments,
2578 MCMC.get(),
2579 rtw,
2580 workingfolder.toStdString()
2581 );
2582
2583 // Check for errors during execution
2584 if (results.Error() != "")
2585 {
2586 host->ShowWarning(results.Error());
2587 return false;
2588 }
2589
2590 rtw->SetProgress(1);
2591
2592 return true;
2593}
Abstract environment that an analysis runs inside.
virtual void ShowWarning(const std::string &message)=0
Reports a condition that prevented an analysis from running.
Matrix class with labeled rows and columns for Chemical Mass Balance analysis.
Definition cmbmatrix.h:22
void SetBooleanValue(bool val)
Sets boolean display mode for table widget.
Definition cmbmatrix.h:186
Collection of time series with labels and observed values.
string Label(unsigned int i) const
Gets label for time point (uses custom labels if set).
Collection of named CMBVectorSet objects for hierarchical data organization.
Collection of named CMBVector objects for multi-variable analysis.
Vector class with string labels for Chemical Mass Balance analysis.
Definition cmbvector.h:20
CMBVector ExtractWithinRange(const double &lowval, const double &highval) const
Extracts elements with values within specified range.
void SetBooleanValue(bool val)
Sets boolean display mode for table widget.
Definition cmbvector.h:164
CMBVector ExtractUpToMinimum() const
Extracts elements up to first minimum value.
void append(const string &label, const double &val)
Appends a labeled element to the vector.
double valueAt(int i) const
Gets value at specified index.
vector< string > Labels() const
Gets all element labels.
Definition cmbvector.h:141
Markov Chain Monte Carlo sampler for Bayesian parameter estimation.
Definition MCMC.h:351
bool SetProperty(const string &varname, const string &value)
Set MCMC properties from string key-value pairs.
Definition MCMC.hpp:75
bool step(int k, int chain_counter)
Perform single MCMC step for one chain.
Definition MCMC.hpp:367
T * Model
Pointer to the model object being calibrated.
Definition MCMC.h:359
void initialize(CMBTimeSeriesSet *results, bool random=false)
Initialize MCMC chains with starting parameter values.
Definition MCMC.hpp:214
void SetRandomSeed(std::uint64_t seed)
Sets the master seed for the chains' random streams.
Definition MCMC.hpp:706
Manages a collection of concentration measurements with statistical analysis.
bool ExecuteOutlierAnalysis(const std::map< std::string, std::string > &arguments)
Executes outlier detection analysis for a source/target group.
bool ExecuteTestCMBBayesian(const std::map< std::string, std::string > &arguments)
Executes MCMC test with a simple analytical model.
bool ExecuteCMBBayesian(const std::map< std::string, std::string > &arguments)
Executes Bayesian Chemical Mass Balance using MCMC sampling.
bool ExecuteDFAM(const std::map< std::string, std::string > &arguments)
Executes multi-way Discriminant Function Analysis across all groups.
bool ExecuteDFA(const std::map< std::string, std::string > &arguments)
Executes Discriminant Function Analysis between two groups.
bool ExecuteSDFAM(const std::map< std::string, std::string > &arguments)
Executes multi-way Stepwise Discriminant Function Analysis across all groups.
bool ExecuteBoxCox(const std::map< std::string, std::string > &arguments)
Calculates optimal Box-Cox transformation parameters.
bool ExecuteKolmogorovSmirnovIndividual(const std::map< std::string, std::string > &arguments)
Executes Kolmogorov-Smirnov test for a single constituent in a group.
void ReportBoxCoxSkips(SourceSinkData &dataset, const std::string &group, const std::string &consequence)
Warns about constituents the Box-Cox transformation leaves untransformed.
bool CheckNegativeElements(SourceSinkData *data=nullptr)
Validates that all element concentrations are non-negative.
bool ExecuteCMBBayesianBatch(const std::map< std::string, std::string > &arguments)
Executes Bayesian Chemical Mass Balance across all target samples.
bool ResolveRandomSeed(std::map< std::string, std::string > &arguments, std::uint64_t &seed)
Resolves the "Random seed" argument of an MCMC analysis.
bool ExecuteAutoSelect(const std::map< std::string, std::string > &arguments)
Executes automatic element selection based on discriminant power.
bool ExecuteSDFA(const std::map< std::string, std::string > &arguments)
Executes Stepwise Discriminant Function Analysis between two groups.
bool Execute(const std::string &command, const std::map< std::string, std::string > &arguments)
Executes a specified analysis command with given parameters.
Definition conductor.cpp:24
bool ExecuteBracketingAnalysisBatch(const std::map< std::string, std::string > &arguments)
Executes bracketing analysis across all target samples.
bool ExecuteANOVA(const std::map< std::string, std::string > &arguments)
Executes Analysis of Variance (ANOVA) for element discrimination.
bool ExecuteErrorAnalysis(const std::map< std::string, std::string > &given_arguments)
Executes bootstrap error analysis for uncertainty quantification.
AnalysisHost * host
Non-owning pointer to the running environment.
Definition conductor.h:193
QString workingfolder
Output directory path.
Definition conductor.h:192
bool ExecuteSourceVerify(const std::map< std::string, std::string > &arguments)
Executes source verification analysis.
bool ExecuteMLR(const std::map< std::string, std::string > &arguments)
Executes multiple linear regression versus organic matter and particle size.
Conductor(AnalysisHost *host)
Constructs a Conductor that reports through host.
Definition conductor.cpp:18
bool ExecuteDistributionFitting(const std::map< std::string, std::string > &arguments)
Executes distribution fitting analysis for a constituent.
bool ExecuteLevenbergMarquardtBatch(const std::map< std::string, std::string > &arguments)
Executes Levenberg-Marquardt optimization across all target samples.
bool ExecuteKolmogorovSmirnov(const std::map< std::string, std::string > &arguments)
Executes Kolmogorov-Smirnov goodness-of-fit test for a source/target group.
SourceSinkData * Data()
Returns pointer to the current SourceSinkData.
Definition conductor.h:80
SourceSinkData * data
Non-owning pointer to analysis data.
Definition conductor.h:186
bool ExecuteSDFAOnevsRest(const std::map< std::string, std::string > &arguments)
Executes Stepwise Discriminant Function Analysis for one group versus all others.
bool ExecuteBracketingAnalysis(const std::map< std::string, std::string > &arguments)
Executes bracketing analysis for a single target sample.
bool ExecuteDFAOnevsRest(const std::map< std::string, std::string > &arguments)
Executes Discriminant Function Analysis for one group versus all others.
SourceSinkData BoxCoxTransformedWithReport(SourceSinkData &dataset)
Box-Cox transforms data with optimal lambdas, reporting skipped constituents.
bool ExecuteCovarianceMatrix(const std::map< std::string, std::string > &arguments)
Calculates covariance matrix for a source or target group.
Results results
Current analysis results (cleared each Execute).
Definition conductor.h:191
void ReportNegativeContributions(const std::vector< std::string > &offenders)
Reports negative source contributions through the AnalysisHost.
bool ExecuteOMSizeCorrect(const std::map< std::string, std::string > &arguments)
Executes organic matter and particle size correction.
bool ExecuteLevenbergMarquardt(const std::map< std::string, std::string > &arguments)
Executes Levenberg-Marquardt nonlinear optimization.
bool ExecuteEDP(const std::map< std::string, std::string > &arguments)
Calculates two-way element discriminant power between two groups.
bool ExecuteEDPM(const std::map< std::string, std::string > &arguments)
Calculates multi-way element discriminant power across all groups.
bool ExecuteCorrelationMatrix(const std::map< std::string, std::string > &arguments)
Calculates correlation matrix for a source or target group.
std::unique_ptr< CMCMC< SourceSinkData > > MCMC
MCMC sampler (owned).
Definition conductor.h:190
Manages a collection of elemental profiles (samples) for source fingerprinting analysis.
Elemental_Profile SelectTopElementsAggregate(int n) const
Select top N elements across all samples (aggregate minimum).
Container for elemental concentration data of a single sediment sample.
vector< string > GetElementNames() const
Get list of all element names.
options & GetOptions()
Get reference to the options structure.
Definition interface.h:278
void SetOption(options_key opt, bool val)
Set a configuration option.
Definition interface.h:253
void SetLimit(_range lowhigh, const double &value)
Set upper or lower limit for value highlighting.
Definition interface.h:236
virtual void Start()
Makes the reporter visible or otherwise begins reporting.
virtual void SetYAxisTitle(const QString &title, int chart=0)=0
Sets the vertical axis title of a chart.
virtual void SetProgress(const double &prog)=0
Sets the primary progress fraction.
virtual void SetTitle(const QString &title, int chart=0)=0
Sets the title of a chart.
void SetAbsoluteValue(bool val)
Definition resultitem.h:60
void SetShowGraph(bool state)
Definition resultitem.h:83
void setYAxisTitle(const string &title)
Definition resultitem.h:42
void SetXAxisMode(xaxis_mode mode)
Definition resultitem.h:29
void SetYLimit(_range highlow, const double &value)
Definition resultitem.h:69
void setTableTitle(const string &Title)
Definition resultitem.h:50
void SetName(const string &_name)
Definition resultitem.h:24
void SetResult(Interface *_result)
Definition resultitem.h:21
void SetShowTable(bool state)
Definition resultitem.h:81
void setXAxisTitle(const string &title)
Definition resultitem.h:34
void SetYAxisMode(yaxis_mode mode)
Definition resultitem.h:28
void SetShowAsString(bool value)
Definition resultitem.h:32
void SetType(const result_type &_type)
Definition resultitem.h:26
Holds a progress reporter for the duration of one analysis.
bool InitializeParametersAndObservations(const string &targetsamplename, estimation_mode est_mode=estimation_mode::elemental_profile_and_contribution)
Initialize parameters and observations for MCMC optimization.
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 > NegativeContributionCheck()
Checks the solved source contributions for negative values.
vector< string > IsotopesWithUnusableBaseElement() const
Lists the isotopes included in the analysis whose base element cannot be used.
Elemental_Profile_Set DifferentiationPower_Percentage(bool include_target)
Computes rank-based differentiation percentage for all source pairs.
SourceSinkData ExtractChemicalElements(bool isotopes) const
Extract only chemical elements (and optionally isotopes).
CMBVector ANOVA(bool use_log)
Performs one-way ANOVA for all elements across source groups.
bool SolveLevenberg_Marquardt(transformation trans=transformation::linear)
Solves for optimal source contributions using the Levenberg-Marquardt algorithm.
CMBMatrix DFAConfusionMatrix()
Leave-one-out confusion matrix of the source samples.
vector< CMBVector > StepwiseDiscriminantFunctionAnalysis(const string &source1, const string &source2)
Performs stepwise discriminant analysis between two specific sources.
ConcentrationSet * GetElementDistribution(const string &element_name)
Retrieves pointer to element distribution at dataset level.
SourceSinkData BoxCoxTransformed(bool calculate_optimal_lambda=false)
Applies Box-Cox transformation to all source groups for normalization.
void SetParameterEstimationMode(estimation_mode est_mode)
Sets the estimation mode for parameter optimization.
CMBVector BracketTest(const string &target_sample, bool correct_based_on_om_n_size, double tolerance=0)
Performs bracket test to check if target concentrations fall within source ranges.
Elemental_Profile t_TestPValue(const string &source1, const string &source2, bool use_log)
Computes t-test p-values for element-wise differences between two sources.
vector< ResultItem > GetMLRResults()
Retrieves multiple linear regression results for all sample groups.
void SetOMandSizeConstituents(const string &_omconstituent, const string &_sizeconstituent)
Sets the names of OM and particle size constituents.
void IncludeExcludeElementsBasedOn(const vector< string > &elements)
Sets element inclusion based on a specified list.
ResultItem GetPredictedElementalProfile(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Generates predicted elemental concentrations for the target sample.
SourceSinkData CreateCorrectedAndFilteredDataset(bool exclude_samples, bool exclude_elements, bool omnsizecorrect, const string &target="") const
Create a corrected and filtered copy of the dataset.
vector< string > NegativeValueCheck()
Checks for zero or negative concentration values across all sources.
CMBTimeSeriesSet VerifySource(const string &source_group, bool use_softmax, bool apply_om_size_correction)
Performs leave-one-out validation on a source group.
bool SetSelectedTargetSample(const string &sample_name)
Sets the currently selected target sample for analysis.
void AddtoToolsUsed(const string &tool)
Adds a tool name to the list of tools used in analysis.
DFA_result DiscriminantFunctionAnalysis()
Performs discriminant function analysis for all source groups.
vector< ResultItem > GetSourceProfiles()
Retrieves elemental profiles for all source groups.
Results MCMC(const string &target_sample, map< string, string > arguments, CMCMC< SourceSinkData > *mcmc, ProgressReporter *progress_window, const string &working_folder)
Performs Markov Chain Monte Carlo analysis for Bayesian source apportionment.
CMBTimeSeriesSet BootStrap(const double &percentage, unsigned int num_iterations, const string &target_sample, bool use_softmax, std::uint64_t seed=DefaultRandomSeed)
Performs bootstrap uncertainty analysis on source contributions.
Elemental_Profile_Set DifferentiationPower(bool use_log, bool include_target)
Computes differentiation power for all source pairs.
SourceSinkData CreateTracerDataset(bool exclude_samples, bool exclude_elements, bool omnsizecorrect, const string &target="") const
As CreateCorrectedAndFilteredDataset, keeping only the tracers.
SourceSinkData CreateCorrectedDataset(const string &target, bool omnsizecorrect, map< string, element_information > *elementinfo)
Create a corrected copy of the dataset for a specific target sample.
ResultItem GetObservedvsModeledElementalProfile(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Creates a comparison of observed vs modeled elemental profiles.
Elemental_Profile_Set DifferentiationPower_P_value(bool include_target)
Computes t-test p-values for all source pairs.
ResultItem GetContribution()
Packages source contributions into a ResultItem for output.
ResultItem GetObservedvsModeledElementalProfile_Isotope(parameter_mode param_mode=parameter_mode::based_on_fitted_distribution)
Creates a comparison of observed vs modeled isotope delta values.
void SetProgressReporter(ProgressReporter *_rtw)
Sets the progress window for displaying optimization progress.
void InitializeParametersObservations(const vector< double > &mins, const vector< double > &maxs)
Definition testmcmc.cpp:11
@ direct
Use empirical statistics from data.
distribution_type
Enumeration of probability distribution types supported in SedSat3.
@ lognormal
Lognormal distribution: ln(x) ~ N(μ, σ²), for strictly positive variables.
@ normal
Normal (Gaussian) distribution: p(x) = N(μ, σ²).
static bool ReadBracketTolerance(const std::map< std::string, std::string > &arguments, AnalysisHost *host, double &tolerance)
@ single_column_x
Enable single-column mode for X-axis data representation.
Definition interface.h:22
bool parseNumericValue(const QVariant &value, double &out, QString &error)
Parses a spreadsheet cell value as a finite number.
The one place where data values entering SedSAT3 are checked.
@ low
Lower bound of the parameter range.
Definition parameter.h:17
@ high
Upper bound of the parameter range.
Definition parameter.h:18
bool ParseRandomSeed(const std::string &text, std::uint64_t &seed)
Parses a user-entered seed.
@ predicted_concentration
Definition resultitem.h:9
@ stacked_bar_chart
Definition resultitem.h:9
@ elemental_profile_set
Definition resultitem.h:9
@ dfa_vectorsetset
Definition resultitem.h:9
@ timeseries_set_first_symbol
Definition resultitem.h:9
@ vectorset_groups
Definition resultitem.h:9
@ source_elemental_profiles_based_on_source_data
CMBVectorSet projected
CMBVector p_values
CMBVectorSet eigen_vectors
CMBVector F_test_P_value
CMBVectorSetSet multi_projected
QString X_suffix
Suffix appended to X-axis field names in serialization.
Definition interface.h:36
QString Y_suffix
Suffix appended to Y-axis field names in serialization.
Definition interface.h:37