id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,531,878
Error.cpp
andreacasalino_Easy-Factor-Graph/src/src/Error.cpp
#include <EasyFactorGraph/Error.h> namespace EFG { Error::Error(const std::string &what) : std::runtime_error(what) {} } // namespace EFG
139
C++
.cpp
4
33.5
67
0.738806
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,879
RandomField.cpp
andreacasalino_Easy-Factor-Graph/src/src/model/RandomField.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/misc/Cast.h> #include <EasyFactorGraph/model/RandomField.h> namespace EFG::model { void RandomField::absorb(const strct::FactorsAware &to_absorb, bool copy) { castConstAndUse<strct::FactorsConstGetter>( to_absorb, [this, &copy](const strct::FactorsConstGetter &as_factor_aware) { const auto &factors = as_factor_aware.getConstFactors(); this->absorbConstFactors(factors.begin(), factors.end(), copy); }); castConstAndUse<train::FactorsTunableGetter>( to_absorb, [this, &copy](const train::FactorsTunableGetter &as_factor_tunable_aware) { this->absorbTunableClusters(as_factor_tunable_aware, copy); }); for (const auto &[var, val] : to_absorb.getEvidences()) { setEvidence(var, val); } } std::vector<float> RandomField::getWeightsGradient_( const train::TrainSet::Iterator &train_set_combinations) { if (!getEvidences().empty()) { removeAllEvidences(); } resetBelief(); propagateBelief(strct::PropagationKind::SUM); std::vector<float> result; result.resize(tuners.size()); strct::Tasks tasks; std::size_t result_pos = 0; for (auto &tuner : tuners) { tasks.emplace_back([&receiver = result[result_pos], &tuner = tuner, &train_set_combinations](const std::size_t) { receiver = tuner->getGradientAlpha(train_set_combinations) - tuner->getGradientBeta(); }); ++result_pos; } getPool().parallelFor(tasks); return result; } } // namespace EFG::model
1,654
C++
.cpp
49
29.102041
75
0.681449
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,880
ConditionalRandomField.cpp
andreacasalino_Easy-Factor-Graph/src/src/model/ConditionalRandomField.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/GroupRange.h> #include <EasyFactorGraph/model/ConditionalRandomField.h> #include <EasyFactorGraph/trainable/tuners/TunerVisitor.h> #include "HiddenObservedTuner.h" #include <algorithm> #include <math.h> namespace EFG::model { namespace { std::vector<std::size_t> find_positions(const categoric::VariablesSoup &all_vars, const categoric::VariablesSet &to_find) { std::vector<std::size_t> result; result.reserve(to_find.size()); for (const auto &var : to_find) { auto it = std::find(all_vars.begin(), all_vars.end(), var); result.push_back(std::distance(all_vars.begin(), it)); } return result; } } // namespace ConditionalRandomField::ConditionalRandomField(const ConditionalRandomField &o) : evidence_vars_positions( find_positions(o.getAllVariables(), o.getObservedVariables())) { absorb(SourceStructure{static_cast<const strct::FactorsConstGetter *>(&o), static_cast<const train::FactorsTunableGetter *>(&o)}, false); } ConditionalRandomField::ConditionalRandomField(const RandomField &source, bool copy) : evidence_vars_positions(find_positions(source.getAllVariables(), source.getObservedVariables())) { absorb( SourceStructure{ static_cast<const strct::FactorsConstGetter *>(&source), static_cast<const train::FactorsTunableGetter *>(&source)}, copy); } void ConditionalRandomField::absorb(const SourceStructure &source, bool copy) { const auto &evidences = source.factors_structure->getEvidences(); if (evidences.empty()) { throw Error{"ConditionalRandomField must have at least 1 evidence"}; } const auto &const_factors = source.factors_structure->getConstFactors(); absorbConstFactors(const_factors.begin(), const_factors.end(), copy); absorbTunableClusters(*source.factors_tunable_structure, copy); for (const auto &[var, val] : evidences) { setEvidence(findVariable(var->name()), val); } // replace tuners of factors connected to an evidence for (auto &tuner : tuners) { train::visitTuner( tuner.get(), [this, &tuner](train::BaseTuner &subject) { this->replaceIfNeeded(tuner, subject); }, [this](train::CompositeTuner &subject) { for (auto &element : subject.getElements()) { this->replaceIfNeeded( element, *dynamic_cast<const train::BaseTuner *>(element.get())); } }); } } void ConditionalRandomField::replaceIfNeeded(train::TunerPtr &container, const train::BaseTuner &subject) { const auto &evidences = this->getEvidences(); const auto &vars = subject.getFactor().function().vars().getVariables(); switch (vars.size()) { case 1: { if (evidences.find(vars.front()) != evidences.end()) { throw Error::make("Found unary factor attached to permanent evidence: ", vars.front()->name()); } } break; case 2: { auto first_as_evidence = evidences.find(vars.front()); auto second_as_evidence = evidences.find(vars.back()); if ((first_as_evidence == evidences.end()) && (second_as_evidence == evidences.end())) { return; } if ((first_as_evidence != evidences.end()) && (second_as_evidence != evidences.end())) { throw Error::make("Found factor connecting the permanent evidences: ", first_as_evidence->first->name(), " and ", second_as_evidence->first->name()); return; } train::TunerPtr replacing_tuner; if (first_as_evidence == evidences.end()) { strct::Node &hidden = *stateMutable().nodes.find(vars.front())->second; replacing_tuner = std::make_unique<train::HiddenObservedTuner>( hidden, second_as_evidence, subject.getFactorPtr(), getAllVariables()); } else { strct::Node &hidden = *stateMutable().nodes.find(vars.back())->second; replacing_tuner = std::make_unique<train::HiddenObservedTuner>( hidden, first_as_evidence, subject.getFactorPtr(), getAllVariables()); } container = std::move(replacing_tuner); } break; } } void ConditionalRandomField::setEvidences( const std::vector<std::size_t> &values) { const auto &state = this->state(); if (values.size() != state.evidences.size()) { throw Error::make("Expected ", std::to_string(state.evidences.size()), " evidences, but got instead ", values.size()); } std::size_t k = 0; for (const auto &[var, val] : state.evidences) { setEvidence(var, values[k]); ++k; } } std::vector<float> ConditionalRandomField::getWeightsGradient_( const train::TrainSet::Iterator &train_set_combinations) { // compute alfa part std::vector<float> alfas; { alfas.resize(tuners.size()); strct::Tasks tasks; std::size_t alfas_pos = 0; for (auto &tuner : tuners) { tasks.emplace_back([&receiver = alfas[alfas_pos], &tuner = tuner, &train_set_combinations](const std::size_t) { receiver = tuner->getGradientAlpha(train_set_combinations); }); ++alfas_pos; } getPool().parallelFor(tasks); } // compute beta part std::vector<float> betas; { betas.reserve(tuners.size()); for (std::size_t k = 0; k < tuners.size(); ++k) { betas.push_back(0); } float coeff = 1.f / static_cast<float>(train_set_combinations.size()); strct::Tasks tasks; for (std::size_t t = 0; t < this->tuners.size(); ++t) { tasks.emplace_back([&receiver = betas[t], &tuner = tuners[t], &coeff](const std::size_t) { receiver += coeff * tuner->getGradientBeta(); }); } train_set_combinations.forEachSample( [this, &tasks](const auto &combination) { { std::size_t var_pos = 0; for (auto &[var, val] : this->state().evidences) { this->setEvidence( var, combination[this->evidence_vars_positions[var_pos]]); ++var_pos; } } propagateBelief(strct::PropagationKind::SUM); this->getPool().parallelFor(tasks); }); } for (std::size_t k = 0; k < alfas.size(); ++k) { alfas[k] -= betas[k]; } return alfas; } std::vector<std::vector<std::size_t>> ConditionalRandomField::makeTrainSet( const GibbsSampler::SamplesGenerationContext &context, float range_percentage, const std::size_t threads) { if ((range_percentage > 1.f) || (range_percentage < 0)) { throw Error{"Invalid range percentage"}; } std::vector<std::size_t> hidden_vars_position = find_positions(getAllVariables(), getHiddenVariables()); std::vector<std::vector<std::size_t>> result; auto emplace_samples = [&](const auto &ev) { this->setEvidences(ev); for (const auto &sample : this->makeSamples(context, threads)) { result.push_back(sample); } }; const auto evidence_set = getObservedVariables(); auto evidences_group = categoric::Group{ categoric::VariablesSoup{evidence_set.begin(), evidence_set.end()}}; categoric::GroupRange evidences_range(evidences_group); if (1.f == range_percentage) { categoric::for_each_combination(evidences_range, emplace_samples); } else { const std::size_t result_max_size = evidences_group.size(); const std::size_t result_size_approx = static_cast<std::size_t>(floorf(result_max_size * range_percentage)); const std::size_t delta = result_max_size / result_size_approx; std::size_t k = 0; while (k < result_max_size) { emplace_samples(*evidences_range); if ((k + delta) >= result_max_size) { break; } for (std::size_t i = 0; i < delta; ++i) { ++evidences_range; } k += delta; } } return result; } } // namespace EFG::model
8,173
C++
.cpp
216
31.314815
80
0.634395
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,881
HiddenObservedTuner.cpp
andreacasalino_Easy-Factor-Graph/src/src/model/HiddenObservedTuner.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include "HiddenObservedTuner.h" namespace EFG::train { HiddenObservedTuner::HiddenObservedTuner( strct::Node &nodeHidden, const strct::Evidences::const_iterator &evidence, const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model) : BaseTuner(factor, variables_in_model), nodeHidden(nodeHidden), evidence(evidence) { pos_in_factor_hidden = 0; pos_in_factor_evidence = 1; if (factor->function().vars().getVariables().front().get() == evidence->first.get()) { std::swap(pos_in_factor_hidden, pos_in_factor_evidence); } } float HiddenObservedTuner::getGradientBeta() { std::vector<const factor::Immutable *> hidden_unaries = { nodeHidden.merged_unaries.get()}; for (const auto &[connected_node, connection] : nodeHidden.active_connections) { hidden_unaries.push_back(connection.message.get()); } auto hidden_probs = factor::MergedUnaries{hidden_unaries}.getProbabilities(); float result = 0; const auto &factor_map = getFactor().function(); std::vector<std::size_t> comb; comb.resize(2); comb[pos_in_factor_evidence] = evidence->second; for (std::size_t h = 0; h < hidden_probs.size(); ++h) { comb[pos_in_factor_hidden] = h; result += hidden_probs[h] * factor_map.findImage(comb); } return result; } } // namespace EFG::train
1,478
C++
.cpp
41
32.682927
79
0.705718
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,882
Graph.cpp
andreacasalino_Easy-Factor-Graph/src/src/model/Graph.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/model/Graph.h> namespace EFG::model { void Graph::absorb(const strct::FactorsAware &to_absorb, bool copy) { const auto &factors = to_absorb.getAllFactors(); absorbConstFactors(factors.begin(), factors.end(), copy); for (const auto &[var, val] : to_absorb.getEvidences()) { setEvidence(var, val); } } } // namespace EFG::model
477
C++
.cpp
16
27.625
69
0.705882
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,883
ModelTrainer.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/ModelTrainer.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_LEARNING_ENABLED #include <EasyFactorGraph/trainable/ModelTrainer.h> #include <TrainingTools/ParametersAware.h> namespace EFG::train { namespace { ::train::Vect to_Vect(const std::vector<float> &subject) { ::train::Vect result(subject.size()); for (std::size_t k = 0; k < subject.size(); ++k) { result(static_cast<Eigen::Index>(k)) = static_cast<double>(subject[k]); } return result; } std::vector<float> to_vector(const ::train::Vect &subject) { std::vector<float> result; result.resize(subject.size()); for (Eigen::Index k = 0; k < subject.size(); ++k) { result[static_cast<std::size_t>(k)] = static_cast<float>(subject(k)); } return result; } struct TrainSetWrapper { TrainSetWrapper(const TrainSet &source, float percentage) : source(source), percentage(percentage) { combinations = std::make_unique<TrainSet::Iterator>(source, 1.f); } const TrainSet &source; float percentage; mutable std::unique_ptr<TrainSet::Iterator> combinations; const TrainSet::Iterator &get() const { if (1.f != percentage) { combinations = std::make_unique<TrainSet::Iterator>(source, percentage); } return *combinations; } }; } // namespace class FactorsTunableGetter::ModelWrapper : public ::train::ParametersAware { public: ModelWrapper(FactorsTunableGetter &subject, const TrainSet &train_set, const TrainInfo &info) : subject(subject), train_set(TrainSetWrapper{train_set, info.stochastic_percentage}), activator(subject, info.threads) {} ::train::Vect getParameters() const final { return to_Vect(subject.getWeights()); }; void setParameters(const ::train::Vect &w) final { subject.setWeights(to_vector(w)); } ::train::Vect getGradient() const final { return -to_Vect(subject.getWeightsGradient_(train_set.get())); } private: FactorsTunableGetter &subject; TrainSetWrapper train_set; strct::PoolAware::ScopedPoolActivator activator; }; void train_model(FactorsTunableGetter &subject, ::train::Trainer &trainer, const TrainSet &train_set, const TrainInfo &info) { FactorsTunableGetter::ModelWrapper wrapper(subject, train_set, info); trainer.train(wrapper); } } // namespace EFG::train #endif
2,373
C++
.cpp
70
30.357143
78
0.711538
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,884
FactorsTunableManager.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/FactorsTunableManager.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/misc/Visitor.h> #include <EasyFactorGraph/trainable/FactorsTunableManager.h> #include <EasyFactorGraph/trainable/tuners/BinaryTuner.h> #include <EasyFactorGraph/trainable/tuners/CompositeTuner.h> #include <EasyFactorGraph/trainable/tuners/TunerVisitor.h> #include <EasyFactorGraph/trainable/tuners/UnaryTuner.h> #include <algorithm> namespace EFG::train { namespace { FactorExponentialPtr extract_factor(const Tuner &subject) { return static_cast<const BaseTuner &>(subject).getFactorPtr(); } } // namespace std::vector<std::variant<FactorExponentialPtr, TunableClusters>> FactorsTunableGetter::getTunableClusters() const { std::vector<std::variant<FactorExponentialPtr, TunableClusters>> result; for (const auto &tuner : tuners) { visitTuner( tuner.get(), [&result](const BaseTuner &base) { result.emplace_back(extract_factor(base)); }, [&result](const CompositeTuner &composite) { TunableClusters cluster; for (const auto &f : composite.getElements()) { cluster.push_back(extract_factor(*f)); } result.emplace_back(std::move(cluster)); }); } return result; } std::vector<float> FactorsTunableGetter::getWeights() const { std::vector<float> result; result.reserve(tuners.size()); for (const auto &tuner : tuners) { result.push_back(tuner->getWeight()); } return result; } void FactorsTunableGetter::setWeights(const std::vector<float> &weights) { if (weights.size() != tuners.size()) { throw Error{"Invalid weights"}; } for (std::size_t k = 0; k < tuners.size(); ++k) { tuners[k]->setWeight(weights[k]); } resetBelief(); } std::vector<float> FactorsTunableGetter::getWeightsGradient( const TrainSet::Iterator &train_set_combinations, const std::size_t threads) { ScopedPoolActivator activator(*this, threads); return getWeightsGradient_(train_set_combinations); } Tuners::iterator FactorsTunableInserter::findTuner( const categoric::VariablesSet &tuned_vars_group) { auto tuners_it = std::find_if( tuners.begin(), tuners.end(), [&group = tuned_vars_group](const TunerPtr &tuner) { bool is_here = false; visitTuner( tuner.get(), [&is_here, &group](const BaseTuner &tuner) { is_here = tuner.getFactor().function().vars().getVariablesSet() == group; }, [&is_here, &group](const CompositeTuner &composite) { for (const auto &element : composite.getElements()) { if (extract_factor(*element) ->function() .vars() .getVariablesSet() == group) { is_here = true; return; } } }); return is_here; }); if (tuners_it == tuners.end()) { throw Error{"Tuner not found"}; } return tuners_it; } TunerPtr FactorsTunableInserter::makeTuner(const FactorExponentialPtr &factor) { auto vars = getAllVariables(); const auto &factor_vars = factor->function().vars().getVariables(); switch (factor_vars.size()) { case 1: { auto *node = locate(factor_vars.front())->node; return std::make_unique<UnaryTuner>(*node, factor, vars); } case 2: { auto *nodeA = locate(factor_vars.front())->node; auto *nodeB = locate(factor_vars.back())->node; return std::make_unique<BinaryTuner>(*nodeA, *nodeB, factor, vars); } } throw Error{"Invalid tunable factor"}; } void FactorsTunableInserter::addTunableFactor( const FactorExponentialPtr &factor, const std::optional<categoric::VariablesSet> &group_sharing_weight) { addDistribution(factor); auto tuner = makeTuner(factor); tunable_factors.emplace(factor); if (std::nullopt == group_sharing_weight) { tuners.emplace_back(std::move(tuner)); return; } auto other_it = findTuner(*group_sharing_weight); visitTuner( other_it->get(), [&tuner, &other_it](BaseTuner &) { std::unique_ptr<CompositeTuner> new_composite = std::make_unique<CompositeTuner>(std::move(*other_it), std::move(tuner)); *other_it = std::move(new_composite); other_it->get()->setWeight(other_it->get()->getWeight()); }, [&tuner](CompositeTuner &tuner_sharing) { tuner_sharing.addElement(std::move(tuner)); tuner_sharing.setWeight(tuner_sharing.getWeight()); }); } void FactorsTunableInserter::copyTunableFactor( const factor::FactorExponential &factor, const std::optional<categoric::VariablesSet> &group_sharing_weight) { auto cloned = std::make_shared<factor::FactorExponential>(factor); addTunableFactor(cloned, group_sharing_weight); } void FactorsTunableInserter::absorbTunableClusters( const FactorsTunableGetter &source, bool copy) { auto insertFactor = [copy = copy, this]( const FactorExponentialPtr &factor, const std::optional<categoric::VariablesSet> &group_sharing_weight) { if (copy) { copyTunableFactor(*factor, group_sharing_weight); } else { addTunableFactor(factor, group_sharing_weight); } }; for (const auto &cluster : source.getTunableClusters()) { try { VisitorConst<FactorExponentialPtr, TunableClusters>{ [&insertFactor](const FactorExponentialPtr &base) { insertFactor(base, std::nullopt); }, [&insertFactor](const TunableClusters &composite) { auto front_factor = composite.front(); const auto &vars = front_factor->function().vars().getVariablesSet(); insertFactor(front_factor, std::nullopt); std::for_each( composite.begin() + 1, composite.end(), [&insertFactor, &vars](const FactorExponentialPtr &tuner) { insertFactor(tuner, vars); }); }} .visit(cluster); } catch (...) { } } } void set_ones(FactorsTunableGetter &subject) { std::vector<float> weights = subject.getWeights(); for (auto &w : weights) { w = 1.f; } subject.setWeights(weights); } } // namespace EFG::train
6,464
C++
.cpp
181
29.088398
80
0.645558
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,885
TrainSet.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/TrainSet.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/trainable/TrainSet.h> #include <math.h> namespace EFG::train { TrainSet::TrainSet(const std::vector<std::vector<std::size_t>> &combinations) { if (combinations.empty()) { throw Error("empty train set"); } const std::size_t size = combinations.front().size(); for (const auto &combination : combinations) { if ((0 == combination.size()) || (size != combination.size())) { throw Error("invalid train set"); } } this->combinations = std::make_shared<const Combinations>(combinations); } TrainSet::Iterator::Iterator(const TrainSet &subject, float percentage) { this->combinations = subject.combinations; if (1.f == percentage) { return; } if ((percentage <= 0) || (percentage > 1.f)) { throw Error::make(percentage, " is an invalid percentage for a TrainSet Iterator"); } int subset_size = std::max(0, static_cast<int>(floorf(percentage * combinations->size()))); auto &subset = combinations_subset.emplace(); subset.reserve(subset_size); for (int k = 0; k < subset_size; ++k) { int sampled_pos = rand() % combinations->size(); subset.push_back(sampled_pos); } } TrainSet::Iterator TrainSet::makeIterator() const { return Iterator{*this, 1.f}; } TrainSet::Iterator TrainSet::makeSubSetIterator(float percentage) const { return Iterator{*this, percentage}; } std::size_t TrainSet::Iterator::size() const { return combinations_subset.has_value() ? combinations_subset->size() : combinations->size(); } } // namespace EFG::train
1,743
C++
.cpp
51
30.176471
79
0.672997
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,886
BinaryTuner.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/tuners/BinaryTuner.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/SpecialFactors.h> #include <EasyFactorGraph/trainable/tuners/BinaryTuner.h> namespace EFG::train { BinaryTuner::BinaryTuner( strct::Node &nodeA, strct::Node &nodeB, const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model) : BaseTuner(factor, variables_in_model), nodeA(nodeA), nodeB(nodeB) { const auto &variables = factor->function().vars().getVariables(); if (variables.front().get() != nodeA.variable.get()) { throw Error{"Invalid BinaryTuner"}; } if (variables.back().get() != nodeB.variable.get()) { throw Error{"Invalid BinaryTuner"}; } } namespace { std::pair<std::vector<float>, std::vector<float>> marginal_distributions(strct::Node &a, strct::Node &b) { auto gather = [](strct::Node &subject, strct::Node &other) { std::unordered_set<const factor::Immutable *> res{ subject.merged_unaries.get()}; for (const auto &[node, conn] : subject.active_connections) { if (node == &other) { continue; } res.emplace(conn.message.get()); } return std::vector<const factor::Immutable *>{res.begin(), res.end()}; }; return std::make_pair(factor::MergedUnaries{gather(a, b)}.getProbabilities(), factor::MergedUnaries{gather(b, a)}.getProbabilities()); } } // namespace float BinaryTuner::getGradientBeta() { auto marginals = marginal_distributions(nodeA, nodeB); auto &merged_a = marginals.first; auto &merged_b = marginals.second; std::vector<float> probs; probs.reserve(getFactor().function().getInfo().totCombinations); float probs_coeff = 0; getFactor().function().forEachCombination<true>( [&](const auto &comb, float img) { probs_coeff += probs.emplace_back(img * merged_a[comb[0]] * merged_b[comb[1]]); }); probs_coeff = 1.f / probs_coeff; for (auto &val : probs) { val *= probs_coeff; } return dotProduct(probs); } } // namespace EFG::train
2,155
C++
.cpp
60
31.9
80
0.678144
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,887
CompositeTuner.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/tuners/CompositeTuner.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/trainable/tuners/CompositeTuner.h> #include <algorithm> namespace EFG::train { CompositeTuner::CompositeTuner(TunerPtr elementA, TunerPtr elementB) { addElement(std::move(elementA)); addElement(std::move(elementB)); } void CompositeTuner::addElement(TunerPtr element) { if (nullptr == element) { throw Error{"null tuner"}; } elements.emplace_back(std::move(element)); } float CompositeTuner::getGradientAlpha(const TrainSet::Iterator &iter) { float grad = 0.f; for (auto &element : elements) { grad += element->getGradientAlpha(iter); } return grad; } float CompositeTuner::getGradientBeta() { float grad = 0.f; for (auto &element : elements) { grad += element->getGradientBeta(); } return grad; } void CompositeTuner::setWeight(float w) { for (auto &element : elements) { element->setWeight(w); } } } // namespace EFG::train
1,051
C++
.cpp
40
23.825
72
0.7251
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,888
BaseTuner.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/tuners/BaseTuner.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/trainable/tuners/BaseTuner.h> namespace EFG::train { BaseTuner::BaseTuner(const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model) : factor(factor), finder(factor->makeFinder(variables_in_model)) {} float BaseTuner::getGradientAlpha(const TrainSet::Iterator &iter) { if (!alpha_part.has_value() || (alpha_part->train_set_iterator != &iter)) { auto &[iter_ptr, val] = alpha_part.emplace(); val = 0; const float coeff = 1.f / static_cast<float>(iter.size()); iter.forEachSample([&finder = this->finder, &value = val, &coeff](const std::vector<std::size_t> &comb) { value += coeff * finder.findImage(comb); }); } return alpha_part->value; } float BaseTuner::dotProduct(const std::vector<float> &prob) const { float dot = 0; auto prob_it = prob.begin(); factor->function().forEachCombination<false>([&](const auto &, float img) { dot += *prob_it * img; ++prob_it; }); return dot; } } // namespace EFG::train
1,197
C++
.cpp
33
32
78
0.659483
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,889
UnaryTuner.cpp
andreacasalino_Easy-Factor-Graph/src/src/trainable/tuners/UnaryTuner.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/structure/SpecialFactors.h> #include <EasyFactorGraph/trainable/tuners/UnaryTuner.h> namespace EFG::train { UnaryTuner::UnaryTuner(strct::Node &node, const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model) : BaseTuner(factor, variables_in_model), node(node) {} float UnaryTuner::getGradientBeta() { std::vector<const factor::Immutable *> unaries = {node.merged_unaries.get()}; for (const auto &[connected_node, connection] : node.active_connections) { unaries.push_back(connection.message.get()); } factor::MergedUnaries merged(unaries); return dotProduct(merged.getProbabilities()); } } // namespace EFG::train
870
C++
.cpp
22
35.272727
80
0.714793
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,890
Immutable.cpp
andreacasalino_Easy-Factor-Graph/src/src/factor/Immutable.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/GroupRange.h> #include <EasyFactorGraph/factor/Immutable.h> namespace EFG::factor { Immutable::Immutable(FunctionPtr data) : function_{data} { if (data == nullptr) { throw Error{"null data"}; } } std::vector<float> Immutable::getProbabilities() const { std::vector<float> probs; probs.reserve(function_->getInfo().totCombinations); function_->forEachCombination<true>( [&probs](const std::vector<std::size_t> &, float img) { probs.push_back(img); }); // normalize values float sum = 0.f; for (const auto &val : probs) { sum += val; } if (sum == 0.f) { float e = 1.f / static_cast<float>(probs.size()); for (auto &val : probs) { val = e; } } else { for (auto &val : probs) { val /= sum; } } return probs; } ImageFinder Immutable::makeFinder(const categoric::VariablesSoup &bigger_group) const { return ImageFinder{function_, bigger_group}; } } // namespace EFG::factor
1,142
C++
.cpp
44
22.75
75
0.665448
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,891
Factor.cpp
andreacasalino_Easy-Factor-Graph/src/src/factor/Factor.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/GroupRange.h> // #include <EasyFactorGraph/factor/CombinationFinder.h> #include <EasyFactorGraph/factor/Factor.h> namespace EFG::factor { Factor::Factor(FunctionPtr data) : Immutable{data}, Mutable{data} {} Factor::Factor(const categoric::Group &vars) : Factor{std::make_shared<Function>(vars)} {} Factor::Factor(const Factor &o) : Factor{o.function().vars()} { functionMutable().cloneImages(o.function()); } Factor::Factor(const Immutable &to_clone, CloneTrasformedImagesTag) : Factor{to_clone.function().vars()} { to_clone.function().forEachCombination<true>( [&recipient = functionMutable()](const auto &comb, float img) { recipient.set(comb, img); }); } namespace { void check_all_same_size(const categoric::VariablesSoup &vars) { const std::size_t size = vars.front()->size(); for (const auto &var : vars) { if (var->size() != size) { throw Error{"The passed variables don't have all the same size"}; } } } class SameValuesCombination : protected std::vector<std::size_t> { public: SameValuesCombination(std::size_t size) { reserve(size); for (std::size_t k = 0; k < size; ++k) { push_back(0); } } std::vector<std::size_t> get() { return *this; } void next() { ++val; for (auto &v : *this) { v = val; } } private: std::size_t val = 0; }; class SimplyCorrelatedFunction : public Function { public: SimplyCorrelatedFunction(const categoric::Group &variables) : Function{variables} { const auto &vars = variables.getVariables(); check_all_same_size(vars); if (1 == vars.size()) { throw Error{"Only 1 variable can't make a correlation"}; } auto imgs = makeSparseContainer(); SameValuesCombination comb{variables.getVariables().size()}; std::size_t each_var_size = variables.getVariables().front()->size(); for (std::size_t k = 0; k < each_var_size; ++k, comb.next()) { imgs.emplace(comb.get(), 1.f); } data_ = std::move(imgs); } }; } // namespace Factor::Factor(const categoric::Group &vars, SimplyCorrelatedTag) : Factor{std::make_shared<SimplyCorrelatedFunction>(vars)} {} namespace { class SimplyAntiCorrelatedFunction : public Function { public: SimplyAntiCorrelatedFunction(const categoric::Group &variables) : Function{variables} { const auto &vars = variables.getVariables(); if (1 == vars.size()) { throw Error{"Only 1 variable can't make a correlation"}; } check_all_same_size(vars); std::vector<float> imgs; imgs.reserve(info->totCombinations); for (std::size_t k = 0; k < info->totCombinations; ++k) { imgs.push_back(1.f); } CombinationHasher hasher{info}; SameValuesCombination comb{variables.getVariables().size()}; std::size_t each_var_size = variables.getVariables().front()->size(); for (std::size_t k = 0; k < each_var_size; ++k, comb.next()) { imgs[hasher(comb.get())] = 0; } data_ = std::move(imgs); } }; } // namespace Factor::Factor(const categoric::Group &vars, SimplyAntiCorrelatedTag) : Factor{std::make_shared<SimplyAntiCorrelatedFunction>(vars)} {} namespace { categoric::Group gather_variables(const std::vector<const Immutable *> &factors) { categoric::VariablesSet vars; for (const auto *factor : factors) { for (const auto &var : factor->function().vars().getVariables()) { auto vars_it = vars.find(var); if (vars_it == vars.end()) { vars.emplace(var); } else if (vars_it->get() != var.get()) { throw Error::make( var->name(), " appears multiple times, but in different variable instances"); } } } return categoric::Group{categoric::VariablesSoup{vars.begin(), vars.end()}}; } } // namespace Factor::Factor(const std::vector<const Immutable *> &factors) : Factor(gather_variables(factors)) { if (factors.empty()) { throw Error{"Empty factors container"}; } std::vector<const Immutable *> same_size_factors; std::vector<ImageFinder> finders; for (const auto *factor : factors) { if (factor->function().vars().getVariables() == function().vars().getVariables()) { same_size_factors.push_back(factor); } else { finders.emplace_back( factor->makeFinder(function().vars().getVariables())); } } categoric::GroupRange range(function().vars()); auto &recipient = functionMutable(); categoric::for_each_combination(range, [&recipient, &same_size_factors, &finders](const auto &comb) { float val = 1.f; for (auto it = same_size_factors.begin(); (it != same_size_factors.end()) && (val != 0); ++it) { val *= (*it)->function().findTransformed(comb); } for (auto it = finders.begin(); (it != finders.end()) && (val != 0); ++it) { val *= it->findTransformed(comb); } if (val != 0) { recipient.set(comb, val); } }); } namespace { std::vector<std::size_t> compute_new_positions(const categoric::VariablesSoup &old_order, const categoric::VariablesSoup &new_order) { std::vector<std::size_t> result; result.reserve(old_order.size()); for (const auto &var : old_order) { auto it = std::find(new_order.begin(), new_order.end(), var); result.push_back(std::distance(new_order.begin(), it)); } return result; } std::vector<std::size_t> get_permuted(const std::vector<std::size_t> &subject, const std::vector<std::size_t> &new_positions) { std::vector<std::size_t> result; result.resize(subject.size()); for (std::size_t p = 0; p < subject.size(); ++p) { result[new_positions[p]] = subject[p]; } return result; } } // namespace Factor Factor::cloneWithPermutedGroup(const categoric::Group &new_order) const { if (new_order.getVariablesSet() != function().vars().getVariablesSet()) { throw Error{"Invalid new order. The new order should be a permutation of " "the factor to clone"}; } auto data = std::make_shared<Function>(new_order); const auto new_positions = compute_new_positions( function().vars().getVariables(), data->vars().getVariables()); function().forEachCombination<false>( [&recipient = *data, &new_positions](const auto &comb, float img) { recipient.set(get_permuted(comb, new_positions), img); }); return data; } } // namespace EFG::factor
6,595
C++
.cpp
189
30.439153
80
0.655232
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,892
ImageFinder.cpp
andreacasalino_Easy-Factor-Graph/src/src/factor/ImageFinder.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/factor/ImageFinder.h> #include <optional> namespace EFG::factor { namespace { std::optional<std::size_t> find_var(const categoric::VariablesSoup &bigger_group, const categoric::VariablePtr &var) { for (std::size_t k = 0; k < bigger_group.size(); ++k) { if (bigger_group[k].get() == var.get()) { return k; } } return std::nullopt; } std::vector<std::size_t> get_indices(const categoric::VariablesSoup &distribution_group, const categoric::VariablesSoup &bigger_group) { if (distribution_group.size() > bigger_group.size()) { throw Error{"Invalid bigger_group to build a CombinationFinder"}; } std::vector<std::size_t> result; result.reserve(distribution_group.size()); for (const auto &distribution_var : distribution_group) { auto index_in_bigger = find_var(bigger_group, distribution_var); if (index_in_bigger.has_value()) { result.push_back(index_in_bigger.value()); } else { throw Error::make(distribution_var->name(), " was not found in the bigger group"); } } return result; } } // namespace ImageFinder::ImageFinder(std::shared_ptr<const Function> function, const categoric::VariablesSoup &bigger_group) : function_{function}, indices_in_bigger_group( get_indices(function_->vars().getVariables(), bigger_group)) {} std::vector<std::size_t> ImageFinder::extractSmallerCombination( const std::vector<std::size_t> &comb) const { std::vector<std::size_t> res; res.reserve(indices_in_bigger_group.size()); for (auto index : indices_in_bigger_group) { res.push_back(comb[index]); } return res; } } // namespace EFG::factor
1,876
C++
.cpp
56
29.196429
73
0.676957
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,893
Function.cpp
andreacasalino_Easy-Factor-Graph/src/src/factor/Function.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/factor/Function.h> #include <math.h> namespace EFG::factor { namespace { std::size_t sizes_prod(const std::vector<std::size_t> &sizes) { std::size_t res = 1; for (auto v : sizes) { res *= v; } return res; } std::size_t compute_critical_size(std::size_t tot_size, float prctg) { auto res = std::floor(tot_size * prctg); return static_cast<std::size_t>(res); } static constexpr std::size_t MIN_CRITICAL = 6; } // namespace std::shared_ptr<const Function::Info> make_info(const categoric::Group &vars) { auto res = std::make_shared<Function::Info>(); for (const auto &var : vars.getVariables()) { res->sizes.push_back(var->size()); } res->totCombinations = sizes_prod(res->sizes); res->critical_size = std::max<std::size_t>( compute_critical_size(res->totCombinations, 0.5f), MIN_CRITICAL); return res; } Function::SparseContainer Function::makeSparseContainer() { return SparseContainer{MIN_CRITICAL, CombinationHasher{info}}; } Function::Function(const categoric::Group &variables) : variables_{variables}, info{make_info(variables)}, data_{makeSparseContainer()} {} std::size_t Function::CombinationHasher::operator()( const std::vector<std::size_t> &comb) const { auto prod = info->totCombinations; std::size_t res = 0; for (std::size_t k = 0; k < info->sizes.size(); ++k) { prod /= info->sizes[k]; res += comb[k] * prod; } return res; } void Function::set(const std::vector<std::size_t> &combination, float image) { Visitor<SparseContainer, DenseContainer>{ [&combination, image = image, critical_size = info->critical_size, info = info, &data = data_](SparseContainer &c) { c[combination] = image; if (c.size() >= critical_size) { DenseContainer values; values.resize(info->totCombinations); for (auto &v : values) { v = 0; } CombinationHasher hasher{info}; for (const auto &[comb, img] : c) { values[hasher(comb)] = img; } data = std::move(values); } }, [&combination, image = image, info = info](DenseContainer &c) { c[CombinationHasher{info}(combination)] = image; }} .visit(data_); } float Function::findImage(const std::vector<std::size_t> &combination) const { float res; VisitorConst<SparseContainer, DenseContainer>{ [&combination, &res](const SparseContainer &c) { if (auto it = c.find(combination); it != c.end()) { res = it->second; } else { res = 0; } }, [&combination, &res, info = info](const DenseContainer &c) { CombinationHasher hasher{info}; res = c[hasher(combination)]; }} .visit(data_); return res; } float Function::findTransformed( const std::vector<std::size_t> &combination) const { float raw = findImage(combination); return transform(raw); } } // namespace EFG::factor
3,100
C++
.cpp
95
27.747368
79
0.639037
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,894
Mutable.cpp
andreacasalino_Easy-Factor-Graph/src/src/factor/Mutable.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/factor/Mutable.h> namespace EFG::factor { Mutable::Mutable(FunctionPtr data) : function_{data} { if (data == nullptr) { throw Error{"null data"}; } } void Mutable::set(const std::vector<std::size_t> &comb, float value) { if (value < 0.f) { throw Error("negative value is not possible"); } const auto &vars = function_->vars().getVariables(); if (comb.size() != vars.size()) { throw Error{"Invalid combination"}; } for (std::size_t k = 0; k < comb.size(); ++k) { if (vars[k]->size() <= comb[k]) { throw Error{"Invalid combination"}; } } function_->set(comb, value); } } // namespace EFG::factor
815
C++
.cpp
30
24.366667
70
0.64578
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,895
FactorExponential.cpp
andreacasalino_Easy-Factor-Graph/src/src/factor/FactorExponential.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/categoric/GroupRange.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <math.h> namespace EFG::factor { FactorExponential::FactorExponential(FunctionPtr data) : Immutable{data}, Mutable{data} {} FactorExponential::FactorExponential(const Factor &factor) : FactorExponential(factor, 1.f) {} namespace { class ExponentialFunction : public Function { public: ExponentialFunction(const Function &giver, float w) : Function{giver.vars()}, weigth{w} { std::vector<float> imgs; imgs.reserve(info->totCombinations); giver.forEachCombination<false>( [&imgs](const auto &, float img) { imgs.push_back(img); }); data_ = std::move(imgs); } void setWeight(float w) { weigth = w; }; float getWeight() const { return weigth; }; protected: float transform(float input) const override { return expf(weigth * input); } private: float weigth; }; } // namespace FactorExponential::FactorExponential(const Factor &factor, float weigth) : FactorExponential{ std::make_shared<ExponentialFunction>(factor.function(), weigth)} {} void FactorExponential::setWeight(float w) { static_cast<ExponentialFunction &>(functionMutable()).setWeight(w); } float FactorExponential::getWeight() const { return static_cast<const ExponentialFunction &>(function()).getWeight(); } FactorExponential::FactorExponential(const FactorExponential &o) : FactorExponential{ std::make_shared<ExponentialFunction>(o.function(), o.getWeight())} {} } // namespace EFG::factor
1,670
C++
.cpp
46
33.173913
80
0.737756
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,896
TrainSetImport.cpp
andreacasalino_Easy-Factor-Graph/src/src/io/TrainSetImport.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/io/TrainSetImport.h> #include "Utils.h" namespace EFG::io { train::TrainSet import_train_set(const std::string &file_name) { std::vector<std::vector<std::size_t>> combinations; useInStrem(file_name, [&combinations](std::ifstream &stream) { std::size_t line_numb = 0; std::size_t expected_size = 0; for_each_line(stream, [&](const std::string &line) { auto &&[combination, img] = parse_combination_image(line); if ((expected_size != 0) && (combination.size() != expected_size)) { throw Error::make("Invalid combination size at line ", std::to_string(line_numb)); } expected_size = combination.size(); combinations.emplace_back(std::move(expected_size)); ++line_numb; }); }); return train::TrainSet{combinations}; } } // namespace EFG::io
973
C++
.cpp
28
30.035714
74
0.647872
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,897
Utils.cpp
andreacasalino_Easy-Factor-Graph/src/src/io/Utils.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include "Utils.h" #include <sstream> namespace EFG::io { std::pair<std::vector<std::size_t>, float> parse_combination_image(const std::string &line) { std::stringstream buff{line}; std::vector<std::string> tokens; { std::string token; while (buff >> token) { tokens.emplace_back(std::move(token)); } } std::vector<std::size_t> comb; std::for_each( tokens.begin(), tokens.end() - 1, [&comb](const std::string &str) { comb.push_back(static_cast<std::size_t>(std::atoi(str.c_str()))); }); return std::make_pair(std::move(comb), static_cast<float>(std::atof(tokens.back().c_str()))); } void import_values(factor::Factor &recipient, const std::filesystem::path &file_name) { useInStrem(file_name, [&](std::ifstream &stream) { recipient.clear(); const std::size_t values_size = recipient.function().vars().getVariables().size(); for_each_line(stream, [&values_size, &recipient](const std::string &line) { auto &&[comb, img] = parse_combination_image(line); if (comb.size() != values_size) { throw Error{"Invalid file content"}; } recipient.set(comb, img); }); }); } void ImportHelper::importConst(const factor::ImmutablePtr &factor) { std::get<strct::FactorsConstInserter *>(model)->addConstFactor(factor); } void ImportHelper::importTunable( const std::shared_ptr<factor::FactorExponential> &factor, const std::optional<categoric::VariablesSet> &sharing_group) { if (auto ptr = std::get<train::FactorsTunableInserter *>(model); ptr) { if (sharing_group.has_value()) { this->cumulated.push_back(TunableCluster{factor, sharing_group.value()}); } else { ptr->addTunableFactor(factor); } return; } std::get<strct::FactorsConstInserter *>(model)->addConstFactor(factor); } void ImportHelper::importCumulatedTunable() const { auto [constInserter, tunableInserter] = model; for (const auto &remaining : cumulated) { if (tunableInserter) { tunableInserter->addTunableFactor(remaining.factor, remaining.group_owning_w_to_share); continue; } constInserter->addConstFactor(remaining.factor); } } } // namespace EFG::io
2,392
C++
.cpp
70
29.142857
79
0.655575
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,898
Importer.cpp
andreacasalino_Easy-Factor-Graph/src/src/io/xml/Importer.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_XML_IO #include <EasyFactorGraph/io/xml/Importer.h> #include "../Utils.h" #include <XML-Parser/Parser.h> namespace EFG::io::xml { namespace { const std::string *try_access_attribute(const xmlPrs::Tag &subject, const std::string &name) { auto it = subject.getAttributes().find(name); if (it == subject.getAttributes().end()) { return nullptr; } return &it->second; } const std::string &access_attribute(const xmlPrs::Tag &subject, const std::string &name) { const auto *attr = try_access_attribute(subject, name); if (nullptr == attr) { throw Error::make(name, " is an inexistent attribute"); } return *attr; } template <typename K, typename V, typename Predicate> void for_each_key(const std::unordered_multimap<K, V> &subject, const K &key, const Predicate &pred) { auto range = subject.equal_range(key); for (auto it = range.first; it != range.second; ++it) { pred(it->second); } } categoric::VariablePtr findVariable(const std::string &name, const categoric::VariablesSet &variables) { const auto itV = std::find_if(variables.begin(), variables.end(), [&name](const categoric::VariablePtr &var) { return var->name() == name; }); if (itV == variables.end()) { throw Error("Inexistent variable"); } return *itV; } categoric::Group importGroup(const xmlPrs::Tag &tag, const categoric::VariablesSet &variables) { categoric::VariablesSoup group; for_each_key(tag.getAttributes(), xmlPrs::Name{"var"}, [&variables, &group](const std::string &name) { group.push_back(findVariable(name, variables)); }); if ((group.size() != 1) && (group.size() != 2)) { throw Error("only unary or binary factor are supported"); } return categoric::Group{group}; } std::shared_ptr<factor::Factor> importFactor(const std::string &prefix, const xmlPrs::Tag &tag, const categoric::VariablesSet &variables) { auto group = importGroup(tag, variables); const auto *corr = try_access_attribute(tag, "Correlation"); if (nullptr != corr) { if (*corr == "T") { return std::make_shared<factor::Factor>( categoric::Group{group.getVariables()}, factor::Factor::SimplyCorrelatedTag{}); } if (*corr == "F") { return std::make_shared<factor::Factor>( categoric::Group{group.getVariables()}, factor::Factor::SimplyAntiCorrelatedTag{}); } throw Error("invalid option for Correlation"); } std::shared_ptr<factor::Factor> result = std::make_shared<factor::Factor>(categoric::Group{group.getVariables()}); const auto *source = try_access_attribute(tag, "Source"); if (nullptr != source) { import_values(*result, prefix + "/" + *source); return result; } for_each_key(tag.getNested(), xmlPrs::Name{"Distr_val"}, [&result](const xmlPrs::TagPtr &comb) { std::vector<std::size_t> combination; for_each_key(comb->getAttributes(), xmlPrs::Name{"v"}, [&combination](const std::string &var) { combination.push_back(std::atoi(var.c_str())); }); const float val = static_cast<float>( std::atof(access_attribute(*comb, "D").c_str())); result->set(combination, val); }); return result; } void importPotential(const std::string &prefix, const xmlPrs::Tag &tag, const categoric::VariablesSet &variables, ImportHelper &importer) { auto shape = importFactor(prefix, tag, variables); const auto *w = try_access_attribute(tag, "weight"); if (nullptr == w) { importer.importConst(shape); return; } auto factor = std::make_shared<factor::FactorExponential>( *shape, static_cast<float>(std::atof(w->c_str()))); const auto *tunab = try_access_attribute(tag, "tunability"); if ((nullptr != tunab) && (*tunab == "Y")) { auto share_tag_it = tag.getNested().find("Share"); if (share_tag_it == tag.getNested().end()) { importer.importTunable(factor); } else { auto group = importGroup(*share_tag_it->second, variables).getVariablesSet(); importer.importTunable(factor, group); } return; } importer.importConst(factor); } } // namespace std::unordered_map<std::string, std::size_t> Importer::convert(Inserters subject, const std::filesystem::path &file_path) { auto maybe_parsed_root = xmlPrs::parse_xml(file_path.string()); auto maybe_parsed_error = std::get_if<xmlPrs::Error>(&maybe_parsed_root); if (nullptr != maybe_parsed_error) { throw *maybe_parsed_error; } const auto &parsed_root = std::get<xmlPrs::Root>(maybe_parsed_root); // import variables categoric::VariablesSet variables; std::unordered_map<std::string, std::size_t> evidences; for_each_key( parsed_root.getNested(), xmlPrs::Name{"Variable"}, [&variables, &evidences](const xmlPrs::TagPtr &var) { const auto &name = access_attribute(*var, "name"); const auto &size = access_attribute(*var, "Size"); auto new_var = categoric::make_variable(std::atoi(size.c_str()), name); if (variables.find(new_var) != variables.end()) { throw Error::make(name, " is a multiple times specified variable "); } variables.emplace(new_var); const auto *obs_flag = try_access_attribute(*var, "evidence"); if (nullptr != obs_flag) { const std::size_t val = static_cast<std::size_t>(atoi(obs_flag->c_str())); evidences.emplace(name, val); } }); // import potentials ImportHelper importer{subject}; for_each_key(parsed_root.getNested(), xmlPrs::Name{"Potential"}, [&](const xmlPrs::TagPtr &factor) { importPotential(file_path.parent_path().string(), *factor, variables, importer); }); importer.importCumulatedTunable(); return evidences; } } // namespace EFG::io::xml #endif
6,449
C++
.cpp
163
31.90184
86
0.608744
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,899
Exporter.cpp
andreacasalino_Easy-Factor-Graph/src/src/io/xml/Exporter.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_XML_IO #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/io/xml/Exporter.h> #include "../Utils.h" #include <XML-Parser/Tag.h> namespace EFG::io::xml { namespace { xmlPrs::Tag &printVariable(const categoric::VariablePtr &var, xmlPrs::Tag &recipient) { auto &var_tag = recipient.addNested("Variable"); auto &attributes = var_tag.getAttributes(); attributes.emplace("name", var->name()); attributes.emplace("Size", std::to_string(var->size())); return var_tag; } void printGroup(const categoric::Group &group, xmlPrs::Tag &recipient) { auto &attributes = recipient.getAttributes(); for (const auto &var : group.getVariables()) { attributes.emplace("var", var->name()); } } xmlPrs::Tag &printPotential(const factor::Immutable &distr, xmlPrs::Tag &recipient) { auto &pot_tag = recipient.addNested("Potential"); printGroup(distr.function().vars(), pot_tag); distr.function().forEachNonNullCombination<false>( [&](const auto &comb, float img) { auto &comb_val = pot_tag.addNested("Distr_val"); auto &attributes = comb_val.getAttributes(); attributes.emplace("D", std::to_string(img)); for (auto v : comb) { attributes.emplace("v", std::to_string(v)); } }); return pot_tag; } xmlPrs::Tag &printExpPotential(const factor::FactorExponential &distr, xmlPrs::Tag &recipient) { auto &pot_tag = printPotential(distr, recipient); pot_tag.getAttributes().emplace("weight", std::to_string(distr.getWeight())); return pot_tag; } } // namespace void Exporter::convert(const std::filesystem::path &out, Getters subject, const std::string &model_name) { useOutStrem(out, [&](std::ofstream &stream) { convert(stream, subject, model_name); }); } void Exporter::convert(std::ostream &out, Getters subject, const std::string &model_name) { auto [state, constGetter, tunableGetter] = subject; xmlPrs::Root exp_root(model_name); // hidden set for (const auto &hidden_var : state->getHiddenVariables()) { printVariable(hidden_var, exp_root); } // evidence set for (const auto &[evidence_var, evidence_val] : state->getEvidences()) { auto &var_tag = printVariable(evidence_var, exp_root); var_tag.getAttributes().emplace("evidence", std::to_string(evidence_val)); } // const factors for (const auto &const_factor : constGetter->getConstFactors()) { std::shared_ptr<const factor::FactorExponential> as_const_exp_factor = std::dynamic_pointer_cast<const factor::FactorExponential, const factor::Immutable>(const_factor); if (nullptr == as_const_exp_factor) { printPotential(*const_factor, exp_root); } else { auto &factor_tag = printExpPotential(*as_const_exp_factor, exp_root); factor_tag.getAttributes().emplace("tunability", "N"); } } if (tunableGetter) { // tunable factors struct Visitor { xmlPrs::Root &root; void operator()(const train::FactorExponentialPtr &factor) const { printExpPotential(*factor, root) .getAttributes() .emplace("tunability", "Y"); } void operator()(const train::TunableClusters &cluster) const { printExpPotential(*cluster.front(), root) .getAttributes() .emplace("tunability", "Y"); const auto &vars = cluster.front()->function().vars(); std::for_each(cluster.begin() + 1, cluster.end(), [&](const train::FactorExponentialPtr &factor) { auto &factor_tag = printExpPotential(*factor, root); factor_tag.getAttributes().emplace("tunability", "Y"); printGroup(vars, factor_tag["Share"]); }); } } visitor{exp_root}; for (const auto &cluster : tunableGetter->getTunableClusters()) { std::visit(visitor, cluster); } } exp_root.print(out); } } // namespace EFG::io::xml #endif
4,236
C++
.cpp
110
31.872727
79
0.636938
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,900
Importer.cpp
andreacasalino_Easy-Factor-Graph/src/src/io/json/Importer.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_JSON_IO #include <EasyFactorGraph/io/json/Importer.h> #include "../Utils.h" namespace EFG::io::json { nlohmann::json Importer::importJsonFromFile(const std::filesystem::path &file_path) { nlohmann::json res; useInStrem(file_path, [&res](std::ifstream &stream) { res = nlohmann::json::parse(stream); }); return res; } namespace { const nlohmann::json *try_access(const nlohmann::json &subject, const std::string &name) { return subject.contains(name) ? &subject[name] : nullptr; } const nlohmann::json &access(const nlohmann::json &subject, const std::string &name) { if (auto res = try_access(subject, name); res) { return *res; } throw Error::make(name, " is inexistent"); } std::string to_string(const nlohmann::json &subject) { if (subject.is_string()) { auto raw_dump = subject.dump(); return std::string{raw_dump, 1, raw_dump.size() - 2}; } throw Error{"Expected a string"}; } categoric::VariablePtr findVariable(const std::string &name, const categoric::VariablesSet &variables) { const auto itV = std::find_if(variables.begin(), variables.end(), [&name](const categoric::VariablePtr &var) { return var->name() == name; }); if (itV == variables.end()) { throw Error("Inexistent variable"); } return *itV; } categoric::Group importGroup(const nlohmann::json &subject, const categoric::VariablesSet &variables) { categoric::VariablesSoup group; for (const auto &var : subject) { group.push_back(findVariable(to_string(var), variables)); } if ((group.size() != 1) && (group.size() != 2)) { throw Error("only unary or binary factor are supported"); } return categoric::Group{group}; } std::shared_ptr<factor::Factor> importFactor(const nlohmann::json &subject, const categoric::VariablesSet &variables) { auto group = importGroup(access(subject, "Variables"), variables); const auto *corr = try_access(subject, "Correlation"); if (nullptr != corr) { if (to_string(*corr) == "T") { return std::make_shared<factor::Factor>( categoric::Group{group.getVariables()}, factor::Factor::SimplyCorrelatedTag{}); } if (to_string(*corr) == "F") { return std::make_shared<factor::Factor>( categoric::Group{group.getVariables()}, factor::Factor::SimplyAntiCorrelatedTag{}); } throw Error("invalid option for Correlation"); } std::shared_ptr<factor::Factor> result = std::make_shared<factor::Factor>(categoric::Group{group.getVariables()}); for (const auto &comb : access(subject, "Distr_val")) { std::vector<std::size_t> combination; for (const auto &v : comb["v"]) { combination.push_back(std::atoi(to_string(v).c_str())); } const float val = static_cast<float>(std::atof(to_string(access(comb, "D")).c_str())); result->set(std::move(combination), val); } return result; } void importPotential(const nlohmann::json &subject, const categoric::VariablesSet &variables, ImportHelper &importer) { auto shape = importFactor(subject, variables); const auto *w = try_access(subject, "weight"); if (nullptr == w) { importer.importConst(shape); return; } auto factor = std::make_shared<factor::FactorExponential>( *shape, static_cast<float>(std::atof(to_string(*w).c_str()))); const auto *tunab = try_access(subject, "tunability"); if ((nullptr != tunab) && (to_string(*tunab) == "Y")) { const auto *share_tag = try_access(subject, "Share"); if (nullptr == share_tag) { importer.importTunable(factor); } else { auto group = importGroup(*share_tag, variables).getVariablesSet(); importer.importTunable(factor, group); } return; } importer.importConst(factor); } } // namespace std::unordered_map<std::string, std::size_t> Importer::convert(Inserters recipient, const nlohmann::json &source) { // import variables categoric::VariablesSet variables; std::unordered_map<std::string, std::size_t> evidences; for (const auto &var : source["Variables"]) { const auto name = to_string(access(var, "name")); const auto size = to_string(access(var, "Size")); auto new_var = categoric::make_variable(std::atoi(size.c_str()), name); if (variables.find(new_var) != variables.end()) { throw Error::make(name, " is a multiple times specified variable "); } variables.emplace(new_var); const auto *obs_flag = try_access(var, "evidence"); if (nullptr != obs_flag) { const std::size_t val = static_cast<std::size_t>(std::atoi(to_string(*obs_flag).c_str())); evidences.emplace(name, val); } } // import potentials ImportHelper importer(recipient); for (const auto &factor : source["Potentials"]) { importPotential(factor, variables, importer); } importer.importCumulatedTunable(); return evidences; } } // namespace EFG::io::json #endif
5,276
C++
.cpp
145
30.827586
79
0.643458
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,901
Exporter.cpp
andreacasalino_Easy-Factor-Graph/src/src/io/json/Exporter.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_JSON_IO #include <EasyFactorGraph/io/json/Exporter.h> #include "../Utils.h" namespace EFG::io::json { void Exporter::exportToFile(const nlohmann::json &source, const std::filesystem::path &out) { useOutStrem(out, [&source](std::ofstream &stream) { stream << source.dump(); }); } namespace { void printVariable(const categoric::VariablePtr &var, nlohmann::json &recipient) { recipient["name"] = var->name(); recipient["Size"] = std::to_string(var->size()); } void printGroup(const categoric::Group &group, nlohmann::json &recipient) { for (const auto &var : group.getVariables()) { auto &added = recipient.emplace_back(); added = var->name(); } } nlohmann::json &printPotential(const factor::Immutable &distr, nlohmann::json &recipient) { auto &potential = recipient.emplace_back(); printGroup(distr.function().vars(), potential["Variables"]); auto &Distr_val = potential["Distr_val"]; distr.function().forEachNonNullCombination<false>( [&](const auto &comb, float img) { auto &Distr_val_added = Distr_val.emplace_back(); Distr_val_added["D"] = std::to_string(img); auto &values = Distr_val_added["v"]; for (const auto &v : comb) { values.emplace_back() = std::to_string(v); } }); return potential; } nlohmann::json &printExpPotential(const factor::FactorExponential &distr, nlohmann::json &recipient) { auto &pot_tag = printPotential(distr, recipient); pot_tag["weight"] = std::to_string(distr.getWeight()); return pot_tag; } } // namespace void Exporter::convert(nlohmann::json &recipient, Getters subject) { auto [state, constGetter, tunableGetter] = subject; // hidden set auto &variables = recipient["Variables"]; for (const auto &hidden_var : state->getHiddenVariables()) { auto &new_var = variables.emplace_back(); printVariable(hidden_var, new_var); } // evidence set for (const auto &[evidence_var, evidence_val] : state->getEvidences()) { auto &new_var = variables.emplace_back(); printVariable(evidence_var, new_var); new_var["evidence"] = std::to_string(evidence_val); } auto &potentials = recipient["Potentials"]; // const factors for (const auto &const_factor : constGetter->getConstFactors()) { std::shared_ptr<const factor::FactorExponential> as_const_exp_factor = std::dynamic_pointer_cast<const factor::FactorExponential, const factor::Immutable>(const_factor); if (nullptr == as_const_exp_factor) { printPotential(*const_factor, potentials); } else { auto &factor_tag = printExpPotential(*as_const_exp_factor, potentials); factor_tag["tunability"] = "N"; } } if (tunableGetter) { // tunable factors struct Visitor { nlohmann::json &potentials; void operator()(const train::FactorExponentialPtr &factor) const { printExpPotential(*factor, potentials)["tunability"] = "Y"; } void operator()(const train::TunableClusters &cluster) const { printExpPotential(*cluster.front(), potentials)["tunability"] = "Y"; const auto &vars = cluster.front()->function().vars(); std::for_each(cluster.begin() + 1, cluster.end(), [&](const train::FactorExponentialPtr &factor) { auto &factor_json = printExpPotential(*factor, potentials); factor_json["tunability"] = "Y"; printGroup(vars, factor_json["Share"]); }); } } visitor{potentials}; for (const auto &cluster : tunableGetter->getTunableClusters()) { std::visit(visitor, cluster); } } } } // namespace EFG::io::json #endif
3,988
C++
.cpp
103
31.951456
77
0.630614
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,902
Group.cpp
andreacasalino_Easy-Factor-Graph/src/src/categoric/Group.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/Group.h> namespace EFG::categoric { VariablesSet to_vars_set(const VariablesSoup &soup) { VariablesSet result; for (const auto &var : soup) { result.emplace(var); } return result; } Group::Group(const VariablesSoup &group) : group(group), group_sorted(to_vars_set(group)) { if (group.empty()) { throw Error{"Variables group can't be empty"}; } if (group.size() != group_sorted.size()) { throw Error{"Variables group with multiple variables with same name"}; } } Group::Group(const VariablePtr &var) { group.push_back(var); group_sorted.emplace(var); } void Group::add(const VariablePtr &var) { auto it = group_sorted.find(var); if (it == group_sorted.end()) { group.push_back(var); group_sorted.emplace(var); return; } throw Error::make(var->name(), ", already existing inside group of variables"); } void Group::replaceVariables(const VariablesSoup &new_variables) { auto new_group_sorted = to_vars_set(new_variables); if (new_group_sorted.size() != group.size()) { throw Error{"Invalid new variables group"}; } for (std::size_t k = 0; k < new_variables.size(); ++k) { if (new_variables[k]->size() != group[k]->size()) { throw Error{"Invalid new variables group"}; } } group = new_variables; group_sorted = std::move(new_group_sorted); } std::size_t Group::size() const { std::size_t S = 1; for (const auto &var : group) { S *= var->size(); } return S; } VariablesSet &operator-=(VariablesSet &subject, const VariablesSet &to_remove) { for (const auto &rem : to_remove) { auto it = subject.find(rem); if (it != subject.end()) { subject.erase(it); } } return subject; } VariablesSet get_complementary(const VariablesSet &entire_set, const VariablesSet &subset) { VariablesSet result = entire_set; result -= subset; return result; } } // namespace EFG::categoric
2,134
C++
.cpp
75
24.853333
80
0.665366
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,903
GroupRange.cpp
andreacasalino_Easy-Factor-Graph/src/src/categoric/GroupRange.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/GroupRange.h> namespace EFG::categoric { GroupRange::Data::Data(const std::vector<size_t> &s, bool eor) : sizes{s}, end_of_range{eor} { combination.resize(sizes.size()); for (auto &v : combination) { v = 0; } } namespace { std::vector<size_t> get_sizes(const Group &variables) { std::vector<size_t> result; result.reserve(variables.size()); for (const auto &var : variables.getVariables()) { result.push_back(var->size()); } return result; } } // namespace GroupRange::GroupRange(const std::vector<std::size_t> &sizes) { data.emplace(sizes, false); } GroupRange::GroupRange(const Group &variables) : GroupRange{get_sizes(variables)} {} GroupRange::GroupRange(const GroupRange &o) { if (o.data) { data.emplace(o.data->sizes, o.data->end_of_range); data->combination = o.data->combination; } } GroupRange &GroupRange::operator++() { if (!data.has_value()) { throw Error{"GroupRange not incrementable"}; } auto &comb = data->combination; std::size_t k = comb.size() - 1; while (true) { if (++comb[k] == data->sizes[k]) { if (k == 0) { this->data->end_of_range = true; data.reset(); return *this; } else { comb[k] = 0; --k; } } else break; } return *this; } bool operator==(const GroupRange &a, const GroupRange &b) { return a.isEqual(b); } bool operator!=(const GroupRange &a, const GroupRange &b) { return !a.isEqual(b); } } // namespace EFG::categoric
1,681
C++
.cpp
65
22.507692
63
0.651119
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,904
Variable.cpp
andreacasalino_Easy-Factor-Graph/src/src/categoric/Variable.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/Variable.h> namespace EFG::categoric { Variable::Variable(std::size_t size, const std::string &name) : size_(size), name_(name) { if (name.size() == 0) throw Error("Empty name for Variable forbidden"); if (size == 0) throw Error("Null size for Variable forbidden"); } VariablePtr make_variable(std::size_t size, const std::string &name) { return std::make_shared<Variable>(size, name); } } // namespace EFG::categoric
621
C++
.cpp
20
28.75
70
0.707358
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,905
SpecialFactors.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/SpecialFactors.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/SpecialFactors.h> #include <cmath> #include <limits> #include <algorithm> namespace EFG::factor { UnaryFactor::UnaryFactor(FunctionPtr data) : Factor{data}, variable{data->vars().getVariables().front()} { if (data->vars().getVariables().size() != 1) { throw Error{"Unary factor can refer only to unary group"}; } } float UnaryFactor::diff(const UnaryFactor &o) const { auto this_prob = getProbabilities(); auto o_prob = o.getProbabilities(); float res = 0; for (std::size_t k = 0; k < this_prob.size(); ++k) { res += std::abs(this_prob[k] - o_prob[k]); } return res; } namespace { class MergableFunction : public Function { public: MergableFunction(const categoric::VariablePtr &var) : Function{categoric::Group{var}} { std::vector<float> imgs; for (std::size_t k = 0; k < var->size(); ++k) { imgs.push_back(1.f); } data_ = std::move(imgs); imgs_ = std::get_if<std::vector<float>>(&data_); } void merge(const Function &subject) { auto it = imgs_->begin(); subject.forEachCombination<true>([&it](const auto &, float img) { *it *= img; ++it; }); } void normalize() { float coeff = 1.f / *std::max_element(imgs_->begin(), imgs_->end()); for (auto &val : *imgs_) { val *= coeff; } } private: std::vector<float> *imgs_; }; } // namespace MergedUnaries::MergedUnaries(const categoric::VariablePtr &var) : UnaryFactor{std::make_shared<MergableFunction>(var)} {} MergedUnaries::MergedUnaries(const std::vector<const Immutable *> &factors) : UnaryFactor(std::make_shared<MergableFunction>( factors.front()->function().vars().getVariables().front())) { for (const auto *factor : factors) { merge(*factor); } normalize(); } void MergedUnaries::merge(const Immutable &to_merge) { const auto &vars = to_merge.function().vars().getVariables(); if (vars.size() != 1) { throw Error{"Invalid factor"}; } if (vars.front().get() != this->variable.get()) { throw Error{"Invalid factor"}; } static_cast<MergableFunction &>(functionMutable()).merge(to_merge.function()); } void MergedUnaries::normalize() { static_cast<MergableFunction &>(functionMutable()).normalize(); } namespace { categoric::VariablePtr get_other_var(const Immutable &binary_factor, const categoric::VariablePtr &var) { const auto &vars = binary_factor.function().vars().getVariables(); if (2 != vars.size()) { throw Error{"invalid binary factor"}; } return (vars.front() == var) ? vars.back() : vars.front(); } void get_positions(const Immutable &binary_factor, const categoric::VariablePtr &unary_factor_var, std::size_t &unary_factor_var_pos, std::size_t &other_var_pos) { unary_factor_var_pos = 0; other_var_pos = 1; if (binary_factor.function().vars().getVariables().back().get() == unary_factor_var.get()) { std::swap(unary_factor_var_pos, other_var_pos); } } } // namespace Evidence::Evidence(const Immutable &binary_factor, const categoric::VariablePtr &evidence_var, const std::size_t evidence) : UnaryFactor(std::make_shared<Function>( get_other_var(binary_factor, evidence_var))) { std::size_t pos_evidence; std::size_t pos_hidden; get_positions(binary_factor, getVariable(), pos_hidden, pos_evidence); auto &data = functionMutable(); binary_factor.function().forEachCombination<true>( [&](const auto &comb, float img) { if (comb[pos_evidence] == evidence) { data.set(std::vector<std::size_t>{comb[pos_hidden]}, img); } }); } Indicator::Indicator(const categoric::VariablePtr &var, std::size_t value) : UnaryFactor(std::make_shared<Function>(var)) { if (value >= var->size()) { throw Error{"Invalid indicator factor"}; } functionMutable().set(std::vector<std::size_t>{value}, 1.f); } namespace { template <typename ReducerT> void fill_message(const UnaryFactor &merged_unaries, const Immutable &binary_factor, Function &recipient) { std::size_t message_pos; std::size_t sender_pos; get_positions(binary_factor, merged_unaries.getVariable(), message_pos, sender_pos); std::size_t message_size = binary_factor.function().vars().getVariables()[message_pos]->size(); for (std::size_t r = 0; r < message_size; ++r) { ReducerT reducer{}; merged_unaries.function().forEachCombination<true>( [&](const auto &sender_comb, float sender_val) { std::vector<std::size_t> binary_factor_comb; binary_factor_comb.resize(2); binary_factor_comb[sender_pos] = sender_comb.front(); binary_factor_comb[message_pos] = r; reducer.update(sender_val * binary_factor.function().findTransformed( binary_factor_comb)); }); recipient.set(std::vector<std::size_t>{r}, reducer.val); } } } // namespace MessageSUM::MessageSUM(const UnaryFactor &merged_unaries, const Immutable &binary_factor) : UnaryFactor(std::make_shared<Function>( get_other_var(binary_factor, merged_unaries.getVariable()))) { struct Reducer { void update(float v) { val += v; } float val = 0; }; fill_message<Reducer>(merged_unaries, binary_factor, functionMutable()); } MessageMAP::MessageMAP(const UnaryFactor &merged_unaries, const Immutable &binary_factor) : UnaryFactor(std::make_shared<Function>( get_other_var(binary_factor, merged_unaries.getVariable()))) { struct Reducer { void update(float v) { val = std::max<float>(val, v); } float val = std::numeric_limits<float>::min(); }; fill_message<Reducer>(merged_unaries, binary_factor, functionMutable()); } } // namespace EFG::factor
6,070
C++
.cpp
169
30.763314
80
0.649949
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,906
BaselineLoopyPropagator.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/BaselineLoopyPropagator.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/structure/BaselineLoopyPropagator.h> #include <algorithm> namespace EFG::strct { namespace { bool have_no_changing_deps( const HiddenCluster::TopologyInfo &subject, const std::unordered_set<const Node::Connection *> &will_change) { auto it = std::find_if(subject.dependencies.begin(), subject.dependencies.end(), [&will_change](const Node::Connection *dep) { return will_change.find(dep) != will_change.end(); }); return it == subject.dependencies.end(); } using Infoes = std::vector<std::vector<HiddenCluster::TopologyInfo *>>; Infoes compute_loopy_order(HiddenCluster &cluster, std::vector<float> &variations) { Infoes result; if (variations.size() > 1) { std::list<HiddenCluster::TopologyInfo *> open; for (auto &info : *cluster.connectivity.get()) { open.push_back(&info); } // multithreaded computation while (!open.empty()) { std::unordered_set<const Node::Connection *> should_not_change; std::unordered_set<const Node::Connection *> will_change; auto &new_tasks = result.emplace_back(); auto open_it = open.begin(); while (open_it != open.end()) { if ((should_not_change.find((*open_it)->connection) == should_not_change.end()) && have_no_changing_deps(**open_it, will_change)) { will_change.emplace((*open_it)->connection); for (const auto *dep : (*open_it)->dependencies) { should_not_change.emplace(dep); } new_tasks.push_back(*open_it); open_it = open.erase(open_it); } else { ++open_it; } } } } else { auto &new_tasks = result.emplace_back(); new_tasks.reserve(cluster.connectivity.get()->size()); for (auto &task : *cluster.connectivity.get()) { new_tasks.push_back(&task); } } return result; } static constexpr float DEFAULT_VARIATION_TOLLERANCE = static_cast<float>(1e-3); } // namespace bool BaselineLoopyPropagator::propagateBelief(HiddenCluster &subject, PropagationKind kind, const PropagationContext &context, Pool &pool) { // set message to ones for (auto *node : subject.nodes) { for (auto &[sender, connection] : node->active_connections) { connection.message = std::make_unique<factor::MergedUnaries>(node->variable); } } std::vector<float> variations; variations.resize(pool.size()); auto order = compute_loopy_order(subject, variations); for (std::size_t iter = 0; iter < context.max_iterations_loopy_propagation; ++iter) { for (auto &variation : variations) { variation = 0; } for (auto &tasks : order) { Tasks lambdas; lambdas.reserve(tasks.size()); for (auto *task : tasks) { lambdas.emplace_back( [task = task, kind = kind, &variations](const std::size_t th_id) { auto &variation = variations[th_id]; auto candidate = task->updateMessage(kind).value(); variation = std::max<float>(variation, candidate); }); } pool.parallelFor(lambdas); } if (*std::max_element(variations.begin(), variations.end()) < DEFAULT_VARIATION_TOLLERANCE) { return true; } } return false; } } // namespace EFG::strct
3,625
C++
.cpp
101
28.257426
80
0.603071
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,907
GibbsSampler.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/GibbsSampler.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/structure/GibbsSampler.h> #include <EasyFactorGraph/structure/SpecialFactors.h> #include <algorithm> #include <time.h> namespace EFG::strct { UniformSampler::UniformSampler() { auto random_seed = static_cast<unsigned int>(time(NULL)); resetSeed(random_seed); } std::size_t UniformSampler::sampleFromDiscrete( const std::vector<float> &distribution) const { float s = this->sample(); float cumul = 0.f; for (std::size_t k = 0; k < distribution.size(); ++k) { cumul += distribution[k]; if (s <= cumul) { return k; } } return distribution.size() - 1; } void UniformSampler::resetSeed(std::size_t newSeed) { this->generator.seed(static_cast<unsigned int>(newSeed)); } bool GibbsSampler::SamplerNode::noChangingDeps( const std::unordered_set<const std::size_t *> &will_change) const { auto it = std::find_if(dynamic_dependencies.begin(), dynamic_dependencies.end(), [&will_change](const DynamicDependency &dep) { return will_change.find(dep.sender_value_in_combination) != will_change.end(); }); return it == dynamic_dependencies.end(); } std::vector<GibbsSampler::SamplerNode> GibbsSampler::makeSamplerNodes( std::vector<std::size_t> &combination_buffer) const { const auto vars_order = getAllVariables(); const std::size_t size = vars_order.size(); combination_buffer.resize(size); SmartMap<categoric::Variable, std::size_t *> combination_values_map; for (std::size_t k = 0; k < size; ++k) { auto *comb_ptr = &combination_buffer[k]; *comb_ptr = 0; combination_values_map.emplace(vars_order[k], comb_ptr); } std::vector<SamplerNode> result; result.reserve(size); const auto &state = this->state(); for (const auto &[var, val] : state.evidences) { *combination_values_map.find(var)->second = val; } for (auto &cluster : state.clusters) { for (auto *node : cluster.nodes) { node->updateMergedUnaries(); auto &added_node = result.emplace_back(); added_node.value_in_combination = combination_values_map.find(node->variable)->second; added_node.static_dependencies = node->merged_unaries.get(); for (const auto &[connected_node, connection] : node->active_connections) { auto &added_dep = added_node.dynamic_dependencies.emplace_back(); added_dep.sender = connected_node->variable; added_dep.sender_value_in_combination = combination_values_map.find(connected_node->variable)->second; added_dep.factor = connection.factor; } } } return result; } namespace { Task make_sampling_task(const GibbsSampler::SamplerNode &subject, std::vector<UniformSampler> &engines) { return [&subject, &engines](const std::size_t thread_id) { std::vector<const factor::Immutable *> factors = { subject.static_dependencies}; std::list<factor::Evidence> marginalized; for (const auto &dep : subject.dynamic_dependencies) { factors.push_back(&marginalized.emplace_back( *dep.factor, dep.sender, *dep.sender_value_in_combination)); } factor::MergedUnaries merged(factors); *subject.value_in_combination = engines[thread_id].sampleFromDiscrete(merged.getProbabilities()); }; } std::vector<Tasks> make_sampling_tasks(const std::vector<GibbsSampler::SamplerNode> &nodes, std::vector<UniformSampler> &engines, const std::optional<std::size_t> &seed, Pool &pool) { engines.resize(pool.size()); if (std::nullopt != seed) { std::size_t s = *seed; for (auto &engine : engines) { engine.resetSeed(s); s += 5; } } std::vector<Tasks> result; if (1 == pool.size()) { auto &new_tasks = result.emplace_back(); for (const auto &node : nodes) { new_tasks.emplace_back(make_sampling_task(node, engines)); } } else { std::list<const GibbsSampler::SamplerNode *> open; for (auto &node : nodes) { open.push_back(&node); } while (!open.empty()) { std::unordered_set<const std::size_t *> should_not_change; std::unordered_set<const std::size_t *> will_change; auto &new_tasks = result.emplace_back(); auto open_it = open.begin(); while (open_it != open.end()) { if ((should_not_change.find((*open_it)->value_in_combination) == should_not_change.end()) && (*open_it)->noChangingDeps(will_change)) { will_change.emplace((*open_it)->value_in_combination); for (const auto &dep : (*open_it)->dynamic_dependencies) { should_not_change.emplace(dep.sender_value_in_combination); } new_tasks.emplace_back(make_sampling_task(**open_it, engines)); open_it = open.erase(open_it); } else { ++open_it; } } } } return result; } std::pair<std::size_t, std::size_t> delta_and_burn_out(const GibbsSampler::SamplesGenerationContext &context) { std::size_t delta_iterations = context.delta_iterations.has_value() ? context.delta_iterations.value() : static_cast<std::size_t>(ceil(context.samples_number * 0.1)); delta_iterations = std::max<std::size_t>(1, delta_iterations); std::size_t burn_out = context.transient.has_value() ? context.transient.value() : 10 * delta_iterations; return std::make_pair(delta_iterations, burn_out); } void evolve_samples(strct::Pool &pool, const std::vector<Tasks> &sample_jobs, std::size_t iterations) { for (std::size_t iter = 0; iter < iterations; ++iter) { for (const auto &tasks : sample_jobs) { pool.parallelFor(tasks); } } } } // namespace std::vector<std::vector<std::size_t>> GibbsSampler::makeSamples(const SamplesGenerationContext &context, const std::size_t threads) { ScopedPoolActivator activator(*this, threads); auto [delta_iterations, burn_out] = delta_and_burn_out(context); std::vector<std::size_t> combination; auto sampling_nodes = makeSamplerNodes(combination); std::vector<UniformSampler> engines; auto &pool = getPool(); auto sampling_tasks = make_sampling_tasks(sampling_nodes, engines, context.seed, pool); evolve_samples(pool, sampling_tasks, burn_out); std::vector<std::vector<std::size_t>> result; result.reserve(context.samples_number); while (result.size() != context.samples_number) { result.push_back(combination); evolve_samples(pool, sampling_tasks, delta_iterations); } return result; } } // namespace EFG::strct
6,822
C++
.cpp
180
32.005556
80
0.653631
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,908
QueryManager.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/QueryManager.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/misc/Visitor.h> #include <EasyFactorGraph/structure/QueryManager.h> #include <EasyFactorGraph/structure/SpecialFactors.h> #include <EasyFactorGraph/structure/bases/StateAware.h> namespace EFG::strct { namespace { factor::MergedUnaries gather_incoming_messages(Node &subject) { std::vector<const factor::Immutable *> messages = { subject.merged_unaries.get()}; for (const auto &[connected_node, message] : subject.active_connections) { messages.push_back(message.message.get()); } if (messages.empty()) { return factor::MergedUnaries{subject.variable}; } return factor::MergedUnaries{messages}; } std::vector<float> zeros(std::size_t size) { std::vector<float> result; result.reserve(size); for (std::size_t k = 0; k < size; ++k) { result.push_back(0); } return result; } } // namespace std::vector<float> QueryManager::getMarginalDistribution(const NodeLocation &location) { std::vector<float> result; auto &[node, it] = location; VisitorConst<HiddenClusters::iterator, Evidences::iterator>{ [&result, &node = node](const HiddenClusters::iterator &) { result = gather_incoming_messages(*node).getProbabilities(); }, [&result, &node = node](const Evidences::iterator &location) { result = zeros(node->variable->size()); result[location->second] = 1.f; }} .visit(it); return result; } void QueryManager::throwInexistentVar(const std::string &var) { throw Error::make(var, " is a not part of the graph"); } std::vector<float> QueryManager::getMarginalDistribution(const std::string &var, std::size_t threads) { return getMarginalDistribution(findVariable(var), threads); } namespace { std::size_t find_max(const std::vector<float> &values) { std::size_t res = 0; float max = values.front(); for (std::size_t k = 1; k < values.size(); ++k) { if (values[k] > max) { max = values[k]; res = k; } } return res; } } // namespace std::size_t QueryManager::getMAP(const categoric::VariablePtr &var, std::size_t threads) { auto values = marginalQuery_<PropagationKind::MAP>(var, threads); return find_max(values); } std::size_t QueryManager::getMAP(const std::string &var, std::size_t threads) { return getMAP(findVariable(var), threads); } std::vector<size_t> QueryManager::getHiddenSetMAP(std::size_t threads) { checkPropagation_<PropagationKind::MAP>(threads); auto vars = getHiddenVariables(); std::vector<size_t> result; result.reserve(vars.size()); auto &nodes = stateMutable().nodes; for (const auto &var : vars) { auto values = gather_incoming_messages(*nodes[var]).getProbabilities(); result.push_back(find_max(values)); } return result; } factor::Factor QueryManager::getJointMarginalDistribution(const categoric::Group &subgroup, std::size_t threads) { checkPropagation_<PropagationKind::SUM>(threads); std::vector<NodeLocation> locations; std::unordered_set<Node *> subgroup_nodes; for (const auto &var_name : subgroup.getVariables()) { auto location = locate(var_name); if (!location.has_value()) { throwInexistentVar(var_name->name()); } subgroup_nodes.emplace(location->node); locations.emplace_back(location.value()); } std::unordered_set<const factor::Immutable *> contributions; std::vector<factor::Indicator> indicators; for (auto &[node, location] : locations) { VisitorConst<HiddenClusters::iterator, Evidences::iterator>{ [&node = node, &subgroup_nodes, &contributions](const HiddenClusters::iterator &) { contributions.emplace(node->merged_unaries.get()); for (const auto &[connected_node, connection] : node->active_connections) { if (subgroup_nodes.find(connected_node) == subgroup_nodes.end()) { contributions.emplace(connection.message.get()); } else { contributions.emplace(connection.factor.get()); } } }, [&node = node, &contributions, &indicators](const Evidences::iterator &location) { auto &added = indicators.emplace_back(node->variable, location->second); contributions.emplace(&added); }} .visit(location); } return factor::Factor{std::vector<const factor::Immutable *>{ contributions.begin(), contributions.end()}} .cloneWithPermutedGroup(subgroup); } factor::Factor QueryManager::getJointMarginalDistribution( const std::vector<std::string> &subgroup, std::size_t threads) { categoric::VariablesSoup vars; for (const auto &var : subgroup) { vars.push_back(findVariable(var)); } return getJointMarginalDistribution(categoric::Group{vars}, threads); } } // namespace EFG::strct
5,089
C++
.cpp
139
31.151079
80
0.670922
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,909
EvidenceManager.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/EvidenceManager.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/misc/Visitor.h> #include <EasyFactorGraph/structure/EvidenceManager.h> #include <EasyFactorGraph/structure/bases/StateAware.h> #include <algorithm> namespace EFG::strct { void EvidenceSetter::setEvidence(const categoric::VariablePtr &variable, std::size_t value) { if (variable->size() <= value) { throw Error::make(std::to_string(value), " is an invalid evidence for variable ", variable->name()); } auto info = locate(variable); if (!info.has_value()) { throw Error::make(variable->name(), " is a non existing variable"); } auto *node = info->node; Evidences::iterator evidence_location; VisitorConst<HiddenClusters::iterator, Evidences::iterator>{ [&](const HiddenClusters::iterator &it) { while (!node->active_connections.empty()) { Node::disable(*node, *node->active_connections.begin()->first); } // update clusters auto &state = stateMutable(); if (1 == it->nodes.size()) { state.clusters.erase(it); } else { auto nodes = it->nodes; state.clusters.erase(it); nodes.erase(node); for (auto &&cluster : compute_clusters(nodes)) { state.clusters.emplace_back(std::move(cluster)); } } evidence_location = state.evidences.emplace(node->variable, value).first; }, [&](const Evidences::iterator &it) { evidence_location = it; evidence_location->second = value; }} .visit(info->location); for (auto &[connected_node, connection] : node->disabled_connections) { auto connection_it = connected_node->disabled_connections.find(node); connection_it->second.message = std::make_unique<factor::Evidence>( *connection_it->second.factor, node->variable, evidence_location->second); connected_node->merged_unaries.reset(); } resetBelief(); } void EvidenceSetter::setEvidence(const std::string &variable, std::size_t value) { setEvidence(findVariable(variable), value); } void EvidenceRemover::removeEvidence_(const categoric::VariablePtr &variable) { auto &state = stateMutable(); auto evidence_it = state.evidences.find(variable); if (evidence_it == state.evidences.end()) { throw Error::make(variable->name(), " is not an evidence"); } resetBelief(); state.evidences.erase(evidence_it); auto &node = *state.nodes[variable].get(); while (!node.disabled_connections.empty()) { auto it = node.disabled_connections.begin(); it->first->merged_unaries.reset(); Node::activate(node, *it->first, it->second.factor); } node.merged_unaries.reset(); } void EvidenceRemover::removeEvidence(const categoric::VariablePtr &variable) { removeEvidence_(variable); resetState(); } void EvidenceRemover::removeEvidence(const std::string &variable) { removeEvidence(findVariable(variable)); } void EvidenceRemover::removeEvidences( const categoric::VariablesSet &variables) { if (variables.empty()) { return; } for (const auto &variable : variables) { removeEvidence_(variable); } resetState(); } void EvidenceRemover::removeEvidences( const std::unordered_set<std::string> &variables) { categoric::VariablesSet vars; for (const auto &name : variables) { vars.emplace(findVariable(name)); } removeEvidences(vars); } void EvidenceRemover::removeAllEvidences() { const auto &state = this->state(); while (!state.evidences.empty()) { auto var = state.evidences.begin()->first; removeEvidence_(var); } resetState(); } void EvidenceRemover::resetState() { auto &state = stateMutable(); std::unordered_set<Node *> nodes; for (auto &[var, node] : state.nodes) { if (state.evidences.find(var) == state.evidences.end()) { nodes.emplace(node.get()); } } state.clusters = compute_clusters(nodes); } } // namespace EFG::strct
4,163
C++
.cpp
123
28.691057
79
0.66708
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,910
FactorsConstManager.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/FactorsConstManager.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/structure/FactorsConstManager.h> namespace EFG::strct { void FactorsConstInserter::addConstFactor(const factor::ImmutablePtr &factor) { addDistribution(factor); const_factors.emplace(factor); } void FactorsConstInserter::copyConstFactor(const factor::Immutable &factor) { auto cloned = std::make_shared<factor::Factor>( factor, factor::Factor::CloneTrasformedImagesTag{}); addConstFactor(cloned); } } // namespace EFG::strct
580
C++
.cpp
18
29.944444
79
0.767025
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,911
Types.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/Types.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/Types.h> #include <algorithm> #include <limits> namespace EFG::strct { namespace { std::vector<const factor::Immutable *> gather_unaries(Node &subject) { std::vector<const factor::Immutable *> unary_factors; for (const auto &factor : subject.unary_factors) { unary_factors.push_back(factor.get()); } for (auto &[node, connection] : subject.disabled_connections) { unary_factors.push_back(connection.message.get()); } return unary_factors; } } // namespace void Node::updateMergedUnaries() { std::vector<const factor::Immutable *> unary_factors = gather_unaries(*this); if (unary_factors.empty()) { merged_unaries.reset(std::make_unique<factor::MergedUnaries>(variable)); return; } merged_unaries.reset(std::make_unique<factor::MergedUnaries>(unary_factors)); } namespace { Node::Connection *reset(Node::Connection &subject, const factor::ImmutablePtr &factor) { subject.message.reset(); subject.factor = factor; return &subject; } } // namespace std::pair<Node::Connection *, Node::Connection *> Node::activate(Node &a, Node &b, factor::ImmutablePtr factor) { a.disabled_connections.erase(&b); b.disabled_connections.erase(&a); return std::make_pair(reset(a.active_connections[&b], factor), reset(b.active_connections[&a], factor)); } std::pair<Node::Connection *, Node::Connection *> Node::disable(Node &a, Node &b, factor::ImmutablePtr factor) { if (factor == nullptr) { auto it = a.active_connections.find(&b); if (it == a.active_connections.end()) { throw Error::make("Nodes named: ", a.variable->name(), " and ", b.variable->name(), " are not connected"); } factor = it->second.factor; } a.active_connections.erase(&b); b.active_connections.erase(&a); return std::make_pair(reset(a.disabled_connections[&b], factor), reset(b.disabled_connections[&a], factor)); } bool HiddenCluster::TopologyInfo::canUpdateMessage() const { return std::find_if(dependencies.begin(), dependencies.end(), [](const Node::Connection *connection) { return connection->message == nullptr; }) == dependencies.end(); } std::optional<float> HiddenCluster::TopologyInfo::updateMessage(PropagationKind kind) { if (sender->merged_unaries.empty()) { throw Error{"Found node with not updated static dependencies"}; } std::vector<const factor::Immutable *> unary_factors = { sender->merged_unaries.get()}; for (const auto *dep : dependencies) { if (nullptr == dep->message) { return std::nullopt; } unary_factors.push_back(dep->message.get()); } factor::MergedUnaries merged_unaries(unary_factors); std::unique_ptr<const factor::UnaryFactor> previous_message = std::move(connection->message); switch (kind) { case PropagationKind::SUM: connection->message = make_message<factor::MessageSUM>(merged_unaries, *connection->factor); break; case PropagationKind::MAP: connection->message = make_message<factor::MessageMAP>(merged_unaries, *connection->factor); break; default: throw Error{"Invalid propagation kind"}; } if (nullptr == previous_message) { static float MAX_VARIATION = std::numeric_limits<float>::max(); return MAX_VARIATION; } return previous_message->diff(*connection->message); } void HiddenCluster::updateConnectivity() { auto &topology = connectivity.reset( std::make_unique<std::vector<HiddenCluster::TopologyInfo>>()); for (auto *sender : nodes) { sender->updateMergedUnaries(); if (sender->active_connections.empty()) { continue; } std::unordered_set<Node::Connection *> all_dependencies; for (auto &[receiver, incoming_connection] : sender->active_connections) { all_dependencies.emplace(&incoming_connection); } for (auto &[receiver, incoming_connection] : sender->active_connections) { auto &added = topology.emplace_back(); added.sender = sender; added.connection = &receiver->active_connections.find(sender)->second; auto deps = all_dependencies; deps.erase(&incoming_connection); added.dependencies = std::vector<const Node::Connection *>{deps.begin(), deps.end()}; } } } namespace { std::list<std::unordered_set<Node *>> compute_clusters_(const std::unordered_set<Node *> &nodes) { using Cluster = std::unordered_set<Node *>; std::list<Cluster> res; for (auto *node : nodes) { using Iter = std::list<Cluster>::iterator; std::unordered_map<const Cluster *, Iter> neighbour; for (const auto &[node, _] : node->active_connections) { auto it = std::find_if(res.begin(), res.end(), [&node = node](const Cluster &cl) { return cl.find(node) != cl.end(); }); if (it != res.end()) { neighbour[&(*it)] = it; } } switch (neighbour.size()) { case 0: res.emplace_back().emplace(node); break; case 1: neighbour.begin()->second->emplace(node); break; default: { auto &added = res.emplace_back(); added.emplace(node); for (const auto &[_, it] : neighbour) { added.insert(it->begin(), it->end()); res.erase(it); } } break; } } return res; } } // namespace HiddenClusters compute_clusters(const std::unordered_set<Node *> &nodes) { HiddenClusters res; for (auto &&set : compute_clusters_(nodes)) { res.emplace_back().nodes = std::move(set); } return res; } } // namespace EFG::strct
5,854
C++
.cpp
169
29.414201
79
0.653622
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,912
PoolAware.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/bases/PoolAware.cpp
/** * Author: Andrea Casalino * Created: 28.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/bases/PoolAware.h> namespace EFG::strct { namespace { void process_tasks_in_parallel(const Tasks &subject, const std::size_t threads_numb, const std::size_t thread_id) { for (std::size_t k = thread_id; k < subject.size(); k += threads_numb) { subject[k](thread_id); } } } // namespace Pool::Worker::Worker(std::size_t th_id, Context &context) : loop([thread_id = th_id, &context = context, this]() { while (context.life.load()) { if (const Tasks *ptr = to_process.load(); ptr != nullptr) { process_tasks_in_parallel(*ptr, context.pool_size, thread_id); to_process.store(nullptr); } } }) {} Pool::Pool(const std::size_t size) { if (0 == size) { throw Error{"Invalid Pool size"}; } ctxt.pool_size = size; for (std::size_t k = 1; k < size; ++k) { workers.emplace_back(std::make_unique<Worker>(k, ctxt)); } } Pool::~Pool() { ctxt.life.store(false); for (auto &worker : workers) { // if (worker->loop.joinable()) { worker->loop.join(); // } } workers.clear(); } void Pool::parallelFor(const std::vector<Task> &tasks) { std::scoped_lock lock(parallelForMtx); for (auto &worker : workers) { worker->to_process.store(&tasks); } process_tasks_in_parallel(tasks, ctxt.pool_size, 0); bool keep_wait; do { keep_wait = false; for (const auto &worker : workers) { if (worker->to_process.load() != nullptr) { keep_wait = true; break; } } } while (keep_wait); } PoolAware::PoolAware() { resetPool(); } PoolAware::~PoolAware() = default; void PoolAware::resetPool() { pool.emplace(1); } void PoolAware::setPoolSize(const std::size_t new_size) { if (new_size == pool->size()) { return; } pool.emplace(new_size); } } // namespace EFG::strct
2,060
C++
.cpp
72
23.986111
74
0.611729
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,913
BeliefAware.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/bases/BeliefAware.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/BaselineLoopyPropagator.h> #include <EasyFactorGraph/structure/bases/BeliefAware.h> namespace EFG::strct { BeliefAware::BeliefAware() { loopy_propagator = std::make_unique<BaselineLoopyPropagator>(); } void BeliefAware::setLoopyPropagationStrategy( LoopyBeliefPropagationStrategyPtr strategy) { if (nullptr == strategy) { throw Error{"trying to set a null propagator"}; } loopy_propagator = std::move(strategy); } bool BeliefAware::wouldNeedPropagation(PropagationKind kind) const { return (!lastPropagation.has_value()) || (lastPropagation->propagation_kind_done != kind); } namespace { void reset_messages(const HiddenClusters &clusters) { for (const auto &cluster : clusters) { for (auto *node : cluster.nodes) { for (auto &[connected_node, connection] : node->active_connections) { connection.message.reset(); } } } } std::list<HiddenCluster::TopologyInfo *> pack_messages(std::vector<HiddenCluster::TopologyInfo> &conn) { std::list<HiddenCluster::TopologyInfo *> res; for (auto &el : conn) { res.push_back(&el); } return res; } bool message_passing(HiddenCluster &cluster, const PropagationKind &kind, Pool &pool) { std::list<HiddenCluster::TopologyInfo *> leftToCompute = pack_messages(*cluster.connectivity.get()); while (!leftToCompute.empty()) { Tasks to_process; auto it = leftToCompute.begin(); while (it != leftToCompute.end()) { if ((*it)->canUpdateMessage()) { to_process.emplace_back([task = *it, kind](const std::size_t) { task->updateMessage(kind); }); it = leftToCompute.erase(it); } else { ++it; } } if (to_process.empty()) { return false; } pool.parallelFor(to_process); } return true; } } // namespace void BeliefAware::propagateBelief(PropagationKind kind) { if (!wouldNeedPropagation(kind)) { return; } auto &clusters = stateMutable().clusters; auto &pool = getPool(); reset_messages(clusters); PropagationResult result; result.was_completed = true; result.propagation_kind_done = kind; for (auto &cluster : clusters) { if (cluster.connectivity.empty()) { cluster.updateConnectivity(); } else { for (auto *node : cluster.nodes) { if (node->merged_unaries.empty()) { node->updateMergedUnaries(); } } } if (message_passing(cluster, kind, pool)) { auto &cluster_info = result.structures.emplace_back(); cluster_info.tree_or_loopy_graph = true; cluster_info.size = cluster.nodes.size(); continue; } auto &cluster_info = result.structures.emplace_back(); cluster_info.tree_or_loopy_graph = false; cluster_info.size = cluster.nodes.size(); if (!loopy_propagator->propagateBelief(cluster, kind, context, pool)) { result.was_completed = false; } } lastPropagation = result; } } // namespace EFG::strct
3,151
C++
.cpp
103
26.126214
75
0.677536
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,914
FactorsAware.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/bases/FactorsAware.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/misc/Visitor.h> #include <EasyFactorGraph/structure/bases/FactorsAware.h> #include <algorithm> namespace EFG::strct { void FactorsAware::addDistribution( const EFG::factor::ImmutablePtr &distribution) { if (nullptr == distribution) { throw Error{"null distribution can't be add"}; } if (factorsAll.find(distribution) != factorsAll.end()) { throw Error{"Already inserted factor"}; } resetBelief(); switch (distribution->function().vars().getVariables().size()) { case 1: addUnaryDistribution(distribution); break; case 2: addBinaryDistribution(distribution); break; default: throw Error{"Factor with invalid number of variables"}; break; } factorsAll.emplace(distribution); } namespace { void check_is_same_variable(const categoric::VariablePtr &a, const categoric::VariablePtr &b) { if (a.get() != b.get()) { throw Error::make("Trying to insert variable named: ", a->name(), " multiple times with different VariablePtr"); } } } // namespace StateAware::NodeLocation FactorsAware::findOrMakeNode(const categoric::VariablePtr &var) { if (auto info = locate(var); info.has_value()) { check_is_same_variable(var, info.value().node->variable); return *info; } // create this node auto &state = stateMutable(); state.variables.push_back(var); auto *added = state.nodes.emplace(var, std::make_unique<Node>()).first->second.get(); added->variable = var; HiddenClusters::iterator res_it; state.clusters.emplace_back().nodes.emplace(added); res_it = state.clusters.end(); --res_it; return NodeLocation{added, res_it}; } void FactorsAware::addUnaryDistribution( const EFG::factor::ImmutablePtr &unary_factor) { const auto &var = unary_factor->function().vars().getVariables().front(); auto &&[node, _] = findOrMakeNode(var); node->unary_factors.push_back(unary_factor); node->merged_unaries.reset(); } namespace { void hybrid_insertion(Node *node_hidden, Node *node_evidence, std::size_t evidence, const EFG::factor::ImmutablePtr &binary_factor) { Node::disable(*node_hidden, *node_evidence, binary_factor).first->message = std::make_unique<factor::Evidence>(*binary_factor, node_evidence->variable, evidence); node_hidden->merged_unaries.reset(); }; } // namespace void FactorsAware::addBinaryDistribution( const EFG::factor::ImmutablePtr &binary_factor) { const auto &vars = binary_factor->function().vars().getVariables(); const auto nodeA_location = findOrMakeNode(vars.front()); auto *nodeA = nodeA_location.node; const auto nodeB_location = findOrMakeNode(vars.back()); auto *nodeB = nodeB_location.node; if ((nodeA->active_connections.find(nodeB) != nodeA->active_connections.end()) || (nodeA->disabled_connections.find(nodeB) != nodeA->disabled_connections.end())) { throw Error::make(nodeA->variable->name(), " and ", nodeB->variable->name(), " are already connected"); } VisitorConst<HiddenClusters::iterator, Evidences::iterator>{ [&](const HiddenClusters::iterator &hiddenA_location) { VisitorConst<HiddenClusters::iterator, Evidences::iterator>{ [&](const HiddenClusters::iterator &hiddenB_location) { // both are hidden Node::activate(*nodeA, *nodeB, binary_factor); hiddenA_location->connectivity.reset(); if (hiddenA_location != hiddenB_location) { hiddenA_location->nodes.insert(hiddenB_location->nodes.begin(), hiddenB_location->nodes.end()); this->stateMutable().clusters.erase(hiddenB_location); } }, [&](const Evidences::iterator &evidenceB_location) { hybrid_insertion(nodeA, nodeB, evidenceB_location->second, binary_factor); }} .visit(nodeB_location.location); }, [&](const Evidences::iterator &evidenceA_location) { VisitorConst<HiddenClusters::iterator, Evidences::iterator>{ [&](const HiddenClusters::iterator &) { hybrid_insertion(nodeB, nodeA, evidenceA_location->second, binary_factor); }, [&](const Evidences::iterator &) { // both are evidences Node::disable(*nodeA, *nodeB, binary_factor); }} .visit(nodeB_location.location); }} .visit(nodeA_location.location); } } // namespace EFG::strct
4,856
C++
.cpp
125
31.632
80
0.642085
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,915
StateAware.cpp
andreacasalino_Easy-Factor-Graph/src/src/structure/bases/StateAware.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/bases/StateAware.h> #include <algorithm> namespace EFG::strct { categoric::VariablePtr StateAware::findVariable(const std::string &name) const { auto variables_it = std::find_if(state_.variables.begin(), state_.variables.end(), [&name](const categoric::VariablePtr &var) { return var->name() == name; }); if (variables_it == state_.variables.end()) { throw Error::make(name, " is an inexistent variable"); } return *variables_it; } categoric::VariablesSet StateAware::getHiddenVariables() const { categoric::VariablesSet result; for (const auto &cluster : state_.clusters) { for (auto *node : cluster.nodes) { result.emplace(node->variable); } } return result; } categoric::VariablesSet StateAware::getObservedVariables() const { categoric::VariablesSet result; for (const auto &[var, _] : state_.evidences) { result.emplace(var); } return result; } std::optional<StateAware::NodeLocation> StateAware::locate(const categoric::VariablePtr &variable) const { Node *node = nullptr; if (auto it = state_.nodes.find(variable); it == state_.nodes.end()) { return std::nullopt; } else { node = it->second.get(); } if (auto it = state_.evidences.find(variable); it != state_.evidences.end()) { return NodeLocation{node, it}; } auto it = std::find_if(state_.clusters.begin(), state_.clusters.end(), [&node](const HiddenCluster &element) { return element.nodes.find(node) != element.nodes.end(); }); return NodeLocation{node, it}; } } // namespace EFG::strct
1,841
C++
.cpp
56
28.035714
80
0.657111
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,916
ReadMe.cpp
andreacasalino_Easy-Factor-Graph/samples/ReadMe.cpp
#include <EasyFactorGraph/factor/Factor.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/io/TrainSetImport.h> #include <EasyFactorGraph/io/json/Importer.h> #include <EasyFactorGraph/io/xml/Importer.h> #include <EasyFactorGraph/model/RandomField.h> #include <EasyFactorGraph/trainable/ModelTrainer.h> #include <TrainingTools/iterative/solvers/QuasiNewton.h> using namespace EFG; using namespace EFG::categoric; using namespace EFG::factor; using namespace EFG::model; using namespace EFG::io; using namespace EFG::train; using namespace EFG::strct; int main() { { // FACTORS CONSTRUCTION // define a couple of variables, with the same size VariablePtr A = make_variable(3, "A"); // size is 3 VariablePtr B = make_variable(3, "B"); // size is 3 // build a simply correlating factor connecting the 2 variables Factor factor_AB(VariablesSoup{B, A}, // the order in the specified // group matters: B is assumed // as the first variable, A // will be the second Factor::SimplyCorrelatedTag{}); // build an exponential factor using as base `factor_AB`: values of the // images are assumed as exp(weight * images_factor_AB) FactorExponential factor_AB_exponential( factor_AB, 1.5f // this will be the value assumed for the weight ); // define another variable VariablePtr C = make_variable(2, "C"); // size is 2 // define a factor connecting C to B // we start building an empty factor, having all images equal to 0 Factor factor_BC(VariablesSoup{B, C}); // set some individual images of factor_BC // set for <0,1> -> 2 factor_BC.set(std::vector<std::size_t>{0, 1}, 2.f); // set for <2,0> -> 1.3f factor_BC.set(std::vector<std::size_t>{2, 0}, 1.3f); } { // MODELS CONSTRUCTION // start building an empty random field RandomField model; // define some variables, which will be later connected auto A = make_variable(4, "varA"); auto B = make_variable(4, "varB"); auto C = make_variable(4, "varC"); // without loss of generality, add to the model some simply correlating // factors model.addConstFactor(std::make_shared<Factor>( VariablesSoup{A, B}, Factor::SimplyCorrelatedTag{})); // the generated smart // pointer is shallow // copied model.copyConstFactor( Factor{VariablesSoup{A, C}, Factor::SimplyCorrelatedTag{}}); // the passed factor is // deep-copied into the // model // build some additional tunable exponential factors that will be too added auto factor_exp_BC = std::make_shared<FactorExponential>( Factor{VariablesSoup{B, C}, Factor::SimplyCorrelatedTag{}}, 1.f); model.addTunableFactor(factor_exp_BC); auto D = make_variable(4, "varD"); auto factor_exp_CD = std::make_shared<FactorExponential>( Factor{VariablesSoup{C, D}, Factor::SimplyCorrelatedTag{}}, 1.5f); model.addTunableFactor(factor_exp_CD); // insert another tunable factor, this time specifying that it needs to // share the weight with already inserted exponential factor that connects B // and C model.addTunableFactor( std::make_shared<FactorExponential>( Factor{VariablesSoup{C, D}, Factor::SimplyCorrelatedTag{}}, 2.f // actually this value is irrelevant, as the weight of // factor_exp_BC will be assumed from now on ), VariablesSet{B, C} // this additional input is to specify that this exponential factor // needs to share the weight with the one connecting B and C ); // absorb the structure defined in an xml file xml::Importer::importFromFile(model, std::string{"file_name.xml"}); // absorb the structure encoded in a json string nlohmann::json json_defining_a_structure = ...; json::Importer::importFromJson(model, json_defining_a_structure); } { // QUERY THE MODEL RandomField model; // set some evidences model.setEvidence("variable_1", 0); // setting variable_1 = 0 model.setEvidence("variable_2", 2); // setting variable_2 = 2 // get the marginal conditioned distribution of an hidden variable std::vector<float> conditioned_marginals = model.getMarginalDistribution("var_A"); // get maxiomum a posteriori estimation of the entire hidden set std::vector<std::size_t> MAP_hidden_set = model.getHiddenSetMAP(); // set some new evidences model.removeAllEvidences(); model.setEvidence("evid_1", 1); // compute new conditioned marginals: the should be different as the // evidences were changed conditioned_marginals = model.getMarginalDistribution("var_A"); } { // TUNE THE MODEL RandomField tunable_model; // assume we have a training set for the model stored in a file TrainSet training_set = import_train_set("file_name.txt"); // we can train the model using one of the ready to use gradient based // approaches ::train::QuasiNewton ready_to_use_trainer; ready_to_use_trainer.setMaxIterations(50); // some definitions to control the training process TrainInfo info = TrainInfo{ 4, // threads to use 1.f // stochasticity. When set different from 1, the stochastich // gradient descend approaches are actually used }; train_model(tunable_model, ready_to_use_trainer, training_set, info); } { // GIBBS SAMPLING RandomField model; // some definitions to control the samples generation process GibbsSampler::SamplesGenerationContext info = GibbsSampler::SamplesGenerationContext{ 1000, // samples number 0, // seed used by random engines 500 // number of iterations to discard at the beginning (burn out) }; // get samples from the model using Gibbs sampler std::vector<std::vector<std::size_t>> samples = model.makeSamples(info, 4 // threads to use ); } return EXIT_SUCCESS; }
6,380
C++
.cpp
144
36.465278
80
0.654844
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,917
Sample01-1-Variables.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample01-1-Variables.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/categoric/GroupRange.h> #include <EasyFactorGraph/categoric/Variable.h> using namespace EFG::categoric; // just a bunch of utilities needed by the sample #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; int main() { SAMPLE_SECTION("Managing group of variables", "4.1.1.1", [] { // define a group of variables, all with size = 2 Group groupABCD(make_variable(2, "A"), make_variable(2, "B")); cout << "groupABCD with only A and B for the moment: " << groupABCD << endl; groupABCD.add(make_variable(2, "C")); groupABCD.add(make_variable(2, "D")); cout << "groupABCD after adding also C and D: " << groupABCD << endl; }); SAMPLE_SECTION("Managing group of variables", "4.1.1.1", [] { // define a group of variables, all with size = 2 Group groupABCD(make_variable(2, "A"), make_variable(2, "B")); cout << "groupABCD with only A and B for the moment: " << groupABCD << endl; groupABCD.add(make_variable(2, "C")); groupABCD.add(make_variable(2, "D")); cout << "groupABCD after adding also C and D: " << groupABCD << endl; // try to add an already existing variable try { groupABCD.add(make_variable(2, "C")); } catch (...) { cout << "insertion of C in ABCD group correctly refused" << endl; } }); SAMPLE_SECTION("Joint domain of variables", "4.1.1.2", [] { // build some variables auto A = make_variable(2, "A"); auto B = make_variable(4, "B"); auto C = make_variable(3, "C"); { Group AB_group(VariablesSoup{A, B}); cout << AB_group.getVariables() << endl; // display all combinations in the joint domain GroupRange range(AB_group); for_each_combination(range, [](const std::vector<std::size_t> &comb) { cout << comb << std::endl; }); cout << endl; } { Group AC_group(VariablesSoup{A, C}); cout << AC_group.getVariables() << endl; // display all combinations in the joint domain GroupRange range(AC_group); for_each_combination(range, [](const std::vector<std::size_t> &comb) { cout << comb << std::endl; }); cout << endl; } { Group ABC_group(VariablesSoup{A, C, B}); cout << ABC_group.getVariables() << endl; // display all combinations in the joint domain GroupRange range(ABC_group); for_each_combination(range, [](const std::vector<std::size_t> &comb) { cout << comb << std::endl; }); cout << endl; } }); return EXIT_SUCCESS; }
2,778
C++
.cpp
77
31.207792
80
0.630208
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,918
Sample04-HMM-chain.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample04-HMM-chain.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/io/json/Exporter.h> #include <EasyFactorGraph/io/xml/Exporter.h> #include <EasyFactorGraph/model/Graph.h> #include <EasyFactorGraph/structure/SpecialFactors.h> using namespace EFG::model; using namespace EFG::io; using namespace EFG::factor; using namespace EFG::categoric; using namespace EFG::strct; // just a bunch of utilities needed by the sample #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; Graph make_graph_chain(const std::size_t &chain_size, const std::size_t &var_size, const float &weight_XY, const float &weight_YY); int main() { SAMPLE_SECTION( "Chain like structure. After running the sample, check the content of " "the generated Graph_XY.xml, Graph_YY.xml, Graph_XY.json and " "Graph_YY.json ", "4.4", [] { size_t chain_size = 10; // you can change it size_t var_dom_size = 2; // you can change it vector<size_t> Y_MAP; Y_MAP.reserve(chain_size); { // create a chain with a strong weight on the potentials XY. auto G_XY = make_graph_chain(chain_size, var_dom_size, 2.f, 0.5f); // compute MAP on hidden variables and display it for (size_t k = 0; k < chain_size; ++k) { Y_MAP.push_back(G_XY.getMAP("Y_" + to_string(k))); } cout << "Strong correlation with evidences, MAP on Y0,1,.. " << Y_MAP << endl; // export into an xml (just as an exporting example) xml::Exporter::exportToFile( G_XY, xml::ExportInfo{"Graph_XY.xml", "Graph_XY"}); // export into a json (just as an exporting example) json::Exporter::exportToFile(G_XY, "Graph_XY.json"); } { // create a chain with a strong weight on the potentials YY. auto G_YY = make_graph_chain(chain_size, var_dom_size, 0.5f, 2.f); // compute MAP on hidden variables and display it Y_MAP.clear(); for (size_t k = 0; k < chain_size; ++k) { Y_MAP.push_back(G_YY.getMAP("Y_" + to_string(k))); } cout << "Strong correlation among hidden variables, MAP on Y0,1,.. " " " << Y_MAP << endl; // export into an xml (just as an exporting example) xml::Exporter::exportToFile( G_YY, xml::ExportInfo{"Graph_YY.xml", "Graph_YY"}); // export into a json (just as an exporting example) json::Exporter::exportToFile(G_YY, "Graph_YY.json"); } }); return EXIT_SUCCESS; } Graph make_graph_chain(const std::size_t &chain_size, const std::size_t &var_size, const float &weight_XY, const float &weight_YY) { if (chain_size < 2) throw EFG::Error("invalid chain size"); if (var_size < 2) throw EFG::Error("invalid variable size"); Graph G; auto X = make_variable(var_size, "X_placeholder"); auto Y = make_variable(var_size, "Y_placeholder"); auto Ybis = make_variable(var_size, "Y_placeholder_bis"); FactorExponential P_YY( Factor{VariablesSoup{Y, Ybis}, Factor::SimplyCorrelatedTag{}}, weight_YY); FactorExponential P_XY( Factor{VariablesSoup{Y, X}, Factor::SimplyCorrelatedTag{}}, weight_XY); // build the chain and set the value of the evidences equal to: // X_0 = 0, X_1=var_size-1, X_2= 0, X_3 = var_size-1, etc.. VariablesSoup Y_vars, X_vars; for (size_t k = 0; k < chain_size; k++) { Y_vars.push_back(make_variable(var_size, "Y_" + to_string(k))); X_vars.push_back(make_variable(var_size, "X_" + to_string(k))); auto temp_XY = std::make_shared<FactorExponential>(P_XY); temp_XY->replaceVariables(VariablesSoup{X_vars[k], Y_vars[k]}); G.addConstFactor(temp_XY); } for (size_t k = 0; k < chain_size; k++) { ImmutablePtr factor; if (0 == k) { factor = std::make_shared<Indicator>(Y_vars[0], 0); } else { auto temp_YY = std::make_shared<FactorExponential>(P_YY); temp_YY->replaceVariables(VariablesSoup{Y_vars[k], Y_vars[k - 1]}); factor = temp_YY; } G.addConstFactor(factor); } size_t o = 0; for (size_t k = 0; k < chain_size; k++) { G.setEvidence(X_vars[k], o); if (o == 0) o = 1; else o = 0; } return G; }
4,633
C++
.cpp
117
32.880342
80
0.612494
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,919
Sample01-2-Factors.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample01-2-Factors.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/categoric/GroupRange.h> #include <EasyFactorGraph/factor/Factor.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/factor/ImageFinder.h> using namespace EFG::categoric; using namespace EFG::factor; // just a bunch of utilities needed by the sample #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; int main() { SAMPLE_SECTION("Factors construction", "4.1.2.1", [] { // create a couple of variables with Dom size equal to 4 auto A = make_variable(4, "A"); auto B = make_variable(4, "B"); // create a Simple shape involving A and B Factor Phi_AB(VariablesSoup{A, B}); // fill the domain in order to have for Phi_AB(a,b) = a + 2*b (just to // put some numbers) { GroupRange range_AB(Phi_AB.function().vars()); for_each_combination(range_AB, [&Phi_AB](const auto &comb) { Phi_AB.set(comb, static_cast<float>(comb[0] + 2 * comb[1])); }); } // print the distribution cout << Phi_AB.function() << endl << endl; // define another couple of variables with the same Dom size of A and B auto X = make_variable(4, "X"); auto Y = make_variable(4, "Y"); // build a factor involving X and Y, cloning the one that involves A and // B Factor Phi_XY(Phi_AB); // initially clone as is Phi_XY.replaceVariables( VariablesSoup{X, Y}); // then replace variables group cout << Phi_XY.function() << endl << endl; // permute X with Y Factor Phi_XY_permuted = Phi_XY.cloneWithPermutedGroup(VariablesSoup{Y, X}); cout << Phi_XY_permuted.function() << endl << endl; }); SAMPLE_SECTION("Simple Factor query", "4.1.2.2", [] { // build the variables auto V1 = make_variable(3, "V1"); auto V2 = make_variable(3, "V2"); auto V3 = make_variable(3, "V3"); // build a factor correlating V1, V2 and V3 Factor Phi_C = Factor(VariablesSoup{V1, V2, V3}, Factor::SimplyCorrelatedTag{}); cout << "Correlating factor" << endl; cout << Phi_C.function() << endl << endl; float weight = 1.5f; // you can tune this value to see how the probabilities change // build the exponential correlating factor and evaluates the probabilities FactorExponential Psi_C(Phi_C, weight); cout << "probabilities taken from the correlating exponential factor " << endl; cout << Psi_C.getProbabilities() << endl << endl; // build a factor correlating V1, V2 and V3 Factor Phi_A = Factor(VariablesSoup{V1, V2, V3}, Factor::SimplyAntiCorrelatedTag{}); cout << "Anti correlating factor" << endl; cout << Phi_A.function() << endl << endl; // build the exponential anti correlating factor and evaluates the // probabilities FactorExponential Psi_A(Phi_A, weight); cout << "probabilities taken from the correlating exponential factor " << endl; cout << Psi_A.getProbabilities() << endl << endl; }); SAMPLE_SECTION("Find specific combination in Factors", "", [] { Factor factor(VariablesSoup{make_variable(2, "A"), make_variable(3, "B"), make_variable(2, "C"), make_variable(3, "D")}); factor.set(std::vector<std::size_t>{0, 0, 0, 0}, 1.f); factor.set(std::vector<std::size_t>{0, 0, 1, 0}, 2.f); factor.set(std::vector<std::size_t>{1, 0, 1, 1}, 3.f); cout << "current content of the distribution" << endl; cout << factor.function() << endl << endl; cout << "value found for 0 0 1 0 -> " << factor.function().findTransformed( std::vector<std::size_t>{0, 0, 1, 0}) << endl; auto bigger_group = factor.function().vars().getVariables(); bigger_group.push_back(make_variable(2, "E")); auto combination_finder = factor.makeFinder(bigger_group); cout << "value found for 1,0,1,1,0 from group " << bigger_group << " -> " << combination_finder.findImage( std::vector<std::size_t>{1, 0, 1, 1, 0}) << endl; }); SAMPLE_SECTION("Factors merging", "", [] { auto A = make_variable(2, "A"); auto B = make_variable(2, "B"); auto C = make_variable(2, "C"); Factor factor_AC(VariablesSoup{A, C}, Factor::SimplyCorrelatedTag{}); Factor factor_BC(VariablesSoup{B, C}, Factor::SimplyCorrelatedTag{}); std::cout << "distributions to merge" << std::endl; cout << factor_AC.function() << endl << endl; cout << factor_BC.function() << endl << endl; std::cout << "merged distribution" << std::endl; cout << Factor::merge(factor_AC, factor_BC).function() << endl << endl; // change factors to merge and then merge again auto setAllImages = [](Factor &subject, float val) { GroupRange range{subject.function().vars()}; for_each_combination(range, [&](const auto &comb) { subject.set(comb, val); }); }; setAllImages(factor_AC, 0.5f); setAllImages(factor_BC, 0.5f); std::cout << "distributions to merge after the change" << std::endl; cout << factor_AC.function() << endl << endl; cout << factor_BC.function() << endl << endl; std::cout << "merged distribution" << std::endl; cout << Factor::merge(factor_AC, factor_BC).function() << endl << endl; }); return EXIT_SUCCESS; }
5,487
C++
.cpp
124
38.709677
80
0.636193
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,920
Sample05-Matricial.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample05-Matricial.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/io/json/Exporter.h> #include <EasyFactorGraph/io/xml/Exporter.h> #include <EasyFactorGraph/model/Graph.h> using namespace EFG::model; using namespace EFG::io; using namespace EFG::factor; using namespace EFG::categoric; using namespace EFG::strct; // just a bunch of utilities needed by the sample #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; Graph makeMatrix(const std::size_t &matrix_size, const std::size_t &var_size, const float &weight_correlation); int main() { SAMPLE_SECTION( "Matrix like structure. After running the sample, check the content of " "the generated Matrix.xml, Matrix.xml", "4.5", [] { size_t matrix_size = 10; // A matrix of Size x Size variables will be // created, you can change it size_t var_dom_size = 3; // you can change it float weight_potential = 1.3f; auto Matrix = makeMatrix(matrix_size, var_dom_size, weight_potential); // set V0_0 = 0 as an edivence and compute marginals of the variables // along the diagonal of the matrix Matrix.setEvidence("V0_0", 0); std::size_t threads = 1; if (matrix_size > 5) { threads = 3; // use more threads to propagate the belief for big matrices } for (size_t k = 1; k < matrix_size; k++) { const std::string var_name = "V" + to_string(k) + "_" + to_string(k); cout << "Marginals of " << var_name << " "; cout << Matrix.getMarginalDistribution(var_name, threads) << endl; } // save the file into an xml (just as an example) xml::Exporter::exportToFile(Matrix, xml::ExportInfo{"Matrix.xml", "Matrix"}); // save the file into an xml (just as an example) json::Exporter::exportToFile(Matrix, "Matrix.json"); }); return EXIT_SUCCESS; } Graph makeMatrix(const std::size_t &matrix_size, const std::size_t &var_size, const float &weight_correlation) { if (matrix_size < 2) throw EFG::Error("invalid matrix size"); if (var_size < 2) throw EFG::Error("invalid variable size"); // build the matrix of variables std::vector<std::vector<VariablePtr>> variables; for (std::size_t row = 0; row < matrix_size; ++row) { auto &vars_row = variables.emplace_back(); for (std::size_t col = 0; col < matrix_size; ++col) { vars_row.push_back( make_variable(var_size, "V" + to_string(row) + "_" + to_string(col))); } } // build the model Graph model; // Create a correlating potential to replicate auto A = make_variable(var_size, "placeholder"); auto B = make_variable(var_size, "placeholder_bis"); FactorExponential factor( Factor{VariablesSoup{A, B}, Factor::SimplyAntiCorrelatedTag{}}, weight_correlation); for (std::size_t row = 0; row < matrix_size; ++row) { for (std::size_t col = 1; col < matrix_size; ++col) { auto temp = std::make_shared<FactorExponential>(factor); temp->replaceVariables( VariablesSoup{variables[row][col - 1], variables[row][col]}); model.addConstFactor(temp); } if (0 < row) { // connect this row to the previous one for (std::size_t col = 0; col < matrix_size; ++col) { auto temp = std::make_shared<FactorExponential>(factor); temp->replaceVariables( VariablesSoup{variables[row][col], variables[row - 1][col]}); model.addConstFactor(temp); } } } return model; }
3,865
C++
.cpp
97
33.57732
80
0.63663
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,921
Sample02-BeliefPropagation-A.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample02-BeliefPropagation-A.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/factor/Factor.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/model/Graph.h> using namespace EFG::model; using namespace EFG::factor; using namespace EFG::categoric; // just a bunch of utilities needed by the sample #include <Frequencies.h> #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; int main() { SAMPLE_SECTION("Graph with a single potential", "4.2.1", [] { // create a simple graph with two nodes Graph graph; float teta = 1.5f; FactorExponential factor( Factor{VariablesSoup{make_variable(2, "A"), make_variable(2, "B")}, Factor::SimplyCorrelatedTag{}}, teta); graph.copyConstFactor(factor); // make a new belief propagation setting B=0 as observation graph.setEvidence("B", 0); // compute the marginal probabilities cout << "P(A|B=0)" << endl; cout << make_distribution({expf(teta), 1.f}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("A") << " computed values" << endl << endl; // make a new belief propagation setting B1=1 as observation graph.setEvidence("B", 1); cout << "P(A|B=1)" << endl; cout << make_distribution({1.f, expf(teta)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("A") << " computed values" << endl << endl; }); SAMPLE_SECTION("Graph with two potentials and 3 variables", "4.2.2", [] { Graph graph; auto A = make_variable(2, "A"); auto B = make_variable(2, "B"); auto C = make_variable(2, "C"); float alfa = 0.5f, beta = 1.f; graph.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{B, C}, Factor::SimplyCorrelatedTag{}}, alfa)); graph.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{A, B}, Factor::SimplyCorrelatedTag{}}, beta)); // make a new belief propagation setting C=1 as observation graph.setEvidence(C, 1); // compute the marginals of A,B and then compare results with the // theoretical ones, see documentation cout << "P(B|C=1)\n"; cout << make_distribution({1.f, expf(alfa)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution(B) << " computed values" << endl << endl; cout << "P(A|C=1)\n"; cout << make_distribution( {expf(alfa) + expf(beta), 1.f + expf(alfa) * expf(beta)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution(A) << " computed values" << endl << endl; // make a new belief propagation setting B=1 as unique observation graph.removeAllEvidences(); graph.setEvidence(B, 1); cout << "P(A|B=1)\n"; cout << make_distribution({1.f, expf(beta)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution(A) << " computed values" << endl << endl; cout << "P(C|B=1)\n"; cout << make_distribution({1.f, expf(alfa)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution(C) << " computed values" << endl << endl; }); SAMPLE_SECTION("Belief degradation on a chain of variables", "4.2.3", [] { const std::size_t domain_size = 5; const float weight = 2.5f; for (int k = 2; k <= 10; k++) { const auto chain_size = k; // build the set of variables in the chain vector<VariablePtr> Y; Y.reserve(chain_size); for (size_t k = 0; k < chain_size; ++k) { Y.push_back(make_variable(domain_size, "Y_" + to_string(k))); } Graph graph; // build the correlating potentials and add it to the chain for (size_t k = 1; k < chain_size; ++k) { graph.addConstFactor(std::make_shared<FactorExponential>( Factor(VariablesSoup{Y[k - 1], Y[k]}, Factor::SimplyCorrelatedTag{}), weight)); } // set Y_0 as an observations and compute the marginals of the last // variable in the chain graph.setEvidence(Y.front(), 0); cout << "chain size equal to " << chain_size << ", marginals of Y_n: "; cout << graph.getMarginalDistribution(Y.back()->name()) << endl; cout << endl; } }); return EXIT_SUCCESS; }
4,508
C++
.cpp
113
34.026549
77
0.625972
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,922
Sample07-Learning-B.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample07-Learning-B/Sample07-Learning-B.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/io/xml/Importer.h> #include <EasyFactorGraph/model/ConditionalRandomField.h> #include <EasyFactorGraph/trainable/ModelTrainer.h> using namespace EFG::model; using namespace EFG::factor; using namespace EFG::categoric; using namespace EFG::strct; using namespace EFG::io; using namespace EFG::train; // you can also use another iterative trainer #include <TrainingTools/iterative/solvers/QuasiNewton.h> using namespace train; // just a bunch of utilities needed by the sample #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; int main() { SAMPLE_SECTION("Tuning of a conditional random field ", "4.7", [] { RandomField temporary_imported_structure; xml::Importer::importFromFile(temporary_imported_structure, SAMPLE_FOLDER + std::string{"cond_graph.xml"}); ConditionalRandomField conditional_field(temporary_imported_structure, false); cout << "creating the training set, might take a while" << endl; TrainSet train_set(conditional_field.makeTrainSet( GibbsSampler::SamplesGenerationContext{30, 50, 0}, 1.f, 4)); cout << "training set created" << endl; const auto expected_weights = conditional_field.getWeights(); // set all weights to 1 and train the model on the previously generated // train set set_ones(conditional_field); QuasiNewton trainer; trainer.setMaxIterations(15); cout << "training the model, this might take a while as conditional " "random " "field are much more computationally demanding" << endl; trainer.enablePrintAdvancement(); train_model(conditional_field, trainer, train_set, TrainInfo{4, 1.f}); cout << "expected weights: " << expected_weights << endl; cout << "wieghts after train: " << conditional_field.getWeights() << endl; }); return EXIT_SUCCESS; }
2,151
C++
.cpp
53
34.886792
78
0.694631
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,923
Sample08-Subgraphing.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample08-Subgraphing/Sample08-Subgraphing.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/io/xml/Importer.h> #include <EasyFactorGraph/model/Graph.h> using namespace EFG::model; using namespace EFG::factor; using namespace EFG::categoric; using namespace EFG::strct; using namespace EFG::io; // just a bunch of utilities needed by the sample #include <Frequencies.h> #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; float compute_images_sum(const Function &distribution); int main() { SAMPLE_SECTION("Joint distribution of a subgroup of variables ", "4.8.1", [] { Graph graph; // build the model VariablePtr A = make_variable(2, "A"); VariablePtr B = make_variable(2, "B"); VariablePtr C = make_variable(2, "C"); VariablePtr D = make_variable(2, "D"); float alfa = 0.5f, beta = 1.5f; graph.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{A, B}, Factor::SimplyCorrelatedTag{}}, alfa)); graph.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{B, C}, Factor::SimplyCorrelatedTag{}}, beta)); graph.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{C, D}, Factor::SimplyCorrelatedTag{}}, 1.f)); // get the joint marginal probabilities of group ABC cout << "P(A,B,C)" << endl; cout << make_distribution({expf(alfa) * expf(beta), expf(alfa), 1.f, expf(beta), expf(beta), 1.f, expf(alfa), expf(alfa) * expf(beta)}) << " theoretical values" << endl; cout << graph.getJointMarginalDistribution({"A", "B", "C"}) .getProbabilities() << " computed values" << endl << endl; // get the joint marginal probabilities of group AB cout << "P(A,B)" << endl; cout << make_distribution({expf(alfa), 1.f, 1.f, expf(alfa)}) << " theoretical values" << endl; cout << graph.getJointMarginalDistribution({"A", "B"}).getProbabilities() << " computed values" << endl << endl; }); SAMPLE_SECTION( "Joint distribution of a subgroup of variables inside a complex model ", "4.8.2", [] { Graph graph; xml::Importer::importFromFile(graph, SAMPLE_FOLDER + std::string{"graph.xml"}); // set the evidences graph.setEvidence("X1", 0); graph.setEvidence("X2", 0); // produce a list of samples for the hidden variables, conditioned by // the observed values for the other ones auto samples = graph.makeSamples( GibbsSampler::SamplesGenerationContext{1000, 50, 0, 1000}); { // compute the marginal probabilities of the following two // combinations (values refer to variables in the subgraph, i.e. // A1,2,3,4) vector<vector<size_t>> comb_raw = {{0, 0, 0, 0}, {1, 1, 0, 0}}; auto marginal_A_1234 = graph.getJointMarginalDistribution({"A1", "A2", "A3", "A4"}); float images_sum = compute_images_sum(marginal_A_1234.function()); cout << endl << "Prob(A1=0, A2=0, A3=0, A4=0 | X1=0,X2=0)" << endl; cout << getEmpiricalProbability( comb_raw.front(), marginal_A_1234.function().vars().getVariables(), samples, graph.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << marginal_A_1234.function().findTransformed(comb_raw.front()) / images_sum << " computed values" << endl; cout << endl << "Prob(A1=1, A2=1, A3=0, A4=0 | X1=0,X2=0)" << endl; cout << getEmpiricalProbability( comb_raw.back(), marginal_A_1234.function().vars().getVariables(), samples, graph.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << marginal_A_1234.function().findTransformed(comb_raw.back()) / images_sum << " computed values" << endl; } { // compute the marginal probabilities of the following two // combinations (values refer to variables in the subgraph, i.e. // B1,2,3) vector<vector<size_t>> comb_raw = {{0, 0, 0}, {1, 1, 0}}; auto marginal_B_123 = graph.getJointMarginalDistribution({"B1", "B2", "B3"}); float images_sum = compute_images_sum(marginal_B_123.function()); cout << endl << "Prob(B1=0, B2=0, B3=0 | X1=0,X2=0)" << endl; cout << getEmpiricalProbability( comb_raw.front(), marginal_B_123.function().vars().getVariables(), samples, graph.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << marginal_B_123.function().findTransformed(comb_raw.front()) / images_sum << " computed values" << endl; cout << endl << "Prob(B1=1, B2=1, B3=0 | X1=0,X2=0)" << endl; cout << getEmpiricalProbability( comb_raw.back(), marginal_B_123.function().vars().getVariables(), samples, graph.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << marginal_B_123.function().findTransformed(comb_raw.back()) / images_sum << " computed values" << endl; } // set different evidences graph.setEvidence("X1", 1); graph.setEvidence("X2", 1); // produce a list of samples for the hidden variables, conditioned by // the novel evidences samples = graph.makeSamples( GibbsSampler::SamplesGenerationContext{1000, 50, 2, 1000}); { // compute the marginal probabilities of the following two // combinations (values refer to variables in the subgraph, i.e. // A1,2,3,4) vector<vector<size_t>> comb_raw = {{0, 0, 0, 0}, {1, 1, 0, 0}}; auto marginal_A_1234 = graph.getJointMarginalDistribution({"A1", "A2", "A3", "A4"}); float images_sum = compute_images_sum(marginal_A_1234.function()); cout << endl << "Prob(A1=0, A2=0, A3=0, A4=0 | X1=1,X2=1)" << endl; cout << getEmpiricalProbability( comb_raw.front(), marginal_A_1234.function().vars().getVariables(), samples, graph.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << marginal_A_1234.function().findTransformed(comb_raw.front()) / images_sum << " computed values" << endl; cout << endl << "Prob(A1=1, A2=1, A3=0, A4=0 | X1=1,X2=1)" << endl; cout << getEmpiricalProbability( comb_raw.back(), marginal_A_1234.function().vars().getVariables(), samples, graph.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << marginal_A_1234.function().findTransformed(comb_raw.back()) / images_sum << " computed values" << endl; } }); return EXIT_SUCCESS; } float compute_images_sum(const Function &distribution) { float result = 0; distribution.forEachNonNullCombination<true>( [&result](const auto &, float img) { result += img; }); return result; }
7,891
C++
.cpp
166
36.722892
80
0.571503
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,924
Printing.cpp
andreacasalino_Easy-Factor-Graph/samples/Helpers/Printing.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include "Printing.h" #include <functional> std::ostream &operator<<(std::ostream &s, const EFG::categoric::VariablesSoup &group) { s << group.front()->name(); for (std::size_t k = 1; k < group.size(); ++k) { s << ' ' << group[k]->name(); } return s; } std::ostream &operator<<(std::ostream &s, const EFG::categoric::Group &group) { const auto &vars = group.getVariables(); s << '{' << vars.front()->name(); for (std::size_t k = 1; k < vars.size(); ++k) { s << ", " << vars[k]->name(); } s << '}'; return s; } namespace { template <typename T> void print_vector( std::ostream &s, const std::vector<T> &subject, const std::function<void(std::ostream &, const T &)> &pred = [](std::ostream &s, const T &element) { s << element; }) { pred(s, subject.front()); for (std::size_t k = 1; k < subject.size(); ++k) { s << ' '; pred(s, subject[k]); } } } // namespace std::ostream &operator<<(std::ostream &s, const std::vector<float> &values) { print_vector(s, values); return s; } std::ostream &operator<<(std::ostream &s, const std::vector<std::size_t> &values) { print_vector(s, values); return s; } namespace { using Line = std::vector<std::string>; template <std::size_t TableSize> class TabularStream { public: TabularStream() { for (std::size_t k = 0; k < TableSize; ++k) { columns_sizes.push_back(0); } } void addLine(const Line &line) { if (line.size() != TableSize) { throw std::runtime_error{"Invalid line to print"}; } lines.push_back(line); for (std::size_t col = 0; col < TableSize; ++col) { if (columns_sizes[col] < line[col].size()) { columns_sizes[col] = line[col].size(); } } } void print(std::ostream &s) const { for (const auto &line : lines) { s << std::endl; for (std::size_t col = 0; col < TableSize; ++col) { std::string to_add = line[col]; to_add.reserve(columns_sizes[col]); while (to_add.size() != columns_sizes[col]) { to_add.push_back(' '); } s << ' ' << to_add; } } } private: std::vector<std::size_t> columns_sizes; std::vector<Line> lines; }; } // namespace #include <sstream> std::ostream &operator<<(std::ostream &s, const EFG::factor::Function &distribution) { TabularStream<4> table; std::stringstream group_stream; group_stream << distribution.vars().getVariables(); table.addLine( Line{group_stream.str(), "", "raw image value ", "image value"}); EFG::categoric::GroupRange range(distribution.vars()); std::vector<std::vector<std::size_t>> combinations; std::vector<float> images, transformations; distribution.forEachCombination<false>( [&combinations, &images](const auto &comb, float img) { combinations.push_back(comb); images.push_back(img); }); distribution.forEachCombination<true>( [&transformations](const auto &, float img) { transformations.push_back(img); }); for (std::size_t k = 0; k < combinations.size(); ++k) { Line to_add; std::stringstream comb_stream; print_vector(comb_stream, combinations[k]); to_add.push_back(comb_stream.str()); to_add.push_back(" -> "); to_add.push_back(std::to_string(images[k])); to_add.push_back(std::to_string(transformations[k])); table.addLine(to_add); } table.print(s); return s; }
3,594
C++
.cpp
118
25.847458
79
0.602601
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,925
Frequencies.cpp
andreacasalino_Easy-Factor-Graph/samples/Helpers/Frequencies.cpp
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #include <EasyFactorGraph/Error.h> #include <Frequencies.h> #include <Printing.h> #include <algorithm> namespace { std::size_t find_var_position(EFG::categoric::VariablePtr var2Search, const EFG::categoric::VariablesSoup &samplesGroup) { return std::distance( samplesGroup.begin(), std::find(samplesGroup.begin(), samplesGroup.end(), var2Search)); } } // namespace std::vector<float> getEmpiricalMarginals(EFG::categoric::VariablePtr var2Search, const std::vector<std::vector<std::size_t>> &samples, const EFG::categoric::VariablesSoup &samplesGroup) { std::vector<std::size_t> counters; counters.reserve(var2Search->size()); for (std::size_t k = 0; k < var2Search->size(); ++k) { counters.push_back(0); } const std::size_t var_pos = find_var_position(var2Search, samplesGroup); for (const auto &sample : samples) { ++counters[sample.data()[var_pos]]; } std::vector<float> result; result.reserve(counters.size()); for (const auto counter : counters) { result.push_back(static_cast<float>(counter) / static_cast<float>(samples.size())); } return result; } float getEmpiricalProbability( const std::vector<std::size_t> &comb2Search, const EFG::categoric::VariablesSoup &combGroup, const std::vector<std::vector<std::size_t>> &samples, const EFG::categoric::VariablesSoup &samplesGroup) { std::size_t counter = 0; std::vector<std::size_t> var2Search_positions; for (const auto &var : combGroup) { var2Search_positions.push_back(find_var_position(var, samplesGroup)); } for (const auto &sample : samples) { bool increment = true; const auto &sample_data = sample.data(); const auto &comb2Search_data = comb2Search.data(); for (std::size_t k = 0; k < var2Search_positions.size(); ++k) { if (sample_data[var2Search_positions[k]] != comb2Search_data[k]) { increment = false; break; } } if (increment) { ++counter; } } return static_cast<float>(counter) / static_cast<float>(samples.size()); } std::vector<float> make_distribution(const std::vector<float> &values) { float coeff = 0; for (const auto value : values) { coeff += value; } coeff = 1.f / coeff; auto result = values; for (auto &value : result) { value *= coeff; } return result; }
2,510
C++
.cpp
78
27.730769
75
0.665841
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,926
Sample03-BeliefPropagation-B.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample03-BeliefPropagation-B/Sample03-BeliefPropagation-B.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/factor/Factor.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/io/xml/Importer.h> #include <EasyFactorGraph/model/Graph.h> using namespace EFG::model; using namespace EFG::factor; using namespace EFG::categoric; using namespace EFG::strct; // just a bunch of utilities needed by the sample #include <Frequencies.h> #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; std::string merge(const std::string &first, const std::string &second); int main() { SAMPLE_SECTION("Simple polytree belief propagation", "4.3.1", [] { Graph graph; // import the graph from an xml file EFG::io::xml::Importer::importFromFile(graph, merge(SAMPLE_FOLDER, "graph_1.xml")); float a = expf(1.f), b = expf(2.f), g = expf(1.f), e = expf(1.5f); // set E=1 as an evidence graph.setEvidence("E", 1); cout << endl << endl; cout << "E=1\n"; // compute the marginals distributions of the other variables and // compare it cout << "P(A|E)\n"; cout << make_distribution( {(a * (g + e) + (1 + g * e)), ((g + e) + a * (1 + g * e))}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("A") << " computed values" << endl << endl; cout << "P(B|E)\n"; cout << make_distribution({(g + e), (1 + g * e)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("B") << " computed values" << endl << endl; cout << "P(C|E)\n"; cout << make_distribution( {(b * (g + e) + (1 + g * e)), ((g + e) + b * (1 + g * e))}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("C") << " computed values" << endl << endl; cout << "P(D|E)\n"; cout << make_distribution({1.f, e}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("D") << " computed values" << endl << endl; // set E=0 as an evidence and recompute the marginals graph.setEvidence("E", 0); cout << endl << endl; cout << "E=0\n"; cout << "P(A|E)\n"; cout << make_distribution( {(g + e) + a * (1 + g * e), a * (g + e) + (1 + g * e)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("A") << " computed values" << endl << endl; cout << "P(B|E)\n"; cout << make_distribution({1 + g * e, g + e}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("B") << " computed values" << endl << endl; cout << "P(C|E)\n"; cout << make_distribution( {(g + e) + b * (1 + g * e), b * (g + e) + (1 + g * e)}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("C") << " computed values" << endl << endl; cout << "P(D|E)\n"; cout << make_distribution({e, 1.f}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("D") << " computed values" << endl << endl; // set D=1 as an evidence and recompute the marginals of the hidden // variables (including E) graph.removeAllEvidences(); graph.setEvidence("D", 1); cout << endl << endl; cout << "D=1\n"; cout << "P(A|D)\n"; cout << make_distribution({a + g, 1.f + a * g}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("A") << " computed values" << endl << endl; cout << "P(B|D)\n"; cout << make_distribution({1.f, g}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("B") << " computed values" << endl << endl; cout << "P(C|D)\n"; cout << make_distribution({b + g, 1.f + b * g}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("C") << " computed values" << endl << endl; cout << "P(E|D)\n"; cout << make_distribution({1.f, e}) << " theoretical values" << endl; cout << graph.getMarginalDistribution("E") << " computed values" << endl << endl; }); SAMPLE_SECTION("Complex polytree belief propagation", "4.3.2", [] { Graph politree; // import the graph an existing xml file EFG::io::xml::Importer::importFromFile(politree, merge(SAMPLE_FOLDER, "graph_2.xml")); GibbsSampler::SamplesGenerationContext context_for_saples_generation = GibbsSampler::SamplesGenerationContext{ 1500, // number of desired samples 50, 0}; // use internal thread pool to fasten various computations below std::size_t threads = 3; // set v1,v2,v3 as observations and use Gibbs sampling // to produce samples for the joint conditioned (to the observations) // distribution of the hidden variables politree.setEvidence("v1", 1); politree.setEvidence("v2", 1); politree.setEvidence("v3", 1); auto samples = politree.makeSamples(context_for_saples_generation, threads); auto hidden_set = politree.getHiddenVariables(); // compare the computed marginals with the ones coming from the samples // obtained by the Gibbs sampler cout << "P(v10 | Observations): \n"; cout << getEmpiricalMarginals(politree.findVariable("v10"), samples, politree.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << politree.getMarginalDistribution("v10") << " computed values" << endl << endl; cout << "P(v11 | Observations): \n"; cout << getEmpiricalMarginals(politree.findVariable("v11"), samples, politree.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << politree.getMarginalDistribution("v11") << " computed values" << endl << endl; cout << "P(v12 | Observations): \n"; cout << getEmpiricalMarginals(politree.findVariable("v12"), samples, politree.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << politree.getMarginalDistribution("v12") << " computed values" << endl << endl; }); SAMPLE_SECTION("Simple loopy model belief propagation", "4.3.3", [] { Graph loop; // import the graph an existing xml file EFG::io::xml::Importer::importFromFile(loop, merge(SAMPLE_FOLDER, "graph_3.xml")); // set the observation loop.setEvidence("E", 1); cout << endl << endl; cout << "E=1\n"; // compute the marginals distributions of the hidden variables and // compare it float M = expf(1.f); float M_alfa = powf(M, 3) + M + 2.f * powf(M, 2); float M_beta = powf(M, 4) + 2.f * M + powf(M, 2); cout << "P(D|E)\n"; cout << make_distribution( {3.f * M + powf(M, 3), powf(M, 4) + 3.f * powf(M, 2)}) << " theoretical values" << endl; cout << loop.getMarginalDistribution("D") << " computed values" << endl << endl; cout << "P(C|E)\n"; cout << make_distribution({M_alfa, M_beta}) << " theoretical values" << endl; cout << loop.getMarginalDistribution("C") << " computed values" << endl << endl; cout << "P(B|E)\n"; cout << make_distribution({M_alfa, M_beta}) << " theoretical values" << endl; cout << loop.getMarginalDistribution("B") << " computed values" << endl << endl; cout << "P(A|E)\n"; cout << make_distribution({M * M_alfa + M_beta, M_alfa + M * M_beta}) << " theoretical values" << endl; cout << loop.getMarginalDistribution("A") << " computed values" << endl << endl; }); SAMPLE_SECTION("Complex loopy model belief propagation", "4.3.4", [] { Graph loop; // import the graph an existing xml file EFG::io::xml::Importer::importFromFile(loop, merge(SAMPLE_FOLDER, "graph_4.xml")); GibbsSampler::SamplesGenerationContext context_for_saples_generation = GibbsSampler::SamplesGenerationContext{500, // number of desired samples 50, 0}; // use internal thread pool to fasten various computations below std::size_t threads = 3; // set v1=1 as an evidence and use a Gibbs sampler // to produce samples for the joint conditioned (to the observations) // distribution of the hidden variables loop.setEvidence("v1", 1); auto samples = loop.makeSamples(context_for_saples_generation, threads); auto hidden_set = loop.getHiddenVariables(); // compare the computed marginals with the ones coming from the samples // obtained by the Gibbs sampler cout << "P(v8 | Observations): \n"; cout << getEmpiricalMarginals(loop.findVariable("v8"), samples, loop.getAllVariables()) << " empirical values from Gibbs sampling" << endl; cout << loop.getMarginalDistribution("v8", threads) << " computed values" << endl << endl; // use the interal thread pool to also fasten the compuations // of the amrginal distribution }); return EXIT_SUCCESS; } std::string merge(const std::string &first, const std::string &second) { std::stringstream stream; stream << first << second; return stream.str(); }
9,660
C++
.cpp
219
36.6621
80
0.589105
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,927
Sample06-Learning-A.cpp
andreacasalino_Easy-Factor-Graph/samples/Sample06-Learning-A/Sample06-Learning-A.cpp
/** * Author: Andrea Casalino * Created: 03.01.2020 * * report any bug to andrecasa91@gmail.com. **/ // what is required from the EFG core library #include <EasyFactorGraph/io/xml/Importer.h> #include <EasyFactorGraph/model/RandomField.h> #include <EasyFactorGraph/trainable/ModelTrainer.h> using namespace EFG::model; using namespace EFG::factor; using namespace EFG::categoric; using namespace EFG::strct; using namespace EFG::io; using namespace EFG::train; // you can also use another iterative trainer #include <TrainingTools/iterative/solvers/GradientDescend.h> #include <TrainingTools/iterative/solvers/QuasiNewton.h> using namespace train; // just a bunch of utilities needed by the sample #include <Printing.h> #include <SampleSection.h> #include <iostream> using namespace std; /// Extracts samples using Gibbs sampler to generate a training set. /// Then, set all weights of the model to 1 and try to tune the model with the /// previously generated train set. /// The obtained weights are expected to be close to the initial ones. void train_model(RandomField &model_to_tune, ::train::IterativeTrainer &tuner, const std::size_t max_iterations, const std::size_t train_set_size); int main() { SAMPLE_SECTION("Simple tunable model ", "4.6.1", [] { RandomField model; VariablePtr A = make_variable(2, "A"); VariablePtr B = make_variable(2, "B"); VariablePtr C = make_variable(2, "C"); float alfa = 1.f, beta = 1.5f, gamma = 0.5f; model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{A, B}, Factor::SimplyCorrelatedTag{}}, alfa)); model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{A, C}, Factor::SimplyCorrelatedTag{}}, beta)); model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{B, C}, Factor::SimplyCorrelatedTag{}}, gamma)); ::train::QuasiNewton tuner; train_model(model, tuner, 50, 500); }); SAMPLE_SECTION("Medium tunable model ", "4.6.2", [] { RandomField model; VariablePtr A = make_variable(2, "A"); VariablePtr B = make_variable(2, "B"); VariablePtr C = make_variable(2, "C"); VariablePtr D = make_variable(2, "D"); VariablePtr E = make_variable(2, "E"); float alfa = 0.4f, beta = 0.7f, gamma = 0.3f, delta = 1.5f; model.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{A, B}, Factor::SimplyCorrelatedTag{}}, alfa)); // the weight of this potential will be // kept constant model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{A, C}, Factor::SimplyCorrelatedTag{}}, beta)); model.addConstFactor(std::make_shared<Factor>( VariablesSoup{C, D}, Factor::SimplyCorrelatedTag{})); model.addConstFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{B, E}, Factor::SimplyCorrelatedTag{}}, gamma)); // the weight of this potential will be // kept constant model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{D, E}, Factor::SimplyCorrelatedTag{}}, delta)); ::train::QuasiNewton tuner; train_model(model, tuner, 50, 1500); }); SAMPLE_SECTION("Complex tunable model ", "4.6.3", [] { RandomField model; xml::Importer::importFromFile(model, SAMPLE_FOLDER + std::string{"graph_3.xml"}); ::train::QuasiNewton tuner; train_model(model, tuner, 50, 2000); }); SAMPLE_SECTION("Model with sharing weights", "4.6.4", [] { RandomField model; VariablePtr X1 = make_variable(2, "X1"); VariablePtr X2 = make_variable(2, "X2"); VariablePtr X3 = make_variable(2, "X3"); VariablePtr Y1 = make_variable(2, "Y1"); VariablePtr Y2 = make_variable(2, "Y2"); VariablePtr Y3 = make_variable(2, "Y3"); float alfa = 2.f; float beta = 1.f; model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{Y1, Y2}, Factor::SimplyCorrelatedTag{}}, alfa)); model.addTunableFactor( std::make_shared<FactorExponential>( Factor{VariablesSoup{Y2, Y3}, Factor::SimplyCorrelatedTag{}}, alfa), VariablesSet{Y1, Y2}); // this will force this added factor to share the // weight with the one connecting variables Y1,Y2 model.addTunableFactor(std::make_shared<FactorExponential>( Factor{VariablesSoup{Y1, X1}, Factor::SimplyCorrelatedTag{}}, beta)); model.addTunableFactor( std::make_shared<FactorExponential>( Factor{VariablesSoup{Y2, X2}, Factor::SimplyCorrelatedTag{}}, beta), VariablesSet{Y1, X1}); // this will force this added factor to share the // weight with the one connecting variables Y1,X1 model.addTunableFactor( std::make_shared<FactorExponential>( Factor{VariablesSoup{Y3, X3}, Factor::SimplyCorrelatedTag{}}, beta), VariablesSet{Y1, X1}); // this will force this added factor to share the // weight with the one connecting variables Y1,X1 ::train::QuasiNewton tuner; train_model(model, tuner, 50, 1000); }); return EXIT_SUCCESS; } void train_model(RandomField &model_to_tune, ::train::IterativeTrainer &tuner, const std::size_t max_iterations, const std::size_t train_set_size) { const auto expected_weights = model_to_tune.getWeights(); // generate the training set from the current model auto samples = model_to_tune.makeSamples( GibbsSampler::SamplesGenerationContext{train_set_size, 50, 0}); // set all weights to 1 and train the model on the previously generated // train set set_ones(model_to_tune); tuner.setMaxIterations(max_iterations); train_model(model_to_tune, tuner, TrainSet{samples}); cout << "expected weights: " << expected_weights << endl; cout << "weights after train: " << model_to_tune.getWeights() << endl; }
6,082
C++
.cpp
129
41
80
0.683046
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,928
ModelLibrary.h
andreacasalino_Easy-Factor-Graph/tests/ModelLibrary.h
#pragma once #include <EasyFactorGraph/model/RandomField.h> namespace EFG::test::library { class SimpleTree : public EFG::model::RandomField { public: SimpleTree(); static const float alfa; static const float beta; static const float gamma; static const float eps; }; class ComplexTree : public EFG::model::RandomField { public: ComplexTree(); }; class SimpleLoopy : public EFG::model::RandomField { public: SimpleLoopy(); static const float w; }; class ComplexLoopy : public EFG::model::RandomField { public: ComplexLoopy(); }; class ScalableModel : public model::RandomField { public: ScalableModel(std::size_t size, std::size_t var_size, const bool loopy); categoric::VariablePtr root() const; categoric::VariablePtr nonRoot() const; }; } // namespace EFG::test::library
808
C++
.h
31
23.967742
74
0.762712
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,929
Utils.h
andreacasalino_Easy-Factor-Graph/tests/Utils.h
#pragma once #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/factor/Factor.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/structure/bases/FactorsAware.h> #include <EasyFactorGraph/trainable/TrainSet.h> #include <chrono> #include <cmath> #include <math.h> namespace EFG::test { template <typename T> bool almost_equal(T a, T b, T tollerance) { return std::abs(a - b) < tollerance; } template <typename IterableA, typename IterableB> bool almost_equal_it(const IterableA &a, const IterableB &b, float tollerance) { if (a.size() != b.size()) { return false; } auto it_a = a.begin(); auto it_b = b.begin(); for (; it_a != a.end(); ++it_a, ++it_b) { if (!almost_equal(*it_a, *it_b, tollerance)) { return false; } } return true; } bool almost_equal_fnct(const factor::Function &a, const factor::Function &b); categoric::Group make_group(const std::vector<std::size_t> &sizes); factor::Factor make_corr_factor(const categoric::VariablePtr &first, const categoric::VariablePtr &second); std::shared_ptr<factor::Factor> make_corr_factor_ptr(const categoric::VariablePtr &first, const categoric::VariablePtr &second); factor::FactorExponential make_corr_expfactor(const categoric::VariablePtr &first, const categoric::VariablePtr &second, float w); std::shared_ptr<factor::FactorExponential> make_corr_expfactor_ptr(const categoric::VariablePtr &first, const categoric::VariablePtr &second, float w); std::vector<float> make_prob_distr(const std::vector<float> &values); void setAllImages(factor::Factor &subject, float img); struct CombinationsAndProbabilities { std::vector<float> probs; std::vector<std::vector<std::size_t>> combinations; }; CombinationsAndProbabilities compute_combinations_and_probs(const strct::FactorsAware &model); train::TrainSet make_good_trainset(const strct::FactorsAware &model, std::size_t samples); template <typename Pred> std::chrono::nanoseconds measure_time(Pred &&pred) { auto tic = std::chrono::high_resolution_clock::now(); pred(); return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now() - tic); } class LikelihoodGetter { public: LikelihoodGetter(const strct::FactorsAware &model); float getLogActivation(const std::vector<std::size_t> &c) const; float getLogLikeliHood(const EFG::train::TrainSet::Iterator &combinations); private: categoric::Group vars; std::vector<factor::ImageFinder> finders; }; } // namespace EFG::test
2,663
C++
.h
66
36.136364
80
0.719441
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,930
Error.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/Error.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/misc/Strings.h> #include <stdexcept> namespace EFG { class Error : public std::runtime_error { public: Error(const std::string &what); template <typename... Args> static Error make(Args &&...args) { return Error{join<' '>(std::forward<Args>(args)...)}; } }; } // namespace EFG
442
C++
.h
18
22.444444
65
0.687351
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,931
Graph.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/model/Graph.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/EvidenceManager.h> #include <EasyFactorGraph/structure/FactorsConstManager.h> #include <EasyFactorGraph/structure/GibbsSampler.h> #include <EasyFactorGraph/structure/QueryManager.h> namespace EFG::model { /** * @brief A simple graph object, that stores only const factors. * Evidences may be changed over the time. */ class Graph : public strct::EvidenceSetter, public strct::EvidenceRemover, public strct::FactorsConstInserter, public strct::GibbsSampler, public strct::QueryManager { public: Graph() = default; Graph(const Graph &o) { absorb(o, false); }; Graph &operator=(const Graph &) = delete; /** * @brief Gather all the factors (tunable and constant) of another model and * insert/copy them into this object. * @param the model whose factors should be inserted/copied * @param when passing true the factors are deep copied, while in the contrary * case shallow copies of the smart pointers are inserted into this model. */ void absorb(const strct::FactorsAware &to_absorb, bool copy); }; } // namespace EFG::model
1,274
C++
.h
35
32.628571
80
0.724473
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,932
RandomField.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/model/RandomField.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/EvidenceManager.h> #include <EasyFactorGraph/structure/FactorsConstManager.h> #include <EasyFactorGraph/structure/GibbsSampler.h> #include <EasyFactorGraph/structure/QueryManager.h> #include <EasyFactorGraph/trainable/FactorsTunableManager.h> namespace EFG::model { /** * @brief A complete undurected factor graph storing both constant and tunable * factors. Evidences may be changed over the time. */ class RandomField : public strct::EvidenceSetter, public strct::EvidenceRemover, public strct::FactorsConstInserter, public train::FactorsTunableInserter, public strct::GibbsSampler, public strct::QueryManager { public: RandomField() = default; RandomField(const RandomField &o) { absorb(o, false); }; RandomField &operator=(const RandomField &) = delete; /** * @brief Gather all the factors (tunable and constant) of another model and * insert/copy them into this object. * Tunable factors (Exponential non constant) are recognized and * inserted/copied using the train::FactorsTunableAdder interface. All the * others inserted/copied using the strct::FactorsAdder interface. * @param the model whose factors should be inserted/copied * @param when passing true the factors are deep copied, while in the contrary * case shallow copies of the smart pointers storing the factors are inserted * into this model. */ void absorb(const strct::FactorsAware &to_absorb, bool copy); protected: std::vector<float> getWeightsGradient_( const train::TrainSet::Iterator &train_set_combinations) final; }; } // namespace EFG::model
1,838
C++
.h
44
37.090909
80
0.734899
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,933
ConditionalRandomField.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/model/ConditionalRandomField.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/model/RandomField.h> #include <EasyFactorGraph/trainable/tuners/BaseTuner.h> namespace EFG::model { /** * @brief Similar to RandomField, with the difference that the model structure * is immutable after construction. This applies also to the evidence set, which * can't be changed over the time. */ class ConditionalRandomField : protected strct::EvidenceSetter, protected strct::EvidenceRemover, virtual public strct::FactorsAware, virtual public strct::FactorsConstGetter, protected strct::FactorsConstInserter, virtual public train::FactorsTunableGetter, protected train::FactorsTunableInserter, public strct::GibbsSampler, public strct::QueryManager { public: ConditionalRandomField() = delete; ConditionalRandomField(const ConditionalRandomField &o); ConditionalRandomField &operator=(const ConditionalRandomField &) = delete; /** * @brief All the factors of the passed source are inserted/copied. The * evidence set is deduced by the passed source. * @param the model to emulate for building the structure of this one. * @param then passing true the factors are deep copied, while in the contrary * case the smart pointers storing the factors of the source are copied and * inserted. * @throw in case the passed source has no evidences */ ConditionalRandomField(const RandomField &source, bool copy); /** * @brief Sets the new set of evidences. * @param the new set of evidence values. The variables order is the same of * the set obtained using getObservedVariables(). * @throw the number of passed values does not match the number of evidences. * @throw in case some evidence values are inconsistent */ void setEvidences(const std::vector<std::size_t> &values); /** * @brief Builds a training set for the conditioned model. * Instead of using Gibbs sampler for a single combination of evidence, it * tries to span all the possible combination of evidences and generate some * samples conditioned to each of this evidences value. * Then, gather results to build the training set. * Actually, not ALL possible evidence are spwan if that would be too much * computationally demanding. In such cases, simply pass a number lower than 1 * as range_percentage. * * @param information used for samples generation * @param parameter handling how many evidence values are accounted for the * samples generation * @param the number of threads to use for speeding up the process */ std::vector<std::vector<std::size_t>> makeTrainSet(const GibbsSampler::SamplesGenerationContext &context, float range_percentage = 1.f, std::size_t threads = 1); protected: std::vector<float> getWeightsGradient_( const train::TrainSet::Iterator &train_set_combinations) final; private: struct SourceStructure { const strct::FactorsConstGetter *factors_structure; const train::FactorsTunableGetter *factors_tunable_structure; }; void absorb(const SourceStructure &source, bool copy); void replaceIfNeeded(train::TunerPtr &container, const train::BaseTuner &subject); const std::vector<std::size_t> evidence_vars_positions; }; } // namespace EFG::model
3,610
C++
.h
78
39.692308
80
0.707185
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,934
ModelTrainer.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/ModelTrainer.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_LEARNING_ENABLED #pragma once #include <EasyFactorGraph/trainable/FactorsTunableManager.h> #include <TrainingTools/Trainer.h> namespace EFG::train { struct TrainInfo { /** * @brief Number of threads to use for the training procedure. */ std::size_t threads = 1; /** * @brief 1 means actually to use all the train set, adopting a classical * gradient based approach. A lower value implies to a stochastic gradient * based approach. */ float stochastic_percentage = 1.f; }; /** * @param the model to tune * @param the training approach to adopt * @param the train set to use */ void train_model(FactorsTunableGetter &subject, ::train::Trainer &trainer, const TrainSet &train_set, const TrainInfo &info = TrainInfo{}); } // namespace EFG::train #endif
942
C++
.h
33
25.242424
76
0.703991
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,935
TrainSet.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/TrainSet.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <memory> #include <optional> #include <vector> namespace EFG::train { using Combinations = std::vector<std::vector<std::size_t>>; class TrainSet { public: /** * @param the set of combinations that will be part of the train set. * @throw if the combinations don't have all the same size * @throw if the combinations container is empty */ TrainSet(const std::vector<std::vector<std::size_t>> &combinations); const auto &getCombinations() const { return *this->combinations; }; class Iterator; Iterator makeIterator() const; Iterator makeSubSetIterator(float percentage) const; private: std::shared_ptr<const Combinations> combinations; }; /** * @brief an object able to iterate all the combinations that are part of a * training set or a sub portion of it. */ class TrainSet::Iterator { public: /** * @brief involved train set * @param the percentage of combinations to extract from the passed subject. * Passing a value equal to 1, means to use all the combinations of the passed * subject. */ Iterator(const TrainSet &subject, float percentage); template <typename Predicate> void forEachSample(const Predicate &pred) const { if (combinations_subset.has_value()) { const auto &coll = *combinations; for (auto index : combinations_subset.value()) { pred(coll[index]); } return; } for (const auto &sample : *combinations) { pred(sample); } } /** * @return number of combinations considered by this train set iterator. */ std::size_t size() const; private: std::shared_ptr<const Combinations> combinations; std::optional<std::vector<std::size_t>> combinations_subset; }; } // namespace EFG::train
1,863
C++
.h
62
26.774194
80
0.710129
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,936
FactorsTunableManager.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/FactorsTunableManager.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/FactorsAware.h> #include <EasyFactorGraph/trainable/tuners/Tuner.h> #include <optional> #include <variant> namespace EFG::train { using TunableClusters = std::vector<FactorExponentialPtr>; class FactorsTunableGetter : virtual public strct::FactorsAware { public: /** * @brief Get the collections of tunable exponential factors. */ const std::unordered_set<FactorExponentialPtr> &getTunableFactors() const { return tunable_factors; } /** * @brief Get the clusters of tunable exponential factors. Elements in the * same cluster, shares the weight. */ std::vector<std::variant<FactorExponentialPtr, TunableClusters>> getTunableClusters() const; /** * @return the weights of all the tunable factors that are part of the model. * The same order assumed by getTunableClusters() is assumed. */ std::vector<float> getWeights() const; /** * @return sets the weights to use for of all the tunable factors that are * part of the model. The same order assumed by getTunableClusters() should be * assumed. * @throw in case the number of specified weights is inconsistent */ void setWeights(const std::vector<float> &weights); /** * @return the gradients of the weights of all the tunable factors that are * part of the model, w.r.t a certain training set. The same order assumed by * getTunableClusters() is assumed. * @param the training set to use * @param the number of threads to use for the gradient computation */ std::vector<float> getWeightsGradient(const TrainSet::Iterator &train_set_combinations, std::size_t threads = 1); class ModelWrapper; protected: virtual std::vector<float> getWeightsGradient_(const TrainSet::Iterator &train_set_combinations) = 0; std::unordered_set<FactorExponentialPtr> tunable_factors; Tuners tuners; }; class FactorsTunableInserter : virtual public FactorsTunableGetter { public: /** * @brief add a shallow copy of the passed tunable expoenential factor to this * model. * @param the factor to insert * @param an optional group of variables specifying the tunable factor that * should share the weight with the one to insert. When passing a nullopt the * factor will be inserted without sharing its weight. */ void addTunableFactor(const FactorExponentialPtr &factor, const std::optional<categoric::VariablesSet> &group_sharing_weight = std::nullopt); /** * @brief add a deep copy of the passed tunable expoenential factor to this * model. * @param the factor to insert * @param an optional group of variables specifying the tunable factor that * should share the weight with the one to insert. When passing a nullopt the * factor will be inserted without sharing its weight. */ void copyTunableFactor(const factor::FactorExponential &factor, const std::optional<categoric::VariablesSet> &group_sharing_weight = std::nullopt); /** * @brief adds a collection of tunable expoenential factors ot this model. * Passing copy = true, deep copies are created and inserted in this model. * Passing copy = false, shallow copies are created and inserted in this * model. */ template <typename FactorExponentialIt> void absorbTunableFactors(const FactorExponentialIt &begin, const FactorExponentialIt &end, bool copy) { for (auto it = begin; it != end; ++it) { try { if (copy) { copyTunableFactor(**it); } else { addTunableFactor(*it); } } catch (...) { } } } /** * @brief adds a collection of tunable expoenential factors ot this model, * preserving the fact that elements in the same cluster should share the * weight. * Passing copy = true, deep copies are created and inserted in this model. * Passing copy = false, shallow copies are created and inserted in this * model. */ void absorbTunableClusters(const FactorsTunableGetter &source, bool copy); protected: Tuners::iterator findTuner(const categoric::VariablesSet &tuned_vars_group); private: TunerPtr makeTuner(const FactorExponentialPtr &factor); }; /** * @param sets equal to 1 the weight of all the tunable clusters */ void set_ones(FactorsTunableGetter &subject); } // namespace EFG::train
4,580
C++
.h
119
33.714286
80
0.712807
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,937
TunerVisitor.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/tuners/TunerVisitor.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/trainable/tuners/BaseTuner.h> #include <EasyFactorGraph/trainable/tuners/CompositeTuner.h> namespace EFG::train { template <typename BasePred, typename CompositePred> void visitTuner(const Tuner *tuner, BasePred &&base, CompositePred &&composite) { if (auto *basePtr = dynamic_cast<const BaseTuner *>(tuner); basePtr) { base(*basePtr); } else { composite(static_cast<const CompositeTuner &>(*tuner)); } } template <typename BasePred, typename CompositePred> void visitTuner(Tuner *tuner, BasePred &&base, CompositePred &&composite) { if (auto *basePtr = dynamic_cast<BaseTuner *>(tuner); basePtr) { base(*basePtr); } else { composite(static_cast<CompositeTuner &>(*tuner)); } } } // namespace EFG::train
902
C++
.h
28
29.321429
75
0.721839
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,938
BinaryTuner.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/tuners/BinaryTuner.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/StateAware.h> #include <EasyFactorGraph/trainable/tuners/BaseTuner.h> namespace EFG::train { class BinaryTuner : public BaseTuner { public: BinaryTuner(strct::Node &nodeA, strct::Node &nodeB, const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model); float getGradientBeta() final; protected: strct::Node &nodeA; strct::Node &nodeB; }; } // namespace EFG::train
621
C++
.h
21
26.380952
71
0.727731
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,939
CompositeTuner.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/tuners/CompositeTuner.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/trainable/tuners/Tuner.h> #include <vector> namespace EFG::train { class CompositeTuner : public Tuner { public: Tuners &getElements() { return elements; }; const Tuners &getElements() const { return elements; }; CompositeTuner(TunerPtr elementA, TunerPtr elementB); float getGradientAlpha(const TrainSet::Iterator &iter) final; float getGradientBeta() final; void setWeight(float w) final; float getWeight() const final { return elements.front()->getWeight(); }; void addElement(TunerPtr element); private: Tuners elements; }; } // namespace EFG::train
730
C++
.h
24
28.125
74
0.750716
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,940
UnaryTuner.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/tuners/UnaryTuner.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/StateAware.h> #include <EasyFactorGraph/trainable/tuners/BaseTuner.h> namespace EFG::train { class UnaryTuner : public BaseTuner { public: UnaryTuner(strct::Node &node, const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model); float getGradientBeta() final; protected: strct::Node &node; }; } // namespace EFG::train
573
C++
.h
20
25.55
70
0.731752
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,941
Tuner.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/tuners/Tuner.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/categoric/Group.h> #include <EasyFactorGraph/factor/FactorExponential.h> #include <EasyFactorGraph/trainable/TrainSet.h> namespace EFG::train { using FactorExponentialPtr = std::shared_ptr<factor::FactorExponential>; class Tuner { public: virtual ~Tuner() = default; virtual float getGradientAlpha(const TrainSet::Iterator &iter) = 0; virtual float getGradientBeta() = 0; virtual void setWeight(float w) = 0; virtual float getWeight() const = 0; }; using TunerPtr = std::unique_ptr<Tuner>; using Tuners = std::vector<TunerPtr>; } // namespace EFG::train
722
C++
.h
23
29.391304
72
0.758321
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,942
BaseTuner.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/trainable/tuners/BaseTuner.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/ImageFinder.h> #include <EasyFactorGraph/trainable/tuners/Tuner.h> namespace EFG::train { class BaseTuner : public Tuner { public: FactorExponentialPtr getFactorPtr() const { return factor; } const factor::FactorExponential &getFactor() const { return *factor; } float getGradientAlpha(const TrainSet::Iterator &iter) final; void setWeight(float w) final { factor->setWeight(w); } float getWeight() const final { return factor->getWeight(); }; protected: BaseTuner(const FactorExponentialPtr &factor, const categoric::VariablesSoup &variables_in_model); float dotProduct(const std::vector<float> &prob) const; private: FactorExponentialPtr factor; factor::ImageFinder finder; struct GradientAlphaPart { const TrainSet::Iterator *train_set_iterator; float value; }; std::optional<GradientAlphaPart> alpha_part; }; } // namespace EFG::train
1,048
C++
.h
31
30.967742
72
0.756194
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,943
Cache.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/Cache.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/Error.h> #include <memory> namespace EFG { template <typename T> class Cache : std::unique_ptr<T> { public: Cache() = default; T &reset(std::unique_ptr<T> new_value = nullptr) { auto &ref = cast_(); ref = std::move(new_value); return *ref; } bool empty() const { return nullptr == cast_(); }; T *get() { throw_if_empty(); return cast_().get(); } const T *get() const { throw_if_empty(); return cast_().get(); } private: std::unique_ptr<T> &cast_() { return static_cast<std::unique_ptr<T> &>(*this); } const std::unique_ptr<T> &cast_() const { return static_cast<const std::unique_ptr<T> &>(*this); } void throw_if_empty() const { if (nullptr == cast_()) { throw Error{"Try using empty cache"}; } } }; } // namespace EFG
958
C++
.h
41
20.097561
58
0.61301
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,944
Strings.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/Strings.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <sstream> #include <string.h> namespace EFG { namespace detail { template <char Separator> struct Merger { template <typename Last> void join_(Last &&last) { recipient << last; } template <typename First, typename... Args> void join_(First &&first, Args &&...args) { recipient << Separator << first; join_(std::forward<Args>(args)...); } std::ostream &recipient; }; } // namespace detail template <char Separator, typename... Args> void join(std::ostream &recipient, Args &&...args) { detail::Merger<Separator> merger{recipient}; merger.join_(std::forward<Args>(args)...); } template <char Separator, typename... Args> std::string join(Args &&...args) { std::stringstream buff; detail::Merger<Separator> merger{buff}; merger.join_(std::forward<Args>(args)...); return buff.str(); } } // namespace EFG
972
C++
.h
33
27.151515
78
0.689581
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,945
Visitor.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/Visitor.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <functional> #include <variant> namespace EFG { namespace detail { template <typename T> using Predicate = std::function<void(T &)>; template <typename T> struct Node { Predicate<T> pred_; }; } // namespace detail template <typename... Ts> struct Visitor : public detail::Node<Ts>... { Visitor(detail::Predicate<Ts> &&...predicates) { this->template set<Ts...>( std::forward<detail::Predicate<Ts>>(predicates)...); } template <typename T> void operator()(T &subject) const { this->detail::Node<T>::pred_(subject); } void visit(std::variant<Ts...> &subject) const { std::visit(*this, subject); } template <typename T, typename... Tothers> void set(detail::Predicate<T> &&first, detail::Predicate<Tothers> &&...preds) { this->detail::Node<T>::pred_ = std::forward<detail::Predicate<T>>(first); this->template set<Tothers...>( std::forward<detail::Predicate<Tothers>>(preds)...); } template <typename T> void set(detail::Predicate<T> &&last) { this->detail::Node<T>::pred_ = std::forward<detail::Predicate<T>>(last); } }; // TODO not ideal ... find something better to avoid code duplication namespace detail { template <typename T> using PredicateConst = std::function<void(const T &)>; template <typename T> struct NodeConst { PredicateConst<T> pred_; }; } // namespace detail template <typename... Ts> struct VisitorConst : public detail::NodeConst<Ts>... { VisitorConst(detail::PredicateConst<Ts> &&...predicates) { this->template set<Ts...>( std::forward<detail::PredicateConst<Ts>>(predicates)...); } template <typename T> void operator()(const T &subject) const { this->detail::NodeConst<T>::pred_(subject); } void visit(const std::variant<Ts...> &subject) const { std::visit(*this, subject); } template <typename T, typename... Tothers> void set(detail::PredicateConst<T> &&first, detail::PredicateConst<Tothers> &&...preds) { this->detail::NodeConst<T>::pred_ = std::forward<detail::PredicateConst<T>>(first); this->template set<Tothers...>( std::forward<detail::PredicateConst<Tothers>>(preds)...); } template <typename T> void set(detail::PredicateConst<T> &&last) { this->detail::NodeConst<T>::pred_ = std::forward<detail::PredicateConst<T>>(last); } }; } // namespace EFG
2,489
C++
.h
65
34.538462
80
0.670823
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,946
SmartSet.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/SmartSet.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include "SmartPointerUtils.h" #include <unordered_set> namespace EFG { /** * @brief An unordered_set that stores shared pointers that can't be null. * * Elements are hashed by hashing the elements wrapped inside the shared * pointer. * * Elements are compared by comparing the elements wrapped inside the * shared pointer. */ template <typename T> using SmartSet = std::unordered_set<std::shared_ptr<T>, Hasher<T>, Comparator<T>>; template <typename T, typename Predicate> void for_each(const SmartSet<T> &subject, const Predicate &pred) { for (const auto &element : subject) { pred(*element); } } } // namespace EFG
767
C++
.h
29
24.413793
74
0.731241
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,947
SmartPointerUtils.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/SmartPointerUtils.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/Error.h> #include <memory> namespace EFG { template <typename T> struct Hasher { std::size_t operator()(const std::shared_ptr<T> &subject) const { if (nullptr == subject) { throw Error{"can't hash nullptr"}; } return std::hash<T>{}(*subject); } }; template <typename T> struct Comparator { bool operator()(const std::shared_ptr<T> &a, const std::shared_ptr<T> &b) const { return *a == *b; } }; } // namespace EFG
615
C++
.h
25
21.32
67
0.641638
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,948
Cast.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/Cast.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <type_traits> namespace EFG { template <typename DownCastT, typename T, typename Predicate> void castConstAndUse(const T &subject, const Predicate &predicate) { if (auto *ptr = dynamic_cast<const DownCastT *>(&subject); ptr) { predicate(*ptr); } } template <typename DownCastT, typename T, typename Predicate> void castAndUse(T &subject, const Predicate &predicate) { if (auto *ptr = dynamic_cast<DownCastT *>(&subject); ptr) { predicate(*ptr); } } } // namespace EFG
621
C++
.h
22
26.090909
68
0.719328
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,949
SmartMap.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/misc/SmartMap.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include "SmartPointerUtils.h" #include <unordered_map> namespace EFG { /** * @brief An unordered_map that stores as keys shared pointers that can't be * null. * * Keys are hashed by hashing the elements wrapped inside the shared * pointer. * * Keys are compared by comparing the elements wrapped inside the * shared pointer. */ template <typename K, typename V> using SmartMap = std::unordered_map<std::shared_ptr<K>, V, Hasher<K>, Comparator<K>>; template <typename K, typename V, typename Predicate> void for_each(SmartMap<K, V> &subject, const Predicate &pred) { for (auto it = subject.begin(); it != subject.end(); ++it) { pred(*it->first, it->second); } } template <typename K, typename V, typename Predicate> void for_each(const SmartMap<K, V> &subject, const Predicate &pred) { for (auto it = subject.begin(); it != subject.end(); ++it) { pred(*it->first, it->second); } } } // namespace EFG
1,059
C++
.h
36
27.305556
76
0.702065
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,950
ImageFinder.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/factor/ImageFinder.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/Function.h> namespace EFG::factor { /** * @brief An object used to search for the images associated to * sub combinations that are part of a bigger one. */ class ImageFinder { friend class Immutable; public: /** * @brief Searches for matches. For example assume having built this * object with a bigger_group equal to <A,B,C,D> while the variables * describing the distribution this finder refers to is equal to <B,D>. * When passing a comb equal to <0,1,2,0>, this object searches for the * immage associated to the sub combination <B,D> = <1,0>. * @param the combination of values referring to the bigger_group, which * contains the sub combination to search. * @return image associated to the passed combination */ float findTransformed(const std::vector<std::size_t> &comb) const { return function_->findTransformed(extractSmallerCombination(comb)); } float findImage(const std::vector<std::size_t> &comb) const { return function_->findImage(extractSmallerCombination(comb)); } private: ImageFinder(std::shared_ptr<const Function> function, const categoric::VariablesSoup &bigger_group); std::shared_ptr<const Function> function_; std::vector<std::size_t> indices_in_bigger_group; std::vector<std::size_t> extractSmallerCombination(const std::vector<std::size_t> &comb) const; }; } // namespace EFG::factor
1,550
C++
.h
41
34.682927
74
0.732179
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,951
Mutable.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/factor/Mutable.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/Function.h> namespace EFG::factor { class Mutable { public: Mutable(const Mutable &o) = delete; Mutable &operator=(const Mutable &) = delete; Mutable(Mutable &&o) = delete; Mutable &operator=(Mutable &&) = delete; /** * @brief sets the raw value of the image related to the passed combination. * In case the combination is currently not part of the distribution, it is * added to the combinations map, with the passed raw image value. * @param the combination whose raw image must be set * @param the raw image value to assume * @throw passing a negative number for value */ void set(const std::vector<std::size_t> &comb, float value); /** * @brief Removes all the combinations from the combinations map. */ void clear() { function_->clear(); }; /** * @brief Replaces the variables this distribution should refer to. */ void replaceVariables(const categoric::VariablesSoup &new_variables) { function_->vars().replaceVariables(new_variables); }; protected: Mutable(FunctionPtr data); auto &functionMutable() { return *function_; } private: FunctionPtr function_; }; } // namespace EFG::factor
1,323
C++
.h
41
29.341463
78
0.715632
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,952
Function.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/factor/Function.h
/** * Author: Andrea Casalino * Created: 31.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/categoric/GroupRange.h> #include <EasyFactorGraph/misc/Visitor.h> #include <unordered_map> #include <variant> namespace EFG::factor { class Function { public: Function(const categoric::Group &variables); virtual ~Function() = default; void cloneImages(const Function &o) { data_ = o.data_; } void set(const std::vector<std::size_t> &combination, float image); float findTransformed(const std::vector<std::size_t> &combination) const; float findImage(const std::vector<std::size_t> &combination) const; void clear() { data_ = makeSparseContainer(); } // Pred(const std::vector<std::size_t>&, float) template <bool UseTransformed, typename Pred> void forEachCombination(Pred &&pred) const { categoric::GroupRange range{info->sizes}; VisitorConst<SparseContainer, DenseContainer>{ [&](const SparseContainer &c) { categoric::for_each_combination( range, [&](const std::vector<std::size_t> &comb) { auto it = c.find(comb); float img = it == c.end() ? 0 : it->second; if constexpr (UseTransformed) { img = this->transform(img); } pred(comb, img); }); }, [&](const DenseContainer &c) { auto cIt = c.begin(); categoric::for_each_combination( range, [&](const std::vector<std::size_t> &comb) { float img = *cIt; if constexpr (UseTransformed) { img = this->transform(img); } pred(comb, img); ++cIt; }); }} .visit(data_); } // Pred(const std::vector<std::size_t>&, float) template <bool UseTransformed, typename Pred> void forEachNonNullCombination(Pred &&pred) const { VisitorConst<SparseContainer, DenseContainer>{ [&](const SparseContainer &c) { for (const auto &[comb, img] : c) { float img2 = img; if constexpr (UseTransformed) { img2 = this->transform(img2); } pred(comb, img2); } }, [&](const DenseContainer &c) { categoric::GroupRange range{info->sizes}; auto cIt = c.begin(); categoric::for_each_combination( range, [&](const std::vector<std::size_t> &comb) { if (*cIt != 0) { float img = *cIt; if constexpr (UseTransformed) { img = this->transform(img); } pred(comb, img); } ++cIt; }); }} .visit(data_); } struct Info { std::vector<std::size_t> sizes; std::size_t totCombinations; // something to dynamically pass from a sparse to a dense distribution when // the number of combinations increase enough std::size_t critical_size; }; const Info &getInfo() const { return *info; } const auto &vars() const { return variables_; } auto &vars() { return variables_; } struct CombinationHasher { std::shared_ptr<const Info> info; std::size_t operator()(const std::vector<std::size_t> &comb) const; }; protected: categoric::Group variables_; std::shared_ptr<const Info> info; /** * @brief applies a specific function to obtain the image from the passed rwa * value * @param the raw value to convert * @return the converted image */ virtual float transform(float input) const { return input; } using SparseContainer = std::unordered_map<std::vector<std::size_t>, float, CombinationHasher>; SparseContainer makeSparseContainer(); using DenseContainer = std::vector<float>; std::variant<SparseContainer, DenseContainer> data_; }; std::shared_ptr<const Function::Info> make_info(const categoric::Group &vars); using FunctionPtr = std::shared_ptr<Function>; } // namespace EFG::factor
4,110
C++
.h
114
28.096491
79
0.597582
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,953
Immutable.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/factor/Immutable.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/Function.h> #include <EasyFactorGraph/factor/ImageFinder.h> namespace EFG::factor { class ImageFinder; class Immutable { public: Immutable(const Immutable &o) = delete; Immutable &operator=(const Immutable &) = delete; Immutable(Immutable &&o) = delete; Immutable &operator=(Immutable &&) = delete; virtual ~Immutable() = default; const auto &function() const { return *function_; } ImageFinder makeFinder(const categoric::VariablesSoup &bigger_group) const; /** * @return the probabilities associated to each combination in the domain, * when assuming only the existance of this distribution. Such probabilities * are actually the normalized images. The order of returned values, refer to * the combinations that can be iterated by categoric::GroupRange on the * variables representing this distribution. */ std::vector<float> getProbabilities() const; protected: Immutable(FunctionPtr data); private: FunctionPtr function_; }; using ImmutablePtr = std::shared_ptr<Immutable>; } // namespace EFG::factor
1,213
C++
.h
35
32.057143
79
0.758355
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,954
Factor.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/factor/Factor.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/Immutable.h> #include <EasyFactorGraph/factor/Mutable.h> namespace EFG::factor { class Factor : public Immutable, public Mutable { public: Factor(const Factor &o); /** * @brief The variables set representing this factor is assumed equal to the * passed one. * No combinations is instanciated, implicitly assuming all the images equal * to 0. */ Factor(const categoric::Group &vars); struct CloneTrasformedImagesTag {}; /** * @brief The variables set representing this factor is copied from the passed * one. * All the combinations instanciated in the passed factor, are copied in the * combinations map of the factor to build, assigning the images values * obtained by evaluating the passed factor. */ Factor(const Immutable &to_clone, CloneTrasformedImagesTag); struct SimplyCorrelatedTag {}; /** * @brief A simply correlating factor is built. * All the variables in the passed group should have the same size. * The images pertaining to the combinations having all values equal, are * assumed equal to 1, all the others to 0. * For instance assume to pass a variable set equal to: {<A: size 3>, <B: size * 3>, <C: size 3>}. Then, the following combinations map is built: * <0,0,0> -> 1 * <0,0,1> -> 0 * <0,0,2> -> 0 * * <0,1,0> -> 0 * <0,1,1> -> 0 * <0,1,2> -> 0 * * <0,2,0> -> 0 * <0,2,1> -> 0 * <0,2,2> -> 0 * * <1,0,0> -> 0 * <1,0,1> -> 0 * <1,0,2> -> 0 * * <1,1,0> -> 0 * <1,1,1> -> 1 * <1,1,2> -> 0 * * <1,2,0> -> 0 * <1,2,1> -> 0 * <1,2,2> -> 0 * * <2,0,0> -> 0 * <2,0,1> -> 0 * <2,0,2> -> 0 * * <2,1,0> -> 0 * <2,1,1> -> 0 * <2,1,2> -> 0 * * <2,2,0> -> 0 * <2,2,1> -> 0 * <2,2,2> -> 1 */ Factor(const categoric::Group &vars, SimplyCorrelatedTag); struct SimplyAntiCorrelatedTag {}; /** * @brief Similar to Factor(const categoric::Group &, const * UseSimpleCorrelation &), but considering a simple anti-correlation. * Therefore, to all combinations having all equal values, an image equal to 0 * is assigned. All the other ones, are assigned a value equal to 1. * For instance assume to pass a variable set equal to: {<A: size 2>, <B: size * 2>}. Then, the following combinations map is built: * <0,0,0> -> 0 * <0,0,1> -> 1 * <0,0,2> -> 1 * * <0,1,0> -> 1 * <0,1,1> -> 1 * <0,1,2> -> 1 * * <0,2,0> -> 1 * <0,2,1> -> 1 * <0,2,2> -> 1 * * <1,0,0> -> 1 * <1,0,1> -> 1 * <1,0,2> -> 1 * * <1,1,0> -> 1 * <1,1,1> -> 0 * <1,1,2> -> 1 * * <1,2,0> -> 1 * <1,2,1> -> 1 * <1,2,2> -> 1 * * <2,0,0> -> 1 * <2,0,1> -> 1 * <2,0,2> -> 1 * * <2,1,0> -> 1 * <2,1,1> -> 1 * <2,1,2> -> 1 * * <2,2,0> -> 1 * <2,2,1> -> 1 * <2,2,2> -> 0 */ Factor(const categoric::Group &vars, SimplyAntiCorrelatedTag); /** * @brief Builds the factor by merging all the passed factors. * The variables set representing this factor is obtained as the union of the * all the variables sets of the passed distribution. */ template <typename... Immutables> static Factor merge(const Immutable &first, const Immutable &second, const Immutables &...others) { std::vector<const Immutable *> factors; factors.push_back(&first); factors.push_back(&second); (factors.push_back(&others), ...); return Factor{factors}; } Factor(const std::vector<const Immutable *> &factors); /** * @brief Generates a Factor similar to this one, permuting the group of * variables. * @param the new variables group order to assume * @return the permuted variables factor * @throw in case new_order.getVariablesSet() != * this->getVariables().getVariablesSet() */ Factor cloneWithPermutedGroup(const categoric::Group &new_order) const; protected: Factor(FunctionPtr data); }; } // namespace EFG::factor
4,110
C++
.h
147
24.129252
80
0.597419
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,955
FactorExponential.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/factor/FactorExponential.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/Factor.h> #include <EasyFactorGraph/factor/Immutable.h> #include <EasyFactorGraph/factor/Mutable.h> namespace EFG::factor { /** * @brief An exponential factor applies an exponential function to map the raw * values inside the combination map to the actual images. * More precisely, given the weight w characterizing the factor the image value * is obtained in this way: * image = exp(w * raw_value) * * All the combinations are instanciated in the combinations map when building * this object. */ class FactorExponential : public Immutable, protected Mutable { public: /** * @brief The same variables describing the passed factor are assumed for the * object to build. * The map of combinations is built by iterating all the possible ones of the * group of variables describing the passed factor. The raw values are * computed by evaluating the passed factor over each possible combination. * @param the baseline factor * @param the weight that will be considered by the exponential evaluator */ FactorExponential(const Factor &factor, float weigth); /** * @brief Same as FactorExponential(const Factor &, float), assuming * weigth = 1. */ FactorExponential(const Factor &factor); FactorExponential(const FactorExponential &o); /** * @brief sets the weight used by the exponential evaluator. */ void setWeight(float w); /** * @return the weight used by the exponential evaluator. */ float getWeight() const; using Mutable::replaceVariables; protected: FactorExponential(FunctionPtr data); }; } // namespace EFG::factor
1,762
C++
.h
52
31.153846
79
0.750735
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,956
TrainSetImport.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/io/TrainSetImport.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/trainable/TrainSet.h> #include <string> namespace EFG::io { /** * @brief Imports the training set from a file. * The file should be a matrix of raw values. * Each row represent a combination, i.e. a element of the training set to * import. * @throw in case the passed file is inexistent * @throw in case not all the combinations in file have the same size. */ train::TrainSet import_train_set(const std::string &file_name); } // namespace EFG::io
608
C++
.h
20
28.6
74
0.731164
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,957
ModelComponents.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/io/ModelComponents.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/structure/FactorsConstManager.h> #include <EasyFactorGraph/trainable/FactorsTunableManager.h> #include <utility> namespace EFG::io { using Getters = std::tuple<const strct::StateAware *, const strct::FactorsConstGetter *, const train::FactorsTunableGetter *>; template <typename ModelT> Getters castToGetters(ModelT &model) { auto components = std::make_tuple( dynamic_cast<const strct::StateAware *>(&model), dynamic_cast<const strct::FactorsConstGetter *>(&model), dynamic_cast<const train::FactorsTunableGetter *>(&model)); if (nullptr == std::get<0>(components)) { throw Error{"A model should be at least StateAware"}; } if (nullptr == std::get<1>(components)) { throw Error{"A model should be at least FactorsConstGetter"}; } return components; } using Inserters = std::pair<strct::FactorsConstInserter *, train::FactorsTunableInserter *>; template <typename Model> Inserters castToInserters(Model &model) { auto components = std::make_pair(dynamic_cast<strct::FactorsConstInserter *>(&model), dynamic_cast<train::FactorsTunableInserter *>(&model)); if (nullptr == std::get<0>(components)) { throw Error{"A model should be at least FactorsConstInserter"}; } return components; } } // namespace EFG::io
1,499
C++
.h
40
33.675
78
0.71832
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,958
Importer.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/io/xml/Importer.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_XML_IO #pragma once #include <EasyFactorGraph/io/ModelComponents.h> #include <EasyFactorGraph/misc/Cast.h> #include <EasyFactorGraph/structure/EvidenceManager.h> #include <filesystem> namespace EFG::io::xml { class Importer { public: /** * @brief parse the model (variables and factors) described by the specified * file and tries to add its factors to the passed model. * @param recipient of the model parsed from file * @param location of the model to parse and add to the passed one */ template <typename Model> static void importFromFile(Model &model, const std::filesystem::path &file_path) { auto evidences = convert(castToInserters(model), file_path); castAndUse<strct::EvidenceSetter>( model, [&evidences](strct::EvidenceSetter &as_setter) { for (const auto &[var, val] : evidences) { as_setter.setEvidence(as_setter.findVariable(var), val); } }); } private: static std::unordered_map<std::string, std::size_t> convert(Inserters recipient, const std::filesystem::path &file_path); }; } // namespace EFG::io::xml #endif
1,267
C++
.h
38
29.105263
78
0.695012
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,959
Exporter.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/io/xml/Exporter.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_XML_IO #pragma once #include <EasyFactorGraph/io/ModelComponents.h> #include <filesystem> #include <ostream> namespace EFG::io::xml { struct ExportInfo { std::string file_path; std::string model_name = "Model"; }; class Exporter { public: /** * @brief exports the model (variables and factors) into a string, * describing an xml. * @param the model to export * @param the model name to report in the xml */ template <typename Model> static std::string exportToString(const Model &model, const std::string &model_name) { std::ostringstream stream; convert(stream, castToGetters(model), model_name); return stream.str(); } /** * @brief exports the model (variables and factors) into an xml file * @param the model to export * @param info describing the xml to generate. */ template <typename Model> static void exportToFile(const Model &model, const ExportInfo &info) { convert(info.file_path, castToGetters(model), info.model_name); } private: static void convert(const std::filesystem::path &out, Getters subject, const std::string &model_name); static void convert(std::ostream &out, Getters subject, const std::string &model_name); }; } // namespace EFG::io::xml #endif
1,450
C++
.h
48
25.854167
72
0.680546
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,960
Importer.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/io/json/Importer.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_JSON_IO #pragma once #include <EasyFactorGraph/io/ModelComponents.h> #include <EasyFactorGraph/misc/Cast.h> #include <EasyFactorGraph/structure/EvidenceManager.h> #include <nlohmann/json.hpp> #include <filesystem> namespace EFG::io::json { class Importer { public: /** * @brief imports the structure (variables and factors) described in an xml file and add it to the passed model * @param the model receiving the parsed data * @param the path storing the xml to import */ template <typename Model> static void importFromFile(Model &model, const std::filesystem::path &file_path) { auto asJson = importJsonFromFile(file_path); importFromJson(model, asJson); } /** * @brief parse the model (variables and factors) described by the passed * json and tries to add its factors to the passed model. * @param recipient of the model parsed from file * @param json describing the model to parse and add to the passed one */ template <typename Model> static void importFromJson(Model &model, const nlohmann::json &source) { auto evidences = convert(castToInserters(model), source); set_evidences(model, evidences); } private: static std::unordered_map<std::string, std::size_t> convert(Inserters recipient, const nlohmann::json &source); static nlohmann::json importJsonFromFile(const std::filesystem::path &file_path); template <typename Model> static void set_evidences(Model &model, const std::unordered_map<std::string, std::size_t> &ev) { castAndUse<strct::EvidenceSetter>( model, [&ev](strct::EvidenceSetter &as_setter) { for (const auto &[var, val] : ev) { as_setter.setEvidence(as_setter.findVariable(var), val); } }); } }; } // namespace EFG::io::json #endif
1,965
C++
.h
58
29.603448
75
0.701634
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,961
Exporter.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/io/json/Exporter.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #ifdef EFG_JSON_IO #pragma once #include <EasyFactorGraph/io/ModelComponents.h> #include <nlohmann/json.hpp> #include <filesystem> namespace EFG::io::json { class Exporter { public: /** * @brief exports the model (variables and factors) into a json. * @param the model to export */ template <typename Model> static nlohmann::json exportToJson(const Model &model) { nlohmann::json result; convert(result, castToGetters(model)); return result; } /** * @brief exports the model (variables and factors) into an json file * @param the model to export * @param the file to generate storing the exported json */ template <typename Model> static void exportToFile(const Model &model, const std::filesystem::path &file_path) { auto as_json = exportToJson(model); exportToFile(as_json, file_path); } private: static void convert(nlohmann::json &recipient, Getters subject); static void exportToFile(const nlohmann::json &source, const std::filesystem::path &out); }; } // namespace EFG::io::json #endif
1,228
C++
.h
42
25.166667
71
0.692438
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,962
Group.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/categoric/Group.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/categoric/Variable.h> #include <EasyFactorGraph/misc/SmartSet.h> #include <vector> namespace EFG::categoric { using VariablesSoup = std::vector<VariablePtr>; using VariablesSet = SmartSet<Variable>; VariablesSet to_vars_set(const VariablesSoup &soup); /** * @brief An ensemble of categoric variables. Each variable in the ensemble * should have its own unique name. */ class Group { public: /** * @param the initial variables of the group * @throw when passing an empty collection * @throw when passing a collection containing multiple times a certain * variable */ Group(const VariablesSoup &group); /** * @param the initial variable to put in the group */ Group(const VariablePtr &var); /** * @param the first initial variable to put in the group * @param the second initial variable to put in the group * @param all the other initial variables * @throw when passing a collection containing multiple times a certain */ template <typename... Vars> Group(const VariablePtr &varA, const VariablePtr &varB, const Vars &...vars) { this->add(varA); this->add(varB); (this->add(vars), ...); } /** * @brief replaces the group of variables. * @throw In case of size mismatch with the previous variables set: * the sizes of the 2 groups should be the same and the elements in * the same positions must have the same domain size */ void replaceVariables(const VariablesSoup &new_variables); bool operator==(const Group &o) const { return (this->group_sorted == o.group_sorted); }; /** * @param the variable to add in the group * @throw in case a variable with the same name is already part of the group */ void add(const VariablePtr &var); /** @return the size of the joint domain of the group. * For example the group <A,B,C> with sizes <2,4,3> will have a joint domain * of size 2x4x3 = 24 */ std::size_t size() const; /** @return the ensamble of variables as an unsorted collection */ const VariablesSoup &getVariables() const { return this->group; } /** @return the ensamble of variables as a sorted collection */ const VariablesSet &getVariablesSet() const { return this->group_sorted; } protected: Group() = default; VariablesSoup group; VariablesSet group_sorted; }; /** @brief removes the second set from the first */ VariablesSet &operator-=(VariablesSet &subject, const VariablesSet &to_remove); /** @return the complementary group of the entire_set, * i.e. returns entire_set \ subset */ VariablesSet get_complementary(const VariablesSet &entire_set, const VariablesSet &subset); } // namespace EFG::categoric
2,854
C++
.h
83
31.012048
80
0.714857
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,963
Variable.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/categoric/Variable.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <memory> #include <string> namespace EFG::categoric { /** * @brief An object representing an immutable categoric variable. */ class Variable { public: /** * @param domain size of this variable * @param name used to label this varaible. * @throw passing 0 as size * @throw passing an empty string as name */ Variable(std::size_t size, const std::string &name); std::size_t size() const { return this->size_; }; const std::string &name() const { return this->name_; }; bool operator==(const Variable &o) const { return (this->name_ == o.name_) && (this->size_ == o.size_); } protected: const size_t size_; const std::string name_; }; using VariablePtr = std::shared_ptr<Variable>; VariablePtr make_variable(std::size_t size, const std::string &name); } // namespace EFG::categoric namespace std { template <> struct hash<EFG::categoric::Variable> { std::size_t operator()(const EFG::categoric::Variable &subject) const { return std::hash<std::string>{}(subject.name()); } }; } // namespace std
1,179
C++
.h
41
26.317073
73
0.687334
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,964
GroupRange.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/categoric/GroupRange.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/categoric/Group.h> #include <optional> namespace EFG::categoric { /** * @brief This object allows to iterate all the elements in the joint domain * of a group of variables, without precomputing all the elements in such * domain. For example when having a domain made by variables = { A (size = 2), * B (size = 3), C (size = 2) }, the elements in the joint domain that will be * iterated are: * <0,0,0> * <0,0,1> * <0,1,0> * <0,1,1> * <0,2,0> * <0,2,1> * <1,0,0> * <1,0,1> * <1,1,0> * <1,1,1> * <1,2,0> * <1,2,1> * After construction, the Range object starts to point to the first element in * the joint domain <0,0,...>. Then, when incrementing the object, the following * element is pointed. When calling get() the current pointed element can be * accessed. * * This object should be recognized by the compiler as an stl iterator. */ class GroupRange { public: // https://www.internalpointers.com/post/writing-custom-iterators-modern-cpp using iterator_category = std::input_iterator_tag; // using difference_type = std::ptrdiff_t; using value_type = std::vector<std::size_t>; using pointer = const std::vector<std::size_t> *; using reference = const std::vector<std::size_t> &; GroupRange(const std::vector<std::size_t> &sizes); /** @param the group of variables whose joint domain must be iterated */ GroupRange(const Group &variables); GroupRange(const GroupRange &o); pointer operator->() const { return &data->combination; } reference operator*() const { return data->combination; } /** * @brief Make the object to point to the next element in the joint domain. * @throw if the current pointed element is the last one. */ GroupRange &operator++(); static GroupRange end() { return GroupRange{}; }; bool isEqual(const GroupRange &o) const { return this->data == o.data; }; private: GroupRange() = default; struct Data { Data(const std::vector<size_t> &s, bool eor); const std::vector<size_t> sizes; std::vector<std::size_t> combination; bool end_of_range; bool operator==(const Data &o) const { return (end_of_range == o.end_of_range) && (combination == o.combination); } }; std::optional<Data> data; }; static const GroupRange RANGE_END = GroupRange::end(); bool operator==(const GroupRange &a, const GroupRange &b); bool operator!=(const GroupRange &a, const GroupRange &b); /** * @brief Applies the passed predicate to all the elements that can be ranged * using the passed range. */ template <typename Predicate> void for_each_combination(GroupRange &range, const Predicate &predicate) { for (; range != RANGE_END; ++range) { predicate(*range); } } } // namespace EFG::categoric
2,875
C++
.h
84
31.559524
80
0.695276
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,965
FactorsConstManager.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/FactorsConstManager.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/FactorsAware.h> namespace EFG::strct { class FactorsConstGetter : virtual public FactorsAware { public: /** * @return the collection of const factors that are part of the model. Tunable * factors are not accounted in this collection. */ const auto &getConstFactors() const { return const_factors; } protected: std::unordered_set<factor::ImmutablePtr> const_factors; }; class FactorsConstInserter : virtual public FactorsConstGetter { public: /** * @brief add a shallow copy of the passed const factor to this model */ void addConstFactor(const factor::ImmutablePtr &factor); /** * @brief add a deep copy of the passed const factor to this model */ void copyConstFactor(const factor::Immutable &factor); /** * @brief adds a collection of const factors ot this model. * Passing copy = true, deep copies are created and inserted in this model. * Passing copy = false, shallow copies are created and inserted in this * model. */ template <typename DistributionIt> void absorbConstFactors(const DistributionIt &begin, const DistributionIt &end, bool copy) { for (auto it = begin; it != end; ++it) { try { if (copy) { copyConstFactor(**it); } else { addConstFactor(*it); } } catch (...) { } } } }; } // namespace EFG::strct
1,544
C++
.h
51
26.039216
80
0.681237
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,966
GibbsSampler.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/GibbsSampler.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/BeliefAware.h> #include <EasyFactorGraph/structure/bases/PoolAware.h> #include <optional> #include <random> namespace EFG::strct { class UniformSampler { public: UniformSampler(); std::size_t sampleFromDiscrete(const std::vector<float> &distribution) const; void resetSeed(std::size_t newSeed); private: float sample() const { return this->distribution(this->generator); }; mutable std::default_random_engine generator; mutable std::uniform_real_distribution<float> distribution; }; /** * @brief Refer also to https://en.wikipedia.org/wiki/Gibbs_sampling */ class GibbsSampler : virtual public StateAware, virtual public BeliefAware, virtual public PoolAware { public: struct SamplesGenerationContext { std::size_t samples_number; /** * @brief number of iterations used to evolve the model between the drawing * of one sample and another */ std::optional<std::size_t> delta_iterations; /** * @brief sets the seed of the random engine. * Passing a nullopt will make the sampler to generate a random seed by * using the current time. */ std::optional<std::size_t> seed; /** * @brief number of samples to discard before actually starting the sampling * procedure. * * When nothing is specified, 10 times delta_iterations is assumed. */ std::optional<std::size_t> transient; }; /** * @brief Use Gibbs sampling approach to draw empirical samples. Values inside * the returned combiantion are ordered with the same order used for the * variables returned by getAllVariables(). * * In case some evidences are set, their values will appear as is in the * sampled combinations. * * @param number parameters for the samples generation * @param number of threads to use for the samples generation */ std::vector<std::vector<std::size_t>> makeSamples(const SamplesGenerationContext &context, std::size_t threads = 1); struct SamplerNode { std::size_t *value_in_combination; const factor::UnaryFactor *static_dependencies; struct DynamicDependency { categoric::VariablePtr sender; const std::size_t *sender_value_in_combination; factor::ImmutablePtr factor; }; std::vector<DynamicDependency> dynamic_dependencies; bool noChangingDeps( const std::unordered_set<const std::size_t *> &will_change) const; }; private: std::vector<SamplerNode> makeSamplerNodes(std::vector<std::size_t> &combination_buffer) const; }; } // namespace EFG::strct
2,746
C++
.h
80
30.075
80
0.715417
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,967
SpecialFactors.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/SpecialFactors.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/factor/Factor.h> #include <type_traits> namespace EFG::factor { // The special factors defined here, are used internally to propagate the belief // in the most optimized possible way. class UnaryFactor : public Factor { public: const categoric::VariablePtr &getVariable() const { return variable; } float diff(const UnaryFactor &o) const; protected: UnaryFactor(FunctionPtr data); categoric::VariablePtr variable; }; class MergedUnaries : public UnaryFactor { public: // all ones are assumed MergedUnaries(const categoric::VariablePtr &var); MergedUnaries(const std::vector<const Immutable *> &factors); void merge(const Immutable &to_merge); // mostly for performance purpose void normalize(); }; class Evidence : public UnaryFactor { public: Evidence(const Immutable &binary_factor, const categoric::VariablePtr &evidence_var, std::size_t evidence); }; class Indicator : public UnaryFactor { public: Indicator(const categoric::VariablePtr &var, std::size_t value); }; class MessageSUM : public UnaryFactor { public: MessageSUM(const UnaryFactor &merged_unaries, const Immutable &binary_factor); }; class MessageMAP : public UnaryFactor { public: MessageMAP(const UnaryFactor &merged_unaries, const Immutable &binary_factor); }; } // namespace EFG::factor namespace EFG::strct { template <typename MessageT> std::unique_ptr<MessageT> make_message(const factor::UnaryFactor &merged_unaries, const factor::Immutable &binary_factor) { static_assert(std::is_same<MessageT, factor::MessageMAP>::value || std::is_same<MessageT, factor::MessageSUM>::value, "not a valid Message type"); return std::make_unique<MessageT>(merged_unaries, binary_factor); } } // namespace EFG::strct
1,934
C++
.h
58
30.362069
80
0.748654
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,968
Types.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/Types.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/misc/Cache.h> #include <EasyFactorGraph/misc/SmartMap.h> #include <EasyFactorGraph/structure/SpecialFactors.h> #include <list> #include <optional> #include <unordered_map> #include <unordered_set> #include <variant> namespace EFG::strct { struct Node { categoric::VariablePtr variable; struct Connection { factor::ImmutablePtr factor; // incoming message // nullptr when the message is not already available std::unique_ptr<const factor::UnaryFactor> message; }; std::unordered_map<Node *, Connection> active_connections; // in this casethe incoming message represents the marginalized evidence std::unordered_map<Node *, Connection> disabled_connections; std::vector<factor::ImmutablePtr> unary_factors; Cache<const factor::UnaryFactor> merged_unaries; // merged factor containing all the unary factors and the // marginalized evidences void updateMergedUnaries(); static std::pair<Connection *, Connection *> activate(Node &a, Node &b, factor::ImmutablePtr factor); static std::pair<Connection *, Connection *> disable(Node &a, Node &b, factor::ImmutablePtr factor = nullptr); }; using Nodes = SmartMap<categoric::Variable, std::unique_ptr<Node>>; enum class PropagationKind { SUM, MAP }; /** * @brief Clusters of hidden node. Each cluster is a group of * connected hidden nodes. * Nodes in different clusters are not currently connected, due to * the model structure or the kind of evidences currently applied. */ struct HiddenCluster { std::unordered_set<Node *> nodes; struct TopologyInfo { Node *sender; Node::Connection *connection; std::vector<const Node::Connection *> dependencies; bool canUpdateMessage() const; // throw when the computation is not possible // MAX_VARIATION that the message was computed and before was nullopt // any other number is the delta w.r.t, the previous message std::optional<float> updateMessage(PropagationKind kind); }; Cache<std::vector<TopologyInfo>> connectivity; void updateConnectivity(); }; using HiddenClusters = std::list<HiddenCluster>; HiddenClusters compute_clusters(const std::unordered_set<Node *> &nodes); using Evidences = SmartMap<categoric::Variable, std::size_t>; struct PropagationContext { /** * @brief maximum number of iterations to use when trying to calibrate a loopy * graph */ std::size_t max_iterations_loopy_propagation; }; /** * @brief a structure that can be exposed after having propagated the belief, * providing info on the encountered structure. */ struct PropagationResult { PropagationKind propagation_kind_done; bool was_completed; struct ClusterInfo { bool tree_or_loopy_graph; /** * @brief number of nodes that constitutes the sub-graph cluster. */ std::size_t size; }; std::vector<ClusterInfo> structures; }; } // namespace EFG::strct
3,037
C++
.h
87
31.885057
80
0.749316
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,969
QueryManager.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/QueryManager.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/BeliefAware.h> #include <EasyFactorGraph/structure/bases/PoolAware.h> #include <algorithm> namespace EFG::strct { class QueryManager : virtual public StateAware, virtual public BeliefAware, virtual public PoolAware { public: /** * @return the marginal probabilty of the passed variable, i.e. * P(var|observations), conditioned to the last set of evidences. * @param the involved variable * @param the number of threads to use for propagating the belief before * returning the result. * @throw when the passed variable name is not found */ std::vector<float> getMarginalDistribution(const categoric::VariablePtr &var, std::size_t threads = 1) { return marginalQuery_<PropagationKind::SUM>(var, threads); } /** * @brief same as getMarginalDistribution(const categoric::VariablePtr &, * std::size_t), but passing the name of the variable, which is * internally searched. */ std::vector<float> getMarginalDistribution(const std::string &var, std::size_t threads = 1); /** * @return a factor representing the joint distribution of the subgraph * described by the passed set of variables. * @param the involved variables * @param the number of threads to use for propagating the belief before * returning the result. * @throw when some of the passed variable names are not found */ factor::Factor getJointMarginalDistribution(const categoric::Group &subgroup, std::size_t threads = 1); /** * @brief same as getJointMarginalDistribution(const categoric::VariablesSet * &, std::size_t), but passing the names of the variables, which are * internally searched. * * @throw in case the passed set of variables is not representative of a valid * group */ factor::Factor getJointMarginalDistribution(const std::vector<std::string> &subgroup, std::size_t threads = 1); /** * @return the Maximum a Posteriori estimation of a specific variable in * the model, conditioned to the last set of evidences. * @param the involved variable * @param the number of threads to use for propagating the belief before * returning the result. * @throw when the passed variable name is not found */ std::size_t getMAP(const categoric::VariablePtr &var, std::size_t threads = 1); /** * @brief same as getMAP(const categoric::VariablePtr &, * std::size_t), but passing the name of the variable, which is * internally searched. */ std::size_t getMAP(const std::string &var, std::size_t threads = 1); /** * @return the Maximum a Posteriori estimation of the hidden variables, * conditioned to the last set of evidences. Values are ordered with the same * order used by the set of variables returned in getHiddenVariables() * @param the number of threads to use for propagating the belief before * returning the result. */ std::vector<size_t> getHiddenSetMAP(std::size_t threads = 1); private: static void throwInexistentVar(const std::string &var); std::vector<float> getMarginalDistribution(const NodeLocation &location); template <PropagationKind Kind> void checkPropagation_(std::size_t threads) { if (wouldNeedPropagation(Kind)) { ScopedPoolActivator activator(*this, threads); propagateBelief(Kind); } } template <PropagationKind Kind> std::vector<float> marginalQuery_(const categoric::VariablePtr &var, std::size_t threads) { checkPropagation_<Kind>(threads); auto location = locate(var); if (!location) { throwInexistentVar(var->name()); } return getMarginalDistribution(*location); } }; } // namespace EFG::strct
4,042
C++
.h
101
34.128713
80
0.687038
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,970
BaselineLoopyPropagator.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/BaselineLoopyPropagator.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/BeliefAware.h> namespace EFG::strct { class BaselineLoopyPropagator : public LoopyBeliefPropagationStrategy { public: bool propagateBelief(HiddenCluster &subject, PropagationKind kind, const PropagationContext &context, Pool &pool) final; }; } // namespace EFG::strct
462
C++
.h
15
27.6
76
0.745495
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,971
EvidenceManager.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/EvidenceManager.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/BeliefAware.h> #include <EasyFactorGraph/structure/bases/StateAware.h> namespace EFG::strct { class EvidenceSetter : virtual public StateAware, virtual public BeliefAware { public: /** * @brief update the evidence set with the specified new evidence. * In case the involved variable was already part of the evidence set, the * evidence value is simply updated. * On the contrary case, the involved variable is moved into the evidence set, * with the specified value. * @param the involved variable * @param the evidence value * @throw in case the passed variable is not part of the model. */ void setEvidence(const categoric::VariablePtr &variable, std::size_t value); /** * @brief Similar to setEvidence(const categoric::VariablePtr &, const * std::size_t) , but passing the variable name, which is interally searched. */ void setEvidence(const std::string &variable, std::size_t value); }; class EvidenceRemover : virtual public StateAware, virtual public BeliefAware { public: /** * @brief update the evidence set by removing the specified variable. * @param the involved variable * @throw in case the passed variable is not part of the model. * @throw in case the passed variable is not part of the current evidence set. */ void removeEvidence(const categoric::VariablePtr &variable); /** * @brief similar to removeEvidence(const categoric::VariablePtr &), but * passing the variable name, which is internally searched. */ void removeEvidence(const std::string &variable); /** * @brief update the evidence set by removing all the specified variables. * @param the involved variables * @throw in case one of the passed variable is not part of the model. * @throw in case one of the passed variable is not part of the current * evidence set. */ void removeEvidences(const categoric::VariablesSet &variables); /** * @brief similar to removeEvidences(const categoric::VariablesSet &), but * passing the variable names, which are internally searched. */ void removeEvidences(const std::unordered_set<std::string> &variables); /** * @brief removes all the evidences currently set for this model. */ void removeAllEvidences(); private: void removeEvidence_(const categoric::VariablePtr &variable); void resetState(); }; } // namespace EFG::strct
2,544
C++
.h
65
35.984615
80
0.741596
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,972
FactorsAware.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/bases/FactorsAware.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/BeliefAware.h> #include <EasyFactorGraph/structure/bases/StateAware.h> namespace EFG::strct { class FactorsAware : virtual public StateAware, virtual public BeliefAware { public: /** * @return all the factors in the model, tunable and constant. */ const auto &getAllFactors() const { return this->factorsAll; }; protected: void addDistribution(const EFG::factor::ImmutablePtr &distribution); private: NodeLocation findOrMakeNode(const categoric::VariablePtr &var); void addUnaryDistribution(const EFG::factor::ImmutablePtr &unary_factor); void addBinaryDistribution(const EFG::factor::ImmutablePtr &binary_factor); /** * @brief a register storing ALL the factors in the model, no matter the kind (exponential, const, non const) */ std::unordered_set<factor::ImmutablePtr> factorsAll; }; } // namespace EFG::strct
1,018
C++
.h
29
32.586207
77
0.762487
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,973
StateAware.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/bases/StateAware.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/SpecialFactors.h> #include <EasyFactorGraph/structure/Types.h> namespace EFG::strct { class StateAware { public: virtual ~StateAware() = default; /** * @return all the variables that are part of the model. */ const auto &getAllVariables() const { return state_.variables; } /** * @return all the variables defining the hidden set of variables */ categoric::VariablesSet getHiddenVariables() const; /** * @return all the variables defining the evidence set */ categoric::VariablesSet getObservedVariables() const; /** * @return all the variables defining the evidence set, together with the * associated values */ const auto &getEvidences() const { return state_.evidences; }; /** * @return the variable in the model with the passed name * @throw in case no variable with the specified name exists in this model */ categoric::VariablePtr findVariable(const std::string &name) const; StateAware(const StateAware &) = delete; StateAware &operator=(const StateAware &) = delete; StateAware(StateAware &&) = delete; StateAware &operator=(StateAware &&) = delete; protected: struct NodeLocation { Node *node; std::variant<HiddenClusters::iterator, Evidences::iterator> location; }; struct GraphState { categoric::VariablesSoup variables; Nodes nodes; HiddenClusters clusters; Evidences evidences; }; StateAware() = default; const GraphState &state() const { return state_; } GraphState &stateMutable() { return state_; } std::optional<NodeLocation> locate(const categoric::VariablePtr &var) const; std::optional<NodeLocation> locate(const std::string &var_name) const { return locate(findVariable(var_name)); } private: mutable GraphState state_; }; } // namespace EFG::strct
1,961
C++
.h
61
28.918033
78
0.729443
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,974
BeliefAware.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/bases/BeliefAware.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/PoolAware.h> #include <EasyFactorGraph/structure/bases/StateAware.h> #include <optional> namespace EFG::strct { class LoopyBeliefPropagationStrategy { public: virtual ~LoopyBeliefPropagationStrategy() = default; virtual bool propagateBelief(HiddenCluster &subject, PropagationKind kind, const PropagationContext &context, Pool &pool) = 0; }; using LoopyBeliefPropagationStrategyPtr = std::unique_ptr<LoopyBeliefPropagationStrategy>; /** * @brief The propagation relies on a concrete implementation of a * BeliePropagationStrategy. In case no other is specified, a default one, * BaselineBeliefPropagator, is instantiated and used internally. You can * override this default propagator using setPropagationStrategy(...). */ class BeliefAware : virtual public StateAware, virtual public PoolAware { public: virtual ~BeliefAware() = default; const PropagationContext &getPropagationContext() const { return context; } void setPropagationContext(const PropagationContext &ctxt) { context = ctxt; } bool hasPropagationResult() const { return lastPropagation.has_value(); } const PropagationResult &getLastPropagationResult() const { return *this->lastPropagation; }; void setLoopyPropagationStrategy(LoopyBeliefPropagationStrategyPtr strategy); protected: BeliefAware(); void resetBelief() { lastPropagation.reset(); } bool wouldNeedPropagation(PropagationKind kind) const; void propagateBelief(PropagationKind kind); private: PropagationContext context = PropagationContext{1000}; /** * @brief results about the last belief propagation done. It is a nullopt until the first propagation is triggered */ std::optional<PropagationResult> lastPropagation; LoopyBeliefPropagationStrategyPtr loopy_propagator; }; } // namespace EFG::strct
2,028
C++
.h
51
36.058824
80
0.77421
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,975
PoolAware.h
andreacasalino_Easy-Factor-Graph/src/header/EasyFactorGraph/structure/bases/PoolAware.h
/** * Author: Andrea Casalino * Created: 28.03.2022 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <atomic> #include <functional> #include <mutex> #include <optional> #include <thread> #include <vector> namespace EFG::strct { using Task = std::function<void(const std::size_t)>; // the processing thread id // is passed using Tasks = std::vector<Task>; class Pool { public: Pool(std::size_t size); ~Pool(); void parallelFor(const Tasks &tasks); std::size_t size() const { return ctxt.pool_size; } private: struct Context { std::size_t pool_size; std::atomic_bool life = true; }; Context ctxt; std::mutex parallelForMtx; struct Worker { Worker(std::size_t th_id, Context &context); std::thread loop; std::atomic<const Tasks *> to_process = nullptr; }; using WorkerPtr = std::unique_ptr<Worker>; std::vector<WorkerPtr> workers; }; class PoolAware { public: virtual ~PoolAware(); protected: PoolAware(); void resetPool(); Pool &getPool() { return pool.value(); } void setPoolSize(std::size_t new_size); class ScopedPoolActivator { public: ScopedPoolActivator(PoolAware &subject, std::size_t new_size) : subject(subject) { subject.setPoolSize(new_size); } ~ScopedPoolActivator() { subject.resetPool(); } private: PoolAware &subject; }; private: std::optional<Pool> pool; }; } // namespace EFG::strct
1,495
C++
.h
60
21.083333
80
0.669725
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,976
HiddenObservedTuner.h
andreacasalino_Easy-Factor-Graph/src/src/model/HiddenObservedTuner.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/structure/bases/StateAware.h> #include <EasyFactorGraph/trainable/tuners/BaseTuner.h> namespace EFG::train { class HiddenObservedTuner : public BaseTuner { public: HiddenObservedTuner( strct::Node &nodeHidden, const strct::Evidences::const_iterator &evidence, const std::shared_ptr<factor::FactorExponential> &factor, const categoric::VariablesSoup &variables_in_model); float getGradientBeta() final; private: strct::Node &nodeHidden; strct::Evidences::const_iterator evidence; std::size_t pos_in_factor_hidden; std::size_t pos_in_factor_evidence; }; } // namespace EFG::train
764
C++
.h
24
29.125
80
0.757493
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,531,977
Utils.h
andreacasalino_Easy-Factor-Graph/src/src/io/Utils.h
/** * Author: Andrea Casalino * Created: 01.01.2021 * * report any bug to andrecasa91@gmail.com. **/ #pragma once #include <EasyFactorGraph/Error.h> #include <EasyFactorGraph/io/ModelComponents.h> #include <EasyFactorGraph/trainable/TrainSet.h> #include <filesystem> #include <fstream> #include <utility> namespace EFG::io { namespace detail { template <typename T> void check_stream(const T &stream, const std::filesystem::path &file_name) { if (!stream.is_open()) { throw Error::make(file_name, " is a non valid file path"); } } } // namespace detail template <typename Pred> void useInStrem(const std::filesystem::path &file_name, Pred &&pred) { std::ifstream stream{file_name}; detail::check_stream(stream, file_name); pred(stream); } template <typename Pred> void useOutStrem(const std::filesystem::path &file_name, Pred &&pred) { std::ofstream stream{file_name}; detail::check_stream(stream, file_name); pred(stream); } template <typename Predicate> void for_each_line(std::istream &stream, const Predicate &pred) { std::string line; while (!stream.eof()) { line.clear(); std::getline(stream, line); pred(line); } } std::pair<std::vector<std::size_t>, float> parse_combination_image(const std::string &line); /** * @brief Fill the passed factor with the combinations found in the passed file. * The file should be a matrix of raw values. * Each row represent a combination and a raw image (as last element) to add to * the combination map of the passed distribution. * @throw in case the passed file is inexistent * @throw in case the parsed combination is inconsitent for the passed * distribution */ void import_values(factor::Factor &recipient, const std::filesystem::path &file_name); /** * @brief Imports the training set from a file. * The file should be a matrix of raw values. * Each row represent a combination, i.e. a element of the training set to * import. * @throw in case the passed file is inexistent * @throw in case not all the combinations in file have the same size. */ train::TrainSet import_train_set(const std::string &file_name); struct ImportHelper { ImportHelper(Inserters m) : model(m) {} Inserters model; struct TunableCluster { train::FactorExponentialPtr factor; categoric::VariablesSet group_owning_w_to_share; }; std::vector<TunableCluster> cumulated; void importCumulatedTunable() const; void importConst(const factor::ImmutablePtr &factor); void importTunable(const train::FactorExponentialPtr &factor, const std::optional<categoric::VariablesSet> &sharing_group = std::nullopt); }; } // namespace EFG::io
2,712
C++
.h
80
30.875
80
0.728315
andreacasalino/Easy-Factor-Graph
32
4
1
GPL-3.0
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false