keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/SetHash.hpp
.hpp
807
27
#ifndef _SETHASH_HPP #define _SETHASH_HPP #include <functional> #include <set> #include <unordered_set> template <typename T> struct SetHash { // Mutlplying by a large prime should broadcast to higher bits (and // since it's prime, taking % 2^64 should be distributed fairly // uniformly). Also XOR with single element hash because product // with large prime may not use lower-significance bits effectively. std::size_t operator() (const std::unordered_set<T> & s) const { std::hash<T> single_hash; std::size_t combined_hash_value = 0; for (const T & obj : s) { unsigned long single = single_hash(obj); combined_hash_value += 2147483647ul*single ^ single; } combined_hash_value += 2147483647ul*s.size() ^ s.size(); return combined_hash_value; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/Scheduler.hpp
.hpp
2,113
69
#ifndef _SCHEDULER_HPP #define _SCHEDULER_HPP #include "Edge.hpp" #include "MessagePasser.hpp" #include "InferenceGraph.hpp" template <typename VARIABLE_KEY> class Scheduler { protected: // dampening_lambda = 0.0 uses only _current_message; with 1.0, it // only uses _old_message. double _dampening_lambda; double _convergence_threshold; unsigned long _maximum_iterations; public: Scheduler(double dampening_lambda_param, double convergence_threshold_param, unsigned long maximum_iterations_param): _dampening_lambda(dampening_lambda_param), _convergence_threshold(convergence_threshold_param), _maximum_iterations(maximum_iterations_param) { assert(_dampening_lambda < 0.5 && "Dampening should be performed with lambda < 0.5 (higher lambda values will weight older messages over new messages, and may lead to oscillations [unproven])"); } virtual ~Scheduler() {} double dampening_lambda() const { return _dampening_lambda; } double convergence_threshold() const { return _convergence_threshold; } void set_dampening_lambda(double lambda) { _dampening_lambda = lambda; } void set_convergence_threshold(double epsilon) { _convergence_threshold = epsilon; } void set_maximum_iterations(unsigned long n) { _maximum_iterations = n; } // Returns the number of iterations spent: virtual unsigned long process_next_edges() = 0; virtual bool has_converged() const = 0; // Add messages to the queue that are elligible to pass from the start: virtual void add_ab_initio_edges(InferenceGraph<VARIABLE_KEY> &) = 0; // Returns the number of iterations spent: virtual unsigned long run_until_convergence() { unsigned long iteration; for (iteration = 0; ! has_converged() && iteration < this->_maximum_iterations; ) { iteration += process_next_edges(); } if (iteration >= this->_maximum_iterations) std::cerr << "Warning: Did not meet desired convergence threshold (stopping anyway after exceeding " << this->_maximum_iterations << " iterations)." << std::endl; return iteration; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/BeliefPropagationInferenceEngine.hpp
.hpp
9,772
228
#ifndef _BELIEFPROPAGATIONINFERENCEENGINE_HPP #define _BELIEFPROPAGATIONINFERENCEENGINE_HPP #include "InferenceEngine.hpp" #include "Scheduler.hpp" #include "InferenceGraph.hpp" #include "SetHash.hpp" #include "Hyperedge.hpp" #include "../Utility/to_string.hpp" #include "random_tree_subgraph.hpp" #include <unordered_map> template <typename VARIABLE_KEY> class BeliefPropagationInferenceEngine : public InferenceEngine<VARIABLE_KEY> { protected: Scheduler<VARIABLE_KEY> & _scheduler; const InferenceGraph<VARIABLE_KEY> & _graph; unsigned long _nrMessagesPassed = 0; bool every_nontrivial_edge_has_passed_at_least_one_message() const { bool res = true; for (MessagePasser<VARIABLE_KEY>*mp : _graph.message_passers) for (unsigned long k=0; k<mp->number_edges(); ++k) { Edge<VARIABLE_KEY>*edge = mp->get_edge_out(k); if (edge->source->number_edges() == 1 && static_cast<Hyperedge<VARIABLE_KEY>*>(edge->source) != NULL) continue; if (edge->dest->number_edges() == 1 && static_cast<Hyperedge<VARIABLE_KEY>*>(edge->dest) != NULL) continue; res = res && mp->edge_received(k); } return res; } public: BeliefPropagationInferenceEngine(Scheduler<VARIABLE_KEY> & scheduler, const InferenceGraph<VARIABLE_KEY> & graph): _scheduler(scheduler), _graph(graph) { } // returns zero if nothing was run yet. will be overwritten each run. unsigned long getNrMessagesPassed () { return _nrMessagesPassed; } // estimate posterior in steps with different dampening and convergence settings // TODO if we implement getRemainingMessages, we probably could switch the type // of scheduling too. std::vector<LabeledPMF<VARIABLE_KEY> > estimate_posteriors_in_steps( const std::vector<std::vector<VARIABLE_KEY> > & joint_distributions_to_retrieve, const std::vector<std::tuple<unsigned long, double, double>> & step_settings) { for (const auto& step : step_settings) { //inside the scheduler the current nr iteration are reset in run_until_convergence _scheduler.set_maximum_iterations(std::get<0>(step)); _scheduler.set_dampening_lambda(std::get<1>(step)); _scheduler.set_convergence_threshold(std::get<2>(step)); _nrMessagesPassed += _scheduler.run_until_convergence(); if (_scheduler.has_converged()) break; } if ( ! every_nontrivial_edge_has_passed_at_least_one_message() ) // This can happen if the graph is so large that not every edge // has been visited yet or if the graph contains a connected // component with no prior information: std::cerr << "Warning: Not every edge has passed a message (however posteriors may exist for the variables of interest). It may be that belief propagation hasn't yet converged (e.g., if this graph is large). If the graph is not large, check that your model doesn't add an edge using the wrong variable." << std::endl; std::vector<LabeledPMF<VARIABLE_KEY> > results; // Build a dictionary of varaibles to the message passers that // contain them. Set the initial number of bins with the number // of message passers to avoid resizing: std::unordered_map< std::unordered_set<VARIABLE_KEY>, const HUGINMessagePasser<VARIABLE_KEY>*, SetHash<VARIABLE_KEY> > variables_to_message_passers(_graph.message_passers.size()); for (const MessagePasser<VARIABLE_KEY>* mp : _graph.message_passers) { const HUGINMessagePasser<VARIABLE_KEY>* hmp = dynamic_cast<const HUGINMessagePasser<VARIABLE_KEY>* >(mp); if (hmp != NULL) { // mp is a HUGINMessagePasser: const std::vector<VARIABLE_KEY> & ordered_variables = hmp->joint_posterior().ordered_variables(); std::unordered_set<VARIABLE_KEY> unordered_variables(ordered_variables.begin(), ordered_variables.end()); auto iter = variables_to_message_passers.find(unordered_variables); if ( iter == variables_to_message_passers.end() ) variables_to_message_passers[unordered_variables] = hmp; } } for (const std::vector<VARIABLE_KEY> & ordered_variables : joint_distributions_to_retrieve) { std::unordered_set<VARIABLE_KEY> unordered_variables(ordered_variables.begin(), ordered_variables.end()); auto iter = variables_to_message_passers.find(unordered_variables); if (iter == variables_to_message_passers.end()) { std::string vars = ""; for (const VARIABLE_KEY & var : unordered_variables) vars += to_string(var) + " "; std::cerr << "Could not find posterior for variable set " << vars << std::endl; assert(false); } results.push_back(iter->second->joint_posterior().transposed(ordered_variables)); } return results; } std::vector<LabeledPMF<VARIABLE_KEY> > estimate_posteriors(const std::vector<std::vector<VARIABLE_KEY> > & joint_distributions_to_retrieve) { _nrMessagesPassed = _scheduler.run_until_convergence(); if ( ! every_nontrivial_edge_has_passed_at_least_one_message() ) // This can happen if the graph is so large that not every edge // has been visited yet or if the graph contains a connected // component with no prior information: std::cerr << "Warning: Not every edge has passed a message (however posteriors may exist for the variables of interest). It may be that belief propagation hasn't yet converged (e.g., if this graph is large). If the graph is not large, check that your model doesn't add an edge using the wrong variable." << std::endl; std::vector<LabeledPMF<VARIABLE_KEY> > results; // Build a dictionary of varaibles to the message passers that // contain them. Set the initial number of bins with the number // of message passers to avoid resizing: std::unordered_map< std::unordered_set<VARIABLE_KEY>, const HUGINMessagePasser<VARIABLE_KEY>*, SetHash<VARIABLE_KEY> > variables_to_message_passers(_graph.message_passers.size()); for (const MessagePasser<VARIABLE_KEY>* mp : _graph.message_passers) { const HUGINMessagePasser<VARIABLE_KEY>* hmp = dynamic_cast<const HUGINMessagePasser<VARIABLE_KEY>* >(mp); if (hmp != NULL) { // mp is a HUGINMessagePasser: const std::vector<VARIABLE_KEY> & ordered_variables = hmp->joint_posterior().ordered_variables(); std::unordered_set<VARIABLE_KEY> unordered_variables(ordered_variables.begin(), ordered_variables.end()); auto iter = variables_to_message_passers.find(unordered_variables); if ( iter == variables_to_message_passers.end() ) variables_to_message_passers[unordered_variables] = hmp; } } for (const std::vector<VARIABLE_KEY> & ordered_variables : joint_distributions_to_retrieve) { std::unordered_set<VARIABLE_KEY> unordered_variables(ordered_variables.begin(), ordered_variables.end()); auto iter = variables_to_message_passers.find(unordered_variables); if (iter == variables_to_message_passers.end()) { std::string vars = ""; for (const VARIABLE_KEY & var : unordered_variables) vars += to_string(var) + " "; std::cerr << "Could not find posterior for variable set " << vars << std::endl; assert(false); } results.push_back(iter->second->joint_posterior().transposed(ordered_variables)); } return results; } double log_normalization_constant() { std::unordered_map<VARIABLE_KEY, LabeledPMF<VARIABLE_KEY> > var_to_prior_products; std::unordered_map<VARIABLE_KEY, LabeledPMF<VARIABLE_KEY> > var_to_posterior; std::unordered_map<VARIABLE_KEY, LabeledPMF<VARIABLE_KEY> > var_to_invisible_prior; for ( MessagePasser<VARIABLE_KEY>*mp : _graph.message_passers ) { HUGINMessagePasser<VARIABLE_KEY>* hmp = dynamic_cast<HUGINMessagePasser<VARIABLE_KEY>* >(mp); if (hmp != NULL) { if (hmp->prior().dimension() > 0) { for (const VARIABLE_KEY & var : hmp->prior().ordered_variables()) { // Note: computes marginal several times; may be faster to // compute all marginals in single pass. // Use p=1 here, regardless of how inference is performed: LabeledPMF<VARIABLE_KEY> marg = hmp->prior().marginal({var}, 1); var_to_prior_products[var] = var_to_prior_products[var] * marg; } } if (hmp->joint_posterior().dimension() > 0) { for (const VARIABLE_KEY & var : hmp->joint_posterior().ordered_variables()) { if (var_to_posterior.find(var) == var_to_posterior.end()) { // Use p=1 here, regardless of how inference is performed: LabeledPMF<VARIABLE_KEY> marg = hmp->joint_posterior().marginal({var}, 1); marg.reset_log_normalization_constant(); var_to_posterior[var] = marg; } } } } } for ( MessagePasser<VARIABLE_KEY>*mp : _graph.message_passers ) { HUGINMessagePasser<VARIABLE_KEY>* hmp = dynamic_cast<HUGINMessagePasser<VARIABLE_KEY>* >(mp); if (hmp == NULL) { // Not HUGIN (which also means not Hyperedge, since Hyperedge // inherits from HUGIN): for (unsigned long i=0; i<mp->number_edges(); ++i) { Edge<VARIABLE_KEY>*e = mp->get_edge_out(i); for (const VARIABLE_KEY & var : *e->variables_ptr) { if (var_to_posterior.find(var) != var_to_posterior.end()) { var_to_invisible_prior[var] = var_to_posterior[var] / var_to_prior_products[var]; var_to_invisible_prior[var].reset_log_normalization_constant(); } } } } } double result = 0.0; for (const std::pair<VARIABLE_KEY, LabeledPMF<VARIABLE_KEY> > & p : var_to_prior_products) { const VARIABLE_KEY & var = p.first; if (var_to_invisible_prior.find(var) != var_to_invisible_prior.end()) result += (p.second * var_to_invisible_prior[var]).log_normalization_constant(); else result += p.second.log_normalization_constant(); } return result; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/split_connected_components.hpp
.hpp
1,673
46
#ifndef _SPLIT_CONNECTED_COMPONENTS_HPP #define _SPLIT_CONNECTED_COMPONENTS_HPP // This can be done easily in O(n log(n)); here it is done in a // slightly less straightforward way to get an O(n) runtime. template <typename VARIABLE_KEY> std::vector<InferenceGraph<VARIABLE_KEY> > split_connected_components(InferenceGraph<VARIABLE_KEY> && ig) { // Clear colors: for (unsigned long i=0; i<ig.message_passers.size(); ++i) ig.message_passers[i]->color = -1L; // Assign colors for connected components in O(n): unsigned long current_color = 0; for (unsigned long i=0; i<ig.message_passers.size(); ++i) { MessagePasser<VARIABLE_KEY>*mp = ig.message_passers[i]; if (mp->color < 0) { // Note: could possibly simplify, queueing the nodes belonging // to current_color inside this closure: node_dfs({mp}, [current_color](MessagePasser<VARIABLE_KEY>*mp){ mp->color = current_color; }); ++current_color; } } // Group nodes by color: std::vector<std::vector<MessagePasser<VARIABLE_KEY>* > > mps_grouped_by_color(current_color); for (unsigned long i=0; i<ig.message_passers.size(); ++i) { MessagePasser<VARIABLE_KEY>*mp = ig.message_passers[i]; mps_grouped_by_color[mp->color].push_back(mp); } // Build several graphs for result: std::vector<InferenceGraph<VARIABLE_KEY> > result; for (std::vector<MessagePasser<VARIABLE_KEY>* > & mps : mps_grouped_by_color) result.push_back( std::move(InferenceGraph<VARIABLE_KEY>(std::move(mps))) ); // Prevent destructor from being called multiple times: ig.message_passers = std::vector<MessagePasser<VARIABLE_KEY>* >(); return result; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/ConstantMultiplierMessagePasser.hpp
.hpp
3,683
96
#ifndef _CONSTANTMULTIPLIERMESSAGEPASSER_HPP #define _CONSTANTMULTIPLIERMESSAGEPASSER_HPP #include "ContextFreeMessagePasser.hpp" template <typename VARIABLE_KEY> class ConstantMultiplierMessagePasser: public MessagePasser<VARIABLE_KEY> { protected: Vector<double> _scale; Vector<double> _one_over_scale; PMF _message_in_received; PMF _message_out_received; bool _interpolate_scaled, _interpolate_unscaled; double _dithering_sigma_squared; void receive_message_in(unsigned long index) { Edge<VARIABLE_KEY>*incoming_edge = MessagePasser<VARIABLE_KEY>::_edges_in[index]; if (index == 0) { // Message received by input: _message_in_received = incoming_edge->get_message().pmf(); } else { // Message received by output: _message_out_received = incoming_edge->get_message().pmf(); } } LabeledPMF<VARIABLE_KEY> get_message_out(unsigned long index) { Edge<VARIABLE_KEY>*incoming_edge = MessagePasser<VARIABLE_KEY>::_edges_in[index]; if (index == 0) { // Get message out through input (multiply _message_out_received // by _one_over_scale): PMF scaled; if (_interpolate_unscaled) scaled = scaled_pmf_dither_interpolate(_message_out_received, _one_over_scale, _dithering_sigma_squared); else scaled = scaled_pmf_dither(_message_out_received, _one_over_scale, _dithering_sigma_squared); if (_message_in_received.dimension() > 0) scaled.narrow_support(_message_in_received.first_support(), _message_in_received.last_support()); return LabeledPMF<VARIABLE_KEY>(*incoming_edge->variables_ptr, scaled); } else { // Get message out through output (multiply _message_in_received // by _scale): PMF scaled; if (_interpolate_scaled) scaled = scaled_pmf_dither_interpolate(_message_in_received, _scale, _dithering_sigma_squared); else scaled = scaled_pmf_dither(_message_in_received, _scale, _dithering_sigma_squared); if (_message_out_received.dimension() > 0) scaled.narrow_support(_message_out_received.first_support(), _message_out_received.last_support()); return LabeledPMF<VARIABLE_KEY>(*incoming_edge->variables_ptr, scaled); } } public: ConstantMultiplierMessagePasser(ContextFreeMessagePasser<VARIABLE_KEY>* input, const std::vector<VARIABLE_KEY>* input_edge_label, ContextFreeMessagePasser<VARIABLE_KEY>*output, std::vector<VARIABLE_KEY>* output_edge_label, const Vector<double> & scale_param, bool interpolate_scaled, bool interpolate_unscaled, double dithering_sigma): _scale(scale_param), _one_over_scale(1.0 / scale_param), _interpolate_scaled(interpolate_scaled), _interpolate_unscaled(interpolate_unscaled), _dithering_sigma_squared(dithering_sigma*dithering_sigma) { #ifdef ENGINE_CHECK assert(input_edge_label->size() == output_edge_label->size()); assert(input_edge_label->size() == scale_param.size()); #endif // Bind input first and output last: this->bind_to(input, input_edge_label); this->bind_to(output, output_edge_label); } void print(std::ostream & os) const { Edge<VARIABLE_KEY>*input_edge = MessagePasser<VARIABLE_KEY>::_edges_in[0]; Edge<VARIABLE_KEY>*output_edge = MessagePasser<VARIABLE_KEY>::_edges_in[1]; os << "ConstantMultiplierMessagePasser "; for (unsigned int i=0; i<output_edge->variables_ptr->size(); ++i) os << (*output_edge->variables_ptr)[i] << " "; os << "= " << _scale << " * "; for (unsigned int i=0; i<input_edge->variables_ptr->size(); ++i) os << (*input_edge->variables_ptr)[i] << " "; } const Vector<double> & scale() const { return _scale; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/SetQueue.hpp
.hpp
4,369
156
#ifndef _SETQUEUE_HPP #define _SETQUEUE_HPP #include <set> #include <unordered_map> #include <iostream> template <typename VARIABLE_KEY> class SetQueue { protected: double _max_priority; // This needs to use std::set instead of std::unordered_set because // the ordering is used (it used in a manner similar to a heap, so a // priority queue may also be an option). std::set<double> _priorities; // Uses unordered_set<T> since ordering is not used. std::unordered_map<double, std::unordered_set<Edge<VARIABLE_KEY>*> > _priorities_to_values; std::size_t _size; public: SetQueue(): _size(0) { } bool is_empty() const { return _size == 0; } std::size_t size() const { return _size; } double max_priority() const { #ifdef ENGINE_CHECK assert( ! is_empty() ); #endif return _max_priority; } bool contains_priority(double priority) const { auto iter = _priorities.find(priority); return iter != _priorities.end(); } void push_or_update(Edge<VARIABLE_KEY>* val, double new_priority) { if (val->in_queue) update_priority(val, new_priority); else { val->priority = new_priority; push(val); } } void push(Edge<VARIABLE_KEY>* val) { #ifdef ENGINE_CHECK assert(! val->in_queue); #endif if (! contains_priority(val->priority)) { _priorities.insert(val->priority); _priorities_to_values[val->priority] = std::unordered_set<Edge<VARIABLE_KEY>*>(); } // Now both priorities and _priorities_to_values contain priority: std::unordered_set<Edge<VARIABLE_KEY>*> & vals_at_priority = _priorities_to_values[val->priority]; #ifdef ENGINE_CHECK assert( vals_at_priority.find(val) == vals_at_priority.end() && "Value already in Queue"); #endif vals_at_priority.insert(val); if (_size == 0 || val->priority > _max_priority) _max_priority = val->priority; ++_size; val->in_queue = true; } Edge<VARIABLE_KEY>* pop_max() { #ifdef ENGINE_CHECK assert( ! is_empty() ); #endif double priority = max_priority(); std::unordered_set<Edge<VARIABLE_KEY>*> & vals_at_priority = _priorities_to_values[priority]; // Erase the max from the inner set: auto iter = vals_at_priority.begin(); Edge<VARIABLE_KEY>* result = *iter; #ifdef ENGINE_CHECK assert(result->in_queue); #endif vals_at_priority.erase( iter ); // If the inner set has become empty, remove the empty set and // remove the priority from the collection of all priorities: if (vals_at_priority.size() == 0) { _priorities_to_values.erase(priority); _priorities.erase(priority); } --_size; if ( ! is_empty() ) _max_priority = *_priorities.rbegin(); result->in_queue = false; return result; } void remove(Edge<VARIABLE_KEY>* val) { #ifdef ENGINE_CHECK assert(contains_priority(val->priority) && "Error: Priority to update not in queue"); #endif // remove (possibly from middle): --_size; std::unordered_set<Edge<VARIABLE_KEY>*> & vals_at_priority = _priorities_to_values.find(val->priority)->second; #ifdef ENGINE_CHECK assert(vals_at_priority.count(val) && "Error: Value at requested priority not in queue"); #endif vals_at_priority.erase( val ); if ( vals_at_priority.size() == 0 ) { _priorities_to_values.erase(val->priority); _priorities.erase(val->priority); } if ( ! is_empty() ) _max_priority = *_priorities.rbegin(); val->in_queue = false; } void update_priority(Edge<VARIABLE_KEY>* val, double new_priority) { // Note: if new_priority < old_priority, a Fibonacci heap could do // this in amortized O(1): #ifdef ENGINE_CHECK assert(val->in_queue); #endif remove(val); val->priority = new_priority; push(val); } void print(std::ostream & os) const { os << "Size " << size() << std::endl; for (double priority : _priorities) { os << "Priority " << priority << " "; const std::unordered_set<Edge<VARIABLE_KEY>*> & vals_at_priority = _priorities_to_values.find(priority)->second; for (const Edge<VARIABLE_KEY>* val : vals_at_priority) { os << val; // os << " " << val->get_possibly_outdated_message(); os << " " << val->priority; } os << std::endl; } } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/HUGINMessagePasser.hpp
.hpp
4,853
144
#ifndef _HUGINMESSAGEPASSER_HPP #define _HUGINMESSAGEPASSER_HPP #include "PNormMixin.hpp" #include "ContextFreeMessagePasser.hpp" // Note: There is an unexploited speedup when there are only two // edges. In that case, it is better to solve it as a Shafer-Shenoy, // where nothing is cached, since the outgoing messages will simply be // raw inputs (with no multiplication). This could be done in // HUGINMessagePasser or could alternatively be the responsibility of // the graph construction (which would choose an alternate // Shafer-Shenoy message passer in such situations). template <typename VARIABLE_KEY> class HUGINMessagePasser : public ContextFreeMessagePasser<VARIABLE_KEY>, public PNormMixin { protected: LabeledPMF<VARIABLE_KEY> _prior; LabeledPMF<VARIABLE_KEY> _product; std::vector<LabeledPMF<VARIABLE_KEY> > _last_messages_received; std::vector<bool> _ready_to_send_ab_initio; void add_input_and_output_edges(Edge<VARIABLE_KEY>*edge_in, Edge<VARIABLE_KEY>*edge_out) { MessagePasser<VARIABLE_KEY>::add_input_and_output_edges(edge_in, edge_out); // Push an empty last message received: _last_messages_received.push_back(LabeledPMF<VARIABLE_KEY>()); // When edge labels are subset of variables in _product, // start as ready to send ab initio: bool can_send_on_construction = true; for (const VARIABLE_KEY & var: *edge_in->variables_ptr) can_send_on_construction &= _product.contains_variable(var); _ready_to_send_ab_initio.push_back(can_send_on_construction); } bool ready_to_send_message_ab_initio(unsigned long edge_index) const { return _ready_to_send_ab_initio[edge_index]; } void receive_message_in(unsigned long edge_index) { #ifndef SHAFERSHENOY Edge<VARIABLE_KEY>*incoming_edge = MessagePasser<VARIABLE_KEY>::_edges_in[edge_index]; if (_product.dimension() > 0) { if (_last_messages_received[edge_index].dimension()>0) // A message had previously been received along edge; divide // out the old one and multiply in the new one: _product = incoming_edge->get_message() * _product / _last_messages_received[edge_index]; else // No message had previously been received along edge; // multiply in the new one: _product = _product * incoming_edge->get_message(); } else // No previous messages were received until now, and no prior // was provided; initialize the product distribution. _product = incoming_edge->get_message(); _last_messages_received[edge_index] = incoming_edge->get_message(); #endif } LabeledPMF<VARIABLE_KEY> get_message_out(unsigned long edge_index) { #ifdef SHAFERSHENOY LabeledPMF<VARIABLE_KEY> result = _product; for (unsigned int i=0; i<this->number_edges(); ++i) { if (i != edge_index) { Edge<VARIABLE_KEY>*e = this->_edges_in[i]; if (e->has_message()) { auto msg = e->get_possibly_outdated_message(); result = result * msg; } } } Edge<VARIABLE_KEY>*outward_edge = MessagePasser<VARIABLE_KEY>::_edges_out[edge_index]; return result.marginal(*outward_edge->variables_ptr, this->p); #else Edge<VARIABLE_KEY>*outward_edge = MessagePasser<VARIABLE_KEY>::_edges_out[edge_index]; LabeledPMF<VARIABLE_KEY> message_out = _product.marginal(*outward_edge->variables_ptr, this->p); // Divide out the message along the inward edge: if (this->_edge_received[edge_index]) { const LabeledPMF<VARIABLE_KEY> & message_in = _last_messages_received[edge_index]; message_out = message_out / message_in; } return message_out; #endif } public: HUGINMessagePasser(const LabeledPMF<VARIABLE_KEY> & prior, const double p): PNormMixin(p), _prior(prior), _product(prior) { } HUGINMessagePasser(LabeledPMF<VARIABLE_KEY> && prior, const double p): PNormMixin(p), _prior(std::move(prior)), _product(_prior) { } HUGINMessagePasser(const double p): PNormMixin(p) { } const LabeledPMF<VARIABLE_KEY> & joint_posterior() const { #ifdef SHAFERSHENOY LabeledPMF<VARIABLE_KEY> result; for (unsigned int i=0; i<this->number_edges(); ++i) { Edge<VARIABLE_KEY>*e = this->_edges_in[i]; if (e->has_message()) { auto msg = e->get_possibly_outdated_message(); result = result * msg; } } LabeledPMF<VARIABLE_KEY> * res = new LabeledPMF<VARIABLE_KEY>(result*_product); for (unsigned int i=0; i<this->number_edges(); ++i) { Edge<VARIABLE_KEY>*e = this->_edges_in[i]; if (e->has_message()) { auto msg = e->get_possibly_outdated_message(); } } return *res; #else return _product; #endif } const LabeledPMF<VARIABLE_KEY> & prior() const { return _prior; } void print(std::ostream & os) const { os << "HUGINMessagePasser prior:" << _prior << " _joint:" << _product; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/ContextFreeMessagePasser.hpp
.hpp
753
26
#ifndef _CONTEXTFREEMESSAGEPASSER_HPP #define _CONTEXTFREEMESSAGEPASSER_HPP #include "MessagePasser.hpp" // ContextFreeMessagePasser types do not have distinct roles for // messages in or out; this contrasts with e.g. probabilistic // addition, where the output edge needs to be labeled as distinct // from the input edges. As a result, ContextFreeMessagePasser types // can add edges outside of their constructors; therefore, promote // bind_to to allow public access. // ContextFreeMessagePasser is a good base type for hyperedges. template <typename VARIABLE_KEY> class ContextFreeMessagePasser : public MessagePasser<VARIABLE_KEY> { protected: ContextFreeMessagePasser() { } public: using MessagePasser<VARIABLE_KEY>::bind_to; }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/TreeScheduler.hpp
.hpp
421
10
// TODO: find extreme vertices (which must be leaves) and seed with those extreme vertices that can pass ab initio. // Do not wake other MPs, even those that could have passed ab initio, unless they have received messages on all other edges // Note that this strategy will fail if the extreme vertices cannot // pass ab initio (e.g., if you want their posteriors, but they // contribute no information to the model).
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/random_tree_subgraph.hpp
.hpp
1,076
35
#ifndef _RANDOM_TREE_SUBGRAPH_HPP #define _RANDOM_TREE_SUBGRAPH_HPP // Note: Assumes graph is connected (otherwise, split into connected // compoonents and then call) template <typename VARIABLE_KEY> std::list<MessagePasser<VARIABLE_KEY>* > random_tree_subgraph(InferenceGraph<VARIABLE_KEY> & ig) { // Note: doing rand() % N can effectively discard some entropy; if // high-quality random numbers are necessary, then there are more // effective ways to do this. auto rand_int = [](unsigned long size) { return rand() % size; }; // Clear node colors: for (unsigned long i=0; i<ig.message_passers.size(); ++i) ig.message_passers[i]->color = -1; // Choose random root: MessagePasser<VARIABLE_KEY>*root = ig.message_passers[ rand_int(ig.message_passers.size()) ]; // Build traversal order of tree via DFS: std::list<MessagePasser<VARIABLE_KEY>* > result; node_dfs({root}, [&result](MessagePasser<VARIABLE_KEY>*mp){ result.push_back(mp); // Mark the node as visited: mp->color = 1; }); return result; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/HybridFIFOPriorityScheduler.hpp
.hpp
1,901
57
#ifndef _HYBRIDFIFOPRIORITYSCHEDULER_HPP #define _HYBRIDFIFOPRIORITYSCHEDULER_HPP #include "FIFOScheduler.hpp" #include "PriorityScheduler.hpp" // Combines FIFOScheduler and PriorityScheduler: first run // FIFOScheduler (this is useful for solving ). template <typename VARIABLE_KEY> class HybridFIFOPriorityScheduler : public Scheduler<VARIABLE_KEY> { protected: const InferenceGraph<VARIABLE_KEY> & _graph; FIFOScheduler<VARIABLE_KEY>* fs; PriorityScheduler<VARIABLE_KEY>* ps; public: HybridFIFOPriorityScheduler(double dampening_lambda, double convergence_threshold, unsigned long maximum_iterations, const InferenceGraph<VARIABLE_KEY> & graph): Scheduler<VARIABLE_KEY>(dampening_lambda, convergence_threshold, maximum_iterations), _graph(graph), fs(NULL), ps(NULL) { } ~HybridFIFOPriorityScheduler() { if (fs != NULL) delete fs; if (ps != NULL) delete ps; } bool process_next_edges() { if (!fs.has_converged()) fs->process_next_edges(); else ps->process_next_edges(); } unsigned long run_until_convergence() { // Use inf as the convergence threshold for FIFOScheduler, // guaranteening that every reachable edge is only visited once: fs = new FIFOScheduler<VARIABLE_KEY> (this->_dampening_lambda, std::numeric_limits<double>::infinity(), this->_maximum_iterations, _graph); // First, send messages across every reachable edge via the // FIFOScheduler: unsigned long iterations_used = fs->run_until_convergence(); // iterations_used should be <= this->_maximum_iterations, so subtracting is safe: PriorityScheduler<VARIABLE_KEY> ps(this->_dampening_lambda, this->_convergence_threshold, this->_maximum_iterations - iterations_used, _graph); return iterations_used + ps.run_until_convergence(); } bool has_converged() const { return ps->has_converged(); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/ConvolutionTreeMessagePasser.hpp
.hpp
2,690
75
#ifndef _CONVOLUTIONTREEMESSAGEPASSER_HPP #define _CONVOLUTIONTREEMESSAGEPASSER_HPP #include "PNormMixin.hpp" #include "ContextFreeMessagePasser.hpp" #include "ConvolutionTree.hpp" template <typename VARIABLE_KEY> class ConvolutionTreeMessagePasser : public MessagePasser<VARIABLE_KEY>, public PNormMixin { protected: ConvolutionTree _ct; void receive_message_in(unsigned long index) { // Note that variable order within each PMF (which assigns axes) // will be determined by the edge label already (when the message // is passed). Therefore, the order of variables in each edge // label matters (not only the set of variables). _ct.receive_message_in(index, this->_edges_in[index]->get_message().pmf()); } LabeledPMF<VARIABLE_KEY> get_message_out(unsigned long index) { // Get message from _ct and then label appropriately: PMF pmf = _ct.get_message_out(index); return LabeledPMF<VARIABLE_KEY>(*this->_edges_out[index]->variables_ptr, std::move(pmf)); } public: // Should only be constructed by binding to ContextFreeMessagePasser // types because it will involve adding edges to those MessagePasser // types, which could violate context. ConvolutionTreeMessagePasser(const std::vector<ContextFreeMessagePasser<VARIABLE_KEY>*> & inputs, const std::vector<std::vector<VARIABLE_KEY>*> & input_edge_labels, ContextFreeMessagePasser<VARIABLE_KEY>*output, std::vector<VARIABLE_KEY>* output_edge_label, const unsigned char dimension_param, const double p_param): PNormMixin(p_param), _ct(inputs.size(), dimension_param, p_param) { #ifdef ENGINE_CHECK assert(inputs.size() == input_edge_labels.size()); // Note: dimensions are not verified, but will be when messages // are passed through edges. #endif // Bind inputs first and output last; this is what ConvolutionTree // is expecting: for (unsigned long k=0; k<inputs.size(); ++k) this->bind_to(inputs[k], input_edge_labels[k]); this->bind_to(output, output_edge_label); } virtual void print(std::ostream & os) const { // TODO: implement more informative version: os << "ConvolutionTreeMessagePasser " << int(_ct.dimension()) << " "; for (unsigned long i=0; i<this->_edges_in.size()-1; ++i) { os << "{ "; for (unsigned char j=0; j<_ct.dimension(); ++j) { os << (*this->_edges_in[i]->variables_ptr)[j]; os << " "; } os << "}"; if (i != this->_edges_in.size()-2) os << " + "; } os << " = { "; for (unsigned char j=0; j<_ct.dimension(); ++j) { os << (*this->_edges_in[this->_edges_in.size()-1]->variables_ptr)[j]; os << " "; } os << "}"; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/TransformMessagePasser.hpp
.hpp
1,679
40
#ifndef _TRANSFORMMESSAGEPASSER_HPP #define _TRANSFORMMESSAGEPASSER_HPP #include "ContextFreeMessagePasser.hpp" template <typename VARIABLE_KEY> class TransformMessagePasser : public MessagePasser<VARIABLE_KEY> { protected: void receive_message_in(unsigned long index) { // Reorder to match _ordered_variables and pass into _ct: _ct.receive_message_in(index, this->_edges_in[index]->get_message().get_pmf()); } LabeledPMF<VARIABLE_KEY> get_message_out(unsigned long index) { // Get message from _ct and then label appropriately: PMF pmf = _ct.get_message_out(index); return LabeledPMF<VARIABLE_KEY>(*this->_edges_out[index]->variables_ptr, std::move(pmf)); } virtual void map_input_outcome_to_output_outcome(const Vector<unsigned long> & input_outcome, Vector<unsigned long> & output_outcome) = 0; virtual void map_output_outcome_to_input_outcome(Vector<unsigned long> & input_outcome, const Vector<unsigned long> & output_outcome) = 0; public: TransformMessagePasser(const ContextFreeMessagePasser<VARIABLE_KEY>* & input, const std::vector<std::vector<VARIABLE_KEY>*> & input_edge_label, ContextFreeMessagePasser<VARIABLE_KEY>*output, std::vector<VARIABLE_KEY>* output_edge_label, const unsigned char dimension_param, const double p): MessagePasser<VARIABLE_KEY>(p), _ct(inputs.size(), dimension_param, p) { #ifdef ENGINE_CHECK assert(inputs.size() == input_edge.size()); assert(output.size() == output_edge.size()); assert(input.size() == output.size()); #endif // Bind input first and output last: this->bind_to(input, input_edge_label); this->bind_to(output, output_edge_label); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/InferenceEngine.hpp
.hpp
409
17
#ifndef _INFERENCEENGINE_HPP #define _INFERENCEENGINE_HPP #include "../PMF/LabeledPMF.hpp" template <typename VARIABLE_KEY> class InferenceEngine { public: virtual std::vector<LabeledPMF<VARIABLE_KEY> > estimate_posteriors(const std::vector<std::vector<VARIABLE_KEY> > & joint_distributions_to_retrieve) = 0; virtual double log_normalization_constant() = 0; virtual ~InferenceEngine() {} }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Engine/PNormMixin.hpp
.hpp
165
15
#ifndef _PNORMMIXIN_HPP #define _PNORMMIXIN_HPP class PNormMixin { public: const double p; public: PNormMixin(double p_param): p(p_param) { } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/TableDependency.hpp
.hpp
928
34
#ifndef _TABLEDEPENDENCY_HPP #define _TABLEDEPENDENCY_HPP #include "Dependency.hpp" #include "../PMF/LabeledPMF.hpp" template <typename VARIABLE_KEY> class TableDependency : public Dependency<VARIABLE_KEY>, public PNormMixin { protected: LabeledPMF<VARIABLE_KEY> _lpmf; public: TableDependency(const LabeledPMF<VARIABLE_KEY> & lpmf, const double p_param): PNormMixin(p_param), _lpmf(lpmf) { } virtual HUGINMessagePasser<VARIABLE_KEY>* create_message_passer(InferenceGraphBuilder<VARIABLE_KEY> & /*igb*/) const { // Note: Does not create hyperdges or bind to hyperedges. That is // the responsibility of InferenceGraphBuilder. return new HUGINMessagePasser<VARIABLE_KEY>(_lpmf, this->p); } virtual std::vector<VARIABLE_KEY> get_all_variables_used() const { return _lpmf.ordered_variables(); } const LabeledPMF<VARIABLE_KEY> & labeled_pmf() const { return _lpmf; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/AdditiveDependency.hpp
.hpp
2,244
61
#ifndef _ADDITIVEDEPENDENCY_HPP #define _ADDITIVEDEPENDENCY_HPP #include "../Engine/ConvolutionTreeMessagePasser.hpp" #include "Dependency.hpp" template <typename VARIABLE_KEY> class AdditiveDependency : public Dependency<VARIABLE_KEY>, public PNormMixin { protected: std::vector<std::vector<VARIABLE_KEY> > _inputs; std::vector<VARIABLE_KEY> _output; public: AdditiveDependency(const std::vector<std::vector<VARIABLE_KEY> > & inputs, const std::vector<VARIABLE_KEY> & output, const double p_param): PNormMixin(p_param), _inputs(inputs), _output(output) { #ifdef ENGINE_CHECK for (const std::vector<VARIABLE_KEY> & in : _inputs) assert(in.size() == output.size() && "Dimension of each tuple in additive dependency must equal dimension of output tuple"); #endif } virtual ConvolutionTreeMessagePasser<VARIABLE_KEY>* create_message_passer(InferenceGraphBuilder<VARIABLE_KEY> & igb) const { std::vector<ContextFreeMessagePasser<VARIABLE_KEY>*> hyperedges_in; std::vector<std::vector<VARIABLE_KEY>*> edge_labels_in; for (const std::vector<VARIABLE_KEY> & in : _inputs) { HUGINMessagePasser<VARIABLE_KEY>* hyperedge = igb.create_hyperedge(); hyperedges_in.push_back(hyperedge); std::vector<VARIABLE_KEY>* edge_label_in = new std::vector<VARIABLE_KEY>(in); edge_labels_in.push_back(edge_label_in); } ContextFreeMessagePasser<VARIABLE_KEY>* hyperedge_out = igb.create_hyperedge(); std::vector<VARIABLE_KEY>* edge_label_out = new std::vector<VARIABLE_KEY>(_output); // Note: The above allocations are not deallocated until // InferenceGraph destructor. return new ConvolutionTreeMessagePasser<VARIABLE_KEY>(hyperedges_in, edge_labels_in, hyperedge_out, edge_label_out, (unsigned char)_output.size(), this->p); } virtual std::vector<VARIABLE_KEY> get_all_variables_used() const { std::vector<VARIABLE_KEY> result = flatten(get_inputs()); for (const VARIABLE_KEY & var : get_output()) result.push_back(var); return result; } const std::vector<std::vector<VARIABLE_KEY> > & get_inputs() const { return _inputs; } const std::vector<VARIABLE_KEY> & get_output() const { return _output; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/evergreen.hpp
.hpp
1,863
75
#ifndef _EVERGREEN_HPP #define _EVERGREEN_HPP // Create a macro for ALWAYS_INLINE (different modifiers on different compilers) #if defined(_MSC_VER) #define EVERGREEN_ALWAYS_INLINE __forceinline #else #define EVERGREEN_ALWAYS_INLINE inline __attribute__((always_inline)) #endif // added by jpfeuffer to throw exceptions #include <stdexcept> #include <sstream> // added by jpfeuffer to enable header guards before the namespace evergreen #include <unordered_map> #include <unordered_set> #include <vector> #include <iostream> #include <iomanip> #include <chrono> #include <array> #include <set> #include <cmath> #include <list> #include <map> #include <utility> #include <algorithm> #include <functional> #include <assert.h> #include <string.h> // Can be commented out for greater performance; these simply verify // shapes of things and will not be very expensive (they are not like // bounds checking). They should be left as-is by default, because // they will warn of problems that could be tricky for novice users. #ifdef NDEBUG // nondebug #else // debug code #define SHAPE_CHECK #define NUMERIC_CHECK #define ENGINE_CHECK #endif // For debugging only (substantially decreases performance): //#define BOUNDS_CHECK namespace evergreen { // for convenience: #include "../Utility/vector_ostream.hpp" // Inference engines: #include "../Engine/BeliefPropagationInferenceEngine.hpp" #include "BruteForceInferenceEngine.hpp" // Standard schedulers: #include "../Engine/PriorityScheduler.hpp" #include "../Engine/FIFOScheduler.hpp" #include "../Engine/RandomSubtreeScheduler.hpp" // Standard dependencies: #include "AdditiveDependency.hpp" #include "PseudoAdditiveDependency.hpp" #include "ConstantMultiplierDependency.hpp" // TableDependency will already be included. #include "BetheInferenceGraphBuilder.hpp" } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/VariableBounds.hpp
.hpp
5,825
118
#include <map> #ifndef _VARIABLEBOUNDS_HPP #define _VARIABLEBOUNDS_HPP template <typename VARIABLE_KEY> std::map<VARIABLE_KEY, std::pair<long, long> > find_bounds_from_joint(const LabeledPMF<VARIABLE_KEY> & _joint) { std::map<VARIABLE_KEY, std::pair<long, long> > var_to_bounds; for (const VARIABLE_KEY & var : _joint.ordered_variables()) { LabeledPMF<VARIABLE_KEY> var_marg(_joint.marginal({var}, 1)); long var_small = var_marg.pmf().first_support()[0]; long var_large = var_marg.pmf().last_support()[0]; var_to_bounds[var] = std::make_pair(var_small, var_large); } return var_to_bounds; } template <typename VARIABLE_KEY> bool all_bounds_calculable(const AdditiveDependency<VARIABLE_KEY> additive, const std::map<VARIABLE_KEY, std::pair<long, long> > & var_to_bounds) { int dimensions = additive.get_output().size(); int max_missing_bounds_in_dimension = 0; for (int dimension = 0; dimension < dimensions; ++dimension) { int missing_bounds_in_dimension = 0; for (const std::vector<VARIABLE_KEY> & input : additive.get_inputs()) { if (var_to_bounds.count(input[dimension]) == 0) missing_bounds_in_dimension++; } if (var_to_bounds.count(additive.get_output()[dimension]) == 0) missing_bounds_in_dimension++; if (missing_bounds_in_dimension > max_missing_bounds_in_dimension) max_missing_bounds_in_dimension = missing_bounds_in_dimension; } //not <= 1 b/c function used to test not only if bounds are calculable, but if they need to be calculated as well. return max_missing_bounds_in_dimension == 1; } template <typename VARIABLE_KEY> bool no_vars_missing_bounds(const std::map<VARIABLE_KEY, std::vector<AdditiveDependency<VARIABLE_KEY>> > & var_to_additives_using_it, const std::map<VARIABLE_KEY, std::pair<long, long> > & var_to_bounds) { for(auto var_iter = var_to_additives_using_it.begin(); var_iter != var_to_additives_using_it.end(); ++var_iter) { VARIABLE_KEY var = var_iter->first; if (var_to_bounds.count(var) == 0) return false; } return true; } inline std::pair<long, long> compact_two_bounds (const std::pair<long, long> & new_bound, const std::pair<long, long> & old_bound) { std::pair <long, long> bound1(old_bound.first, old_bound.second); std::pair <long, long> bound2(new_bound.first, new_bound.second); std::pair <long, long> bound3(new_bound.first, old_bound.second); std::pair <long, long> bound4(old_bound.first, new_bound.second); std::pair <long, long> compacted_bound = bound1; if (compacted_bound.second - compacted_bound.first > bound2.second - bound2.first && bound2.second - bound2.first > 0) compacted_bound = bound2; if (compacted_bound.second - compacted_bound.first > bound3.second - bound3.first && bound3.second - bound3.first > 0) compacted_bound = bound3; if (compacted_bound.second - compacted_bound.first > bound4.second - bound4.first && bound4.second - bound4.first > 0) compacted_bound = bound4; return compacted_bound; } template <typename VARIABLE_KEY> std::pair<long, long> find_bounds_from_additive(const VARIABLE_KEY & var, const std::vector<std::vector<VARIABLE_KEY> > & inputs, const std::vector<VARIABLE_KEY> & output, const std::map<VARIABLE_KEY, std::pair<long, long> > & var_to_bounds) { long low_bound = 0; long high_bound = 0; bool var_in_output = find(output.begin(), output.end(), var) != output.end(); int var_dimension = 0; if (var_in_output) var_dimension = std::distance(output.begin(), find(output.begin(), output.end(), var)); else { for (const std::vector<VARIABLE_KEY> & input : inputs) { auto input_it = find(input.begin(), input.end(), var); if (input_it != input.end()) var_dimension = std::distance(input.begin(), input_it); } } for(const std::vector<VARIABLE_KEY> & input : inputs) { VARIABLE_KEY additive_var = input[var_dimension]; if (additive_var != var && var_to_bounds.find(additive_var) != var_to_bounds.end()) { long additive_low_bound = var_to_bounds.find(additive_var)->second.first; long additive_high_bound = var_to_bounds.find(additive_var)->second.second; if (var_in_output) { low_bound += additive_low_bound; high_bound += additive_high_bound; } else { low_bound -= additive_high_bound; high_bound -= additive_low_bound; } } } if (!var_in_output && var_to_bounds.find(output[var_dimension]) != var_to_bounds.end()) { low_bound += var_to_bounds.find(output[var_dimension])->second.first; high_bound += var_to_bounds.find(output[var_dimension])->second.second; } return std::make_pair(low_bound, high_bound); } template <typename VARIABLE_KEY> void add_additive_bounds(std::map<VARIABLE_KEY, std::pair<long, long> > & var_to_bounds, const std::map<VARIABLE_KEY, std::vector<AdditiveDependency<VARIABLE_KEY>> > & var_to_additives_using_it) { bool bounds_changed = true; while(bounds_changed) { bounds_changed = false; for(auto var_iter = var_to_additives_using_it.begin(); var_iter != var_to_additives_using_it.end(); ++var_iter) { VARIABLE_KEY var = var_iter->first; std::vector<AdditiveDependency<VARIABLE_KEY> > additives = var_iter->second; for (const AdditiveDependency<VARIABLE_KEY> & additive : additives) { if (all_bounds_calculable(additive, var_to_bounds)) { std::pair<long, long> new_var_bounds = find_bounds_from_additive(var, additive.get_inputs(), additive.get_output(), var_to_bounds); if (var_to_bounds.count(var) == 0) var_to_bounds[var] = new_var_bounds; else var_to_bounds[var] = compact_two_bounds(new_var_bounds, var_to_bounds[var]); bounds_changed = true; } } } } assert(no_vars_missing_bounds(var_to_additives_using_it, var_to_bounds)); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/BruteForceInferenceEngine.hpp
.hpp
5,918
131
#ifndef _BRUTEFORCEINFERENCEENGINE_HPP #define _BRUTEFORCEINFERENCEENGINE_HPP #include "TableDependency.hpp" template <typename VARIABLE_KEY> class BruteForceInferenceEngine; #include "../Utility/inference_utilities.hpp" #include "../Engine/InferenceEngine.hpp" #include "AdditiveDependency.hpp" #include "VariableBounds.hpp" #include <map> // forward declaration: template <typename VARIABLE_KEY> class BruteForceInferenceEngine : public InferenceEngine<VARIABLE_KEY> { protected: LabeledPMF<VARIABLE_KEY> _joint; const double _p; private: void multiply_in_additives(const std::vector<AdditiveDependency<VARIABLE_KEY> > & all_additive) { std::map<VARIABLE_KEY, std::vector<AdditiveDependency<VARIABLE_KEY>> > var_to_additives_using_it; build_variable_to_additives(all_additive, var_to_additives_using_it); std::map<VARIABLE_KEY, std::pair<long, long> > var_to_bounds = find_bounds_from_joint(_joint); add_additive_bounds(var_to_bounds, var_to_additives_using_it); for (const AdditiveDependency<VARIABLE_KEY> & additive : all_additive) { LabeledPMF<VARIABLE_KEY> lpmf = to_lpmf(additive, var_to_bounds); _joint = _joint * lpmf; } } void add_to_map(const VARIABLE_KEY & var, const AdditiveDependency<VARIABLE_KEY> & additive, std::map<VARIABLE_KEY, std::vector<AdditiveDependency<VARIABLE_KEY>> > & var_to_additives_using_it) const { auto additive_iter = var_to_additives_using_it.find(var); if (additive_iter != var_to_additives_using_it.end()) additive_iter->second.push_back(additive); else { // first time this variable has been seen in an additive dependency: var_to_additives_using_it.insert(std::pair<VARIABLE_KEY, std::vector<AdditiveDependency<VARIABLE_KEY>> >(var, {additive})); } } void build_variable_to_additives(const std::vector<AdditiveDependency<VARIABLE_KEY> > & all_additive, std::map<VARIABLE_KEY, std::vector<AdditiveDependency<VARIABLE_KEY>> > & var_to_additives_using_it) const { for (const AdditiveDependency<VARIABLE_KEY> & additive : all_additive) { for (const std::vector<VARIABLE_KEY> & vect : additive.get_inputs()) for (const VARIABLE_KEY & var : vect) add_to_map(var, additive, var_to_additives_using_it); for (const VARIABLE_KEY & var : additive.get_output()) add_to_map(var, additive, var_to_additives_using_it); } } LabeledPMF<VARIABLE_KEY> to_lpmf(const AdditiveDependency<VARIABLE_KEY> & additive, const std::map<VARIABLE_KEY, std::pair<long, long> > & var_to_bounds) const { std::vector<std::vector<VARIABLE_KEY> > inputs = additive.get_inputs(); inputs.push_back(additive.get_output()); std::vector<VARIABLE_KEY> flattened_inputs = additive.get_all_variables_used(); int num_dimensions = inputs[0].size(); LabeledPMF<VARIABLE_KEY> joint; std::vector<long> first_support; std::vector<unsigned long> result_table_dims; for(const VARIABLE_KEY & var : flattened_inputs) { std::pair<long, long> bounds; if (var_to_bounds.find(var) != var_to_bounds.end()) bounds = var_to_bounds.find(var)->second; long var_small = bounds.first; long var_large = bounds.second; first_support.push_back(var_small); result_table_dims.push_back(var_large - var_small + 1); } // Initialized with zeros: Tensor<double> result_table(result_table_dims); enumerate_apply_tensors([&first_support, num_dimensions](const_tup_t index, const int dim, double & res_val){ std::vector<long> sum_val(num_dimensions, 0); for (int current_dim = 0; current_dim < num_dimensions; ++current_dim) for(int i = current_dim; i < dim-num_dimensions; i += num_dimensions) sum_val[current_dim] += index[i] + first_support [i]; bool is_additive = true; for (int i = 0; i < num_dimensions; ++i) if (sum_val[i] != long(index[dim-num_dimensions+i] + first_support[dim-num_dimensions+i])) is_additive = false; if (is_additive) res_val = 1.0; }, result_table.data_shape(), result_table); LabeledPMF<VARIABLE_KEY> table_dependency(flattened_inputs, PMF(first_support, result_table)); table_dependency.reset_log_normalization_constant(); return table_dependency; } public: BruteForceInferenceEngine(const std::vector<TableDependency<VARIABLE_KEY> > & all_tables, const std::vector<AdditiveDependency<VARIABLE_KEY> > & all_additive, double p): _p(p) { // Note: instead of !=, could check fabs(table.p - _p) > epsilon for (const TableDependency<VARIABLE_KEY> & table : all_tables) if (table.p != _p) { std::cerr << "Cannot do brute force on non-homogeneous p norms" << std::endl; assert(false); } for (const AdditiveDependency<VARIABLE_KEY> & additive : all_additive) if (additive.p != _p) { std::cerr << "Cannot do brute force on non-homogeneous p norms" << std::endl; assert(false); } // Note: This could be performed more efficiently by first // allocating the result table (using the union of all variables // and the intersection of their supports) and then performing a // single product over all distributions simultaneously. for (const TableDependency<VARIABLE_KEY> & table : all_tables) _joint = _joint * table.labeled_pmf(); multiply_in_additives(all_additive); } std::vector<LabeledPMF<VARIABLE_KEY> > estimate_posteriors(const std::vector<std::vector<VARIABLE_KEY> > & joint_distributions_to_retrieve) { std::vector<LabeledPMF<VARIABLE_KEY> > results; for (const std::vector<VARIABLE_KEY> & ordered_vars : joint_distributions_to_retrieve) results.push_back(_joint.marginal(ordered_vars, _p)); return results; } // Note: uses p=1: double log_normalization_constant() { return _joint.log_normalization_constant(); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/PseudoAdditiveDependency.hpp
.hpp
4,759
122
#ifndef _PSEUDOADDITIVEDEPENDENCY_HPP #define _PSEUDOADDITIVEDEPENDENCY_HPP #include <map> #include <limits> #include "../Engine/ConvolutionTreeMessagePasser.hpp" #include "TableDependency.hpp" // PseudoAdditiveDependency behaves similar to AdditiveDependency, but // in contrast, it works with brute force, creating a joint // PMF. Because it creates this PMF, it is constructed with tables, // which it uses to uncover the support of each variable can // obtain. These variable supports (which are the intersection of // supports of the tables provided) determine the supports of each // axis of the table. PseudoAdditiveDependency is SLOW. It is intended // for testing and debugging. // Note: This implementation is not lighting fast, and regardless, // AdditiveDependency will be much more efficient (this creates a // table for the additive dependency). It is to be used for testing. template <typename VARIABLE_KEY> class PseudoAdditiveDependency : public Dependency<VARIABLE_KEY>, public PNormMixin { protected: std::vector<std::vector<VARIABLE_KEY> > _inputs; std::vector<VARIABLE_KEY> _output; std::map<VARIABLE_KEY, std::array<long, 2> > _var_to_min_and_max; // Check if outputs are sums of inputs: bool is_additive(std::map<VARIABLE_KEY, long> var_to_outcome) const { for (unsigned int i=0; i<_output.size(); ++i) { const VARIABLE_KEY & var = _output[i]; long res = var_to_outcome[var]; long tot = 0; for (unsigned long k=0; k<_inputs.size(); ++k) tot += var_to_outcome[ _inputs[k][i] ]; if ( res != tot ) return false; } return true; } public: PseudoAdditiveDependency(const std::vector<std::vector<VARIABLE_KEY> > & inputs, const std::vector<VARIABLE_KEY> & output, const std::vector<TableDependency<VARIABLE_KEY> > & existing_tables, const double p_param): PNormMixin(p_param), _inputs(inputs), _output(output) { #ifdef ENGINE_CHECK for (const std::vector<VARIABLE_KEY> & in : _inputs) assert(in.size() == output.size() && "Dimension of each tuple in additive dependency must equal dimension of output tuple"); #endif // For all variables in the additive dependency, initialize // minimum and maximum values: for (const std::vector<VARIABLE_KEY> & in : inputs) for (const VARIABLE_KEY & var : in) { auto iter = _var_to_min_and_max.find(var); if (iter == _var_to_min_and_max.end()) _var_to_min_and_max[var] = {{std::numeric_limits<long>::min(), std::numeric_limits<long>::max()}}; } for (const VARIABLE_KEY & var : output) { auto iter = _var_to_min_and_max.find(var); if (iter == _var_to_min_and_max.end()) _var_to_min_and_max[var] = {{std::numeric_limits<long>::min(), std::numeric_limits<long>::max()}}; } // Find the bounding box for all variables in the additive // dependency: for (const TableDependency<VARIABLE_KEY> & tab_dep : existing_tables) { auto lpmf = tab_dep.labeled_pmf(); for (unsigned int i=0; i<lpmf.dimension(); ++i) { const VARIABLE_KEY & var = lpmf.ordered_variables()[i]; long min_val = lpmf.pmf().first_support()[i]; long max_val = min_val + lpmf.pmf().table().view_shape()[i]; _var_to_min_and_max[var][0] = std::max(_var_to_min_and_max[var][0], min_val); _var_to_min_and_max[var][1] = std::min(_var_to_min_and_max[var][1], max_val); } } } LabeledPMF<VARIABLE_KEY> to_labeled_pmf() const { std::vector<VARIABLE_KEY> ordered_variables(_var_to_min_and_max.size()); Vector<long> first_support(_var_to_min_and_max.size()); Vector<unsigned long> shape(_var_to_min_and_max.size()); unsigned long i=0; for (const auto & var_min_max : _var_to_min_and_max) { ordered_variables[i] = var_min_max.first; first_support[i] = var_min_max.second[0]; shape[i] = var_min_max.second[1] - var_min_max.second[0] + 1; ++i; } Tensor<double> ten(shape); std::map<VARIABLE_KEY, long> var_to_outcome; enumerate_apply_tensors([this, &ordered_variables, &var_to_outcome, &first_support](const_tup_t counter, const unsigned char dim, double & val){ for (unsigned int i=0; i<dim; ++i) var_to_outcome[ordered_variables[i]] = first_support[i] + counter[i]; if (is_additive(var_to_outcome)) val = 1.0; }, ten.data_shape(), ten); PMF pmf(first_support, ten); return LabeledPMF<VARIABLE_KEY>(ordered_variables, pmf); } TableDependency<VARIABLE_KEY> to_table_dependency() const { return TableDependency<VARIABLE_KEY>(to_labeled_pmf(), this->p); } virtual HUGINMessagePasser<VARIABLE_KEY>* create_message_passer(InferenceGraphBuilder<VARIABLE_KEY> & igb) const { return to_table_dependency().create_message_passer(igb); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/BetheInferenceGraphBuilder.hpp
.hpp
5,573
127
#ifndef _BETHEINFERENCEGRAPHBUILDER_HPP #define _BETHEINFERENCEGRAPHBUILDER_HPP #include "InferenceGraphBuilder.hpp" // Note: BetheInferenceGraphBuilder is useful for medium-sized, // densely connected graphs. For large chain graphs, simply build an // HMM or the HMM-like tree decomposition (no automated builder for // that yet). On those graphs, Bethe will perform poorly, and may even // not visit all edges. template <typename VARIABLE_KEY> class BetheInferenceGraphBuilder : public InferenceGraphBuilder<VARIABLE_KEY> { protected: void add_singleton_hyperedges_for_hugins() { // make a copy so that hyperedges can be inserted as you go: std::vector<MessagePasser<VARIABLE_KEY>* > mps = this->_message_passers; for (MessagePasser<VARIABLE_KEY>*mp : mps) { HUGINMessagePasser<VARIABLE_KEY>*hmp = dynamic_cast<HUGINMessagePasser<VARIABLE_KEY>* >(mp); if (hmp != NULL) { for (const VARIABLE_KEY & var : hmp->joint_posterior().ordered_variables()) { Hyperedge<VARIABLE_KEY>*he = this->create_hyperedge(); hmp->bind_to(he, new std::vector<VARIABLE_KEY>{var}); } } } } void merge_hyperedges_with_identical_incident_variable_sets() { // Note that the inner unordered_set could be changed to a vector // for speedup; you would simply check if the last element in the // vector was he, and if not, push_back. This exploits the fact // that each hyperedge is considered one at a time, and so // multiple insertions can only happen when it is inserted back to // back. std::unordered_map<std::unordered_set<VARIABLE_KEY>, std::unordered_set<Hyperedge<VARIABLE_KEY>* >, SetHash<VARIABLE_KEY> > var_sets_to_hyperedges; for (MessagePasser<VARIABLE_KEY>*mp : this->_message_passers) { Hyperedge<VARIABLE_KEY>*he = dynamic_cast<Hyperedge<VARIABLE_KEY>* >(mp); if (he != NULL) { std::unordered_set<VARIABLE_KEY> vars_used = he->variables_used_by_incident_edges(); auto iter = var_sets_to_hyperedges.find(vars_used); if (iter == var_sets_to_hyperedges.end()) var_sets_to_hyperedges[vars_used] = std::unordered_set<Hyperedge<VARIABLE_KEY>* >(); var_sets_to_hyperedges[vars_used].insert(he); } } std::vector<std::vector<Hyperedge<VARIABLE_KEY>* > > hes_to_merge; for (const std::pair<std::unordered_set<VARIABLE_KEY>, std::unordered_set<Hyperedge<VARIABLE_KEY>* > > & vars_and_hes : var_sets_to_hyperedges) { const std::unordered_set<Hyperedge<VARIABLE_KEY>* > & he_set = vars_and_hes.second; std::vector<Hyperedge<VARIABLE_KEY>* > collection_to_merge(he_set.begin(), he_set.end()); hes_to_merge.push_back(collection_to_merge); } this->merge_hyperedges(hes_to_merge); } void bind_singletons_to_superset_hyperedges() { std::unordered_map<VARIABLE_KEY, std::unordered_set<Hyperedge<VARIABLE_KEY>* > > vars_to_hyperedges; for (MessagePasser<VARIABLE_KEY>*mp : this->_message_passers) { Hyperedge<VARIABLE_KEY>*he = dynamic_cast<Hyperedge<VARIABLE_KEY>* >(mp); if (he != NULL) { for (const VARIABLE_KEY & var : he->variables_used_by_incident_edges()) { auto iter = vars_to_hyperedges.find(var); if (iter == vars_to_hyperedges.end()) vars_to_hyperedges[var] = std::unordered_set<Hyperedge<VARIABLE_KEY>* >(); vars_to_hyperedges[var].insert(he); } } } for (const std::pair<VARIABLE_KEY, std::unordered_set<Hyperedge<VARIABLE_KEY>* > > & var_and_he_set : vars_to_hyperedges) { const VARIABLE_KEY & var = var_and_he_set.first; const std::unordered_set<Hyperedge<VARIABLE_KEY>* > & he_set = var_and_he_set.second; // singleton_he should be the only surviving hyperedge that // contains the singleton set of this variable (otherwise it // would have been merged above): bool singleton_found = false; Hyperedge<VARIABLE_KEY>*singleton_he = NULL; for (Hyperedge<VARIABLE_KEY>*singleton_he_local : he_set) if (singleton_he_local->variables_used_by_incident_edges().size() == 1) { singleton_he = singleton_he_local; singleton_found = true; break; } // Hyperedge with singleton is not found, but there are // higher-order hyperedges using that variable. E.g., one // Dependency could create {A,B,C} hyperedge and another could // create {A,B} hyperedge. // Therefore, if {A} and {B} hyperedges don't exist, then they // should be created so that {A,B,C} and {A,B} can be connected // through them. if (! singleton_found && he_set.size() > 1) singleton_he = this->create_hyperedge(); if (singleton_he == NULL) continue; // for all he in he_set, the ones with >1 variables should be // bound to the canonical singleton for that variable for (Hyperedge<VARIABLE_KEY>*he : he_set) if (he->variables_used_by_incident_edges().size() > 1) { singleton_he->bind_to(he, new std::vector<VARIABLE_KEY>{var}); } } } void construct_graph_connections() { // 1. Add singleton hyperedges for all vars in HUGINMessagePasser types with priors: add_singleton_hyperedges_for_hugins(); // 2. Merge all hyperedges that use identical variable sets (these // hyperedges are either singletons constructed above or were // constructed by the Dependency types; in either case, they are // atomic and cannot be broken down). merge_hyperedges_with_identical_incident_variable_sets(); // 3. Bind the singleton hyperedges to higher-order hyperedges // that are supersets: bind_singletons_to_superset_hyperedges(); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/ConstantMultiplierDependency.hpp
.hpp
3,219
71
#ifndef _CONSTANTMULTIPLIERDEPENDENCY_HPP #define _CONSTANTMULTIPLIERDEPENDENCY_HPP #include "../Engine/ConstantMultiplierMessagePasser.hpp" #include "Dependency.hpp" // For building dependencies of the form {Y0,Y1,...} = {X0,X1,...} * {s0,s1,...}. // dithering_sigma is used when the outcomes map to floating point // values. Then, that mass is distributed between the two neighboring // integer bins using a Gaussian with std. deviation dithering_sigma. // Interpolation is used when multiplying a factor >1. For example a // distribution with integer support [0,10] scaled by 3 should give a // distribution with support {0, 3, 6, ..., 30}. However, when a // discrete distribution is being used as a proxy for a continuous // distribution, then each bin is not simply a point value, but a // distribution in [0,1), [1,2), ..., which scaled by 3 will yield // [0,3), [3,6), ... For this reason, ConstantMultiplierDependency // allows the option to interpolate when scaling (whether forwards or // backwards). If the input distribution is truly discrete (not a // proxy for a continuous distribution), then setting // interpolate_scaled=false is appropriate. If the output distribution // is truly discrete, then setting interpolate_unscaled=false is // appropriate. Note that in the future, these could be handled by the // distributions themselves (by specifying continuous vs. discrete // distribution types). template <typename VARIABLE_KEY> class ConstantMultiplierDependency : public Dependency<VARIABLE_KEY> { protected: std::vector<VARIABLE_KEY> _input; std::vector<VARIABLE_KEY> _output; Vector<double> _scale; bool _interpolate_scaled, _interpolate_unscaled; double _dithering_sigma; public: ConstantMultiplierDependency(const std::vector<VARIABLE_KEY> & input, const std::vector<VARIABLE_KEY> & output, Vector<double> scale, bool interpolate_scaled, bool interpolate_unscaled, double dithering_sigma): _input(input), _output(output), _scale(scale), _interpolate_scaled(interpolate_scaled), _interpolate_unscaled(interpolate_unscaled), _dithering_sigma(dithering_sigma) { #ifdef ENGINE_CHECK assert(input.size() == output.size() && input.size() == scale.size() && "Dimension of input, output, and scale in constant multiplier dependency must match"); #endif } virtual ConstantMultiplierMessagePasser<VARIABLE_KEY>* create_message_passer(InferenceGraphBuilder<VARIABLE_KEY> & igb) const { HUGINMessagePasser<VARIABLE_KEY>* hyperedge_in = igb.create_hyperedge(); HUGINMessagePasser<VARIABLE_KEY>* hyperedge_out = igb.create_hyperedge(); std::vector<VARIABLE_KEY>* edge_label_in = new std::vector<VARIABLE_KEY>(_input); std::vector<VARIABLE_KEY>* edge_label_out = new std::vector<VARIABLE_KEY>(_output); return new ConstantMultiplierMessagePasser<VARIABLE_KEY>(hyperedge_in, edge_label_in, hyperedge_out, edge_label_out, _scale, _interpolate_scaled, _interpolate_unscaled, _dithering_sigma); } virtual std::vector<VARIABLE_KEY> get_all_variables_used() const { std::vector<VARIABLE_KEY> result = _input; for (const VARIABLE_KEY & var : _output) result.push_back(var); return result; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/InferenceGraphBuilder.hpp
.hpp
2,856
87
#ifndef _INFERENCEGRAPHBUILDER_HPP #define _INFERENCEGRAPHBUILDER_HPP #include "../Engine/InferenceGraph.hpp" #include "../Engine/Hyperedge.hpp" #include "../Engine/SetHash.hpp" #include "Dependency.hpp" template <typename VARIABLE_KEY> class InferenceGraphBuilder { private: bool _has_created_graph; protected: std::vector<MessagePasser<VARIABLE_KEY>* > _message_passers; // To be defined by derived types; e.g., Bethe construction defines // one connection scheme, there are multiple schemes for Kikuchi // construction, etc. virtual void construct_graph_connections() = 0; public: InferenceGraphBuilder(): _has_created_graph(false) { } virtual ~InferenceGraphBuilder() { if ( ! _has_created_graph ) { // TODO: If no graph has been created, then the allocated memory // needs to be destroyed. assert(false && "InferenceGraphBuilder needs to create a graph or else it leaks memory"); } } Hyperedge<VARIABLE_KEY>* create_hyperedge() { Hyperedge<VARIABLE_KEY>* hyperedge = new Hyperedge<VARIABLE_KEY>(); _message_passers.push_back(hyperedge); return hyperedge; } // Arguments are a collection of vectors of hyperedges to merge. void merge_hyperedges(const std::vector<std::vector<Hyperedge<VARIABLE_KEY>* > > & hes_to_merge) { std::vector<MessagePasser<VARIABLE_KEY>* > new_message_passers; // add all non-hyperedge MessagePasser types: for (MessagePasser<VARIABLE_KEY>*mp : _message_passers) { Hyperedge<VARIABLE_KEY>* he = dynamic_cast<Hyperedge<VARIABLE_KEY>* >(mp); if (he == NULL) new_message_passers.push_back(mp); } // Use the first Hyperedge in the collection of each as the // Hyperedge that will be kept (others will be merged into it) for (const std::vector<Hyperedge<VARIABLE_KEY>* > & he_vec : hes_to_merge) { Hyperedge<VARIABLE_KEY>* he_to_keep = he_vec[0]; new_message_passers.push_back(he_to_keep); for (unsigned long i=1; i<he_vec.size(); ++i) he_to_keep->absorb_hyperedge(he_vec[i]); } _message_passers = new_message_passers; } const std::vector<MessagePasser<VARIABLE_KEY>* > & message_passers() const { return _message_passers; } void insert_dependency(const Dependency<VARIABLE_KEY> & dep) { MessagePasser<VARIABLE_KEY>*mp = dep.create_message_passer(*this); _message_passers.push_back(mp); } InferenceGraph<VARIABLE_KEY> to_graph() { // To prevent two InferenceGraph destructors from deleting the // same memory multiple times: assert(! _has_created_graph && "Each InferenceGraphBuilder should only be used to create a single graph; for a copy of the graph, it should be copied"); construct_graph_connections(); _has_created_graph = true; return InferenceGraph<VARIABLE_KEY>(std::move(_message_passers)); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Evergreen/Dependency.hpp
.hpp
963
27
#ifndef _DEPENDENCY_HPP #define _DEPENDENCY_HPP template <typename VARIABLE_KEY> class InferenceGraphBuilder; template <typename VARIABLE_KEY> class Dependency { public: // The idea here is that dependencies create message passers and // bind them to context free message passers through which they // reach the other message passers in the graph. This allows context // to be respected, but simplifies the job for building a graph // (which can then be performed solely by linking context free // message passers to each other where necessary). Thus, in derived // classes, create_message_passer should create a message passer of // the appropriate type and create and bind it to the necessary // hyperedges. virtual MessagePasser<VARIABLE_KEY>* create_message_passer(InferenceGraphBuilder<VARIABLE_KEY> & igb) const = 0; //virtual std::vector<VARIABLE_KEY> get_all_variables_used() const = 0; virtual ~Dependency() {} }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/L1Regularization.hpp
.hpp
2,404
57
#ifndef _L1REGULARIZATION_HPP #define _L1REGULARIZATION_HPP #include "to_string.hpp" // Note: This is for regularizing 1D variables only thus far; it could // be generalized (but regularizing with multidimensional indicator // variables would only be interesting if the likelihood function on // the sum of the indicators has a lot of covariation between axes). template <typename T> class L1Regularization { public: static void apply(InferenceGraphBuilder<T> & igb, const std::vector<T> & vars_to_regularize, const std::vector<T> & indicator_vars, const LabeledPMF<T> & sum_of_indicators, double p, unsigned long prior_maximum_copies_of_element) { assert(vars_to_regularize.size() == indicator_vars.size() && "Variables and indicator variables should be paired and in order"); // Insert the indicator variables: for (unsigned long i=0; i<vars_to_regularize.size(); ++i) { const T & var = vars_to_regularize[i]; const T & indicator_var = indicator_vars[i]; igb.insert_dependency( make_uniform_indicator_for_nonneg_var(var, indicator_var, prior_maximum_copies_of_element, p) ); } // Insert the additive dependency: // Build vector of singletons for additive dependency: std::vector<std::vector<T> > indicator_singletons(indicator_vars.size()); for (unsigned long i=0; i<indicator_vars.size(); ++i) indicator_singletons[i] = {indicator_vars[i]}; igb.insert_dependency( AdditiveDependency<T>(indicator_singletons, sum_of_indicators.ordered_variables(), p) ); // Insert the distribution on the sum of indicators: igb.insert_dependency(TableDependency<T>(sum_of_indicators, p)); } // Make a 2D LabeledPMF that is 2 x max_val. Where indicator static TableDependency<T> make_uniform_indicator_for_nonneg_var(const T & var, const T & indicator_var, unsigned long max_val, double p) { Tensor<double> ten({max_val+1, 2}); unsigned long ten_size = ten.flat_size(); // if number of element != 0 then the indicator i_e = 1 is 100% for (unsigned long i=0; i<ten_size; ++i) { ten[i] = 0.0; ten[++i] = 1.0; } // if number of element = 0 then the indicator i_e = 0 is 100% ten.flat()[0] = 1.0; ten.flat()[1] = 0; // Create uniform pmf with indiciator. PMF pmf( {0L, 0L}, ten ); return TableDependency<T>(LabeledPMF<T>({var, indicator_var}, pmf), p); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/to_string.hpp
.hpp
240
16
#ifndef _TO_STRING_HPP #define _TO_STRING_HPP #include <string> #include <sstream> template <typename T> std::string to_string(const T & rhs) { std::string res; std::ostringstream ost(res); ost << rhs; return ost.str(); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/Clock.hpp
.hpp
657
30
#ifndef _CLOCK_HPP #define _CLOCK_HPP #include <iostream> #include <iomanip> #include <chrono> class Clock { protected: std::chrono::steady_clock::time_point startTime; public: Clock() { tick(); } void tick() { startTime = std::chrono::steady_clock::now(); } float tock() { std::chrono::steady_clock::time_point endTime = std::chrono::steady_clock::now();; return float(std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count()) / 1e6f; } // Print elapsed time with newline void ptock() { float elapsed = tock(); std::cout << "Took " << elapsed << " seconds" << std::endl; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/sign.hpp
.hpp
125
10
#ifndef _SIGN_HPP #define _SIGN_HPP template <typename T> int sign(T val) { return (val > T(0)) - (val < T(0)); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/shuffled_sequence.hpp
.hpp
375
17
#ifndef _SHUFFLED_SEQUENCE_HPP #define _SHUFFLED_SEQUENCE_HPP inline std::vector<unsigned long> shuffled_sequence(const unsigned long N) { std::vector<unsigned long> result(N); for (unsigned long i=0; i<N; ++i) result[i] = i; // Swap with random index: for (unsigned long i=0; i<N; ++i) std::swap(result[i], result[rand() % N]); return result; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/ComparableMixin.hpp
.hpp
445
23
#ifndef _COMPARABLEMIXIN_H #define _COMPARABLEMIXIN_H template <typename T> class ComparableMixin { public: friend bool operator >(T lhs, T rhs) { return !( lhs < rhs || lhs == rhs ); } friend bool operator !=(T lhs, T rhs) { return !( lhs == rhs ); } friend bool operator >=(T lhs, T rhs) { return lhs > rhs || lhs == rhs; } friend bool operator <=(T lhs, T rhs) { return lhs < rhs || lhs == rhs; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/graph_to_dot.hpp
.hpp
4,655
156
#ifndef _GRAPH_TO_DOT_HPP #define _GRAPH_TO_DOT_HPP #include <fstream> template <typename VARIABLE_KEY> void graph_to_dot(const InferenceGraph<VARIABLE_KEY> & ig, std::ostream & os) { auto print_map = [&os](const std::map<std::string, std::string> & properties) { unsigned int i=0; os << "[ "; for (const std::pair<std::string, std::string> & prop_and_val : properties) { os << prop_and_val.first << "=\"" << prop_and_val.second << "\""; if (i != properties.size()-1) os << ", "; ++i; } os << " ];" << std::endl; }; os << "graph {" << std::endl; const double small=0.025; // Nodes: for (MessagePasser<VARIABLE_KEY>*mp : ig.message_passers) { os << "\t\"" << mp << "\" "; std::map<std::string, std::string> node_properties; // default color: node_properties["color"] = "gray"; node_properties["style"] = "filled"; const HUGINMessagePasser<VARIABLE_KEY>* hmp = dynamic_cast<const HUGINMessagePasser<VARIABLE_KEY>* >(mp); if (hmp != NULL) { // HUGIN: node_properties["shape"] = "box"; node_properties["color"] = "cyan"; node_properties["style"] = "filled"; const HUGINMessagePasser<VARIABLE_KEY>* he = dynamic_cast<const Hyperedge<VARIABLE_KEY>* >(hmp); if (he != NULL) { // Hyperedge: node_properties["style"] = "filled"; node_properties["shape"] = "square"; node_properties["color"] = "red"; node_properties["width"] = to_string(small); node_properties["height"] = to_string(small); } else { // Not Hyperedge: if (hmp->joint_posterior().dimension() > 0) { // HUGIN prior: const std::vector<std::string> & vars = hmp->joint_posterior().ordered_variables(); for (unsigned int i=0; i<vars.size(); ++i) { node_properties["label"] += to_string(vars[i]); if (i != vars.size()-1) node_properties["label"] += ","; } } } } else { // Not HUGIN: const ConvolutionTreeMessagePasser<VARIABLE_KEY>* ctmp = dynamic_cast<const ConvolutionTreeMessagePasser<VARIABLE_KEY>* >(mp); if (ctmp != NULL) { // Convolution tree node_properties["color"] = "green"; node_properties["shape"] = "triangle"; node_properties["width"] = to_string(small); node_properties["height"] = to_string(small); } else { const ConstantMultiplierMessagePasser<VARIABLE_KEY>* cmmp = dynamic_cast<const ConstantMultiplierMessagePasser<VARIABLE_KEY>* >(mp); if (cmmp != NULL) node_properties["color"] = "violet"; node_properties["shape"] = "diamond"; node_properties["width"] = to_string(small); node_properties["height"] = to_string(small); node_properties["label"] = ""; const Vector<double> & scale = cmmp->scale(); for (unsigned int i=0; i<scale.size(); ++i) { node_properties["label"] += to_string(scale[i]); if (i != scale.size()-1) node_properties["label"] += ","; } } } if (node_properties.find("label") == node_properties.end()) // Space is necessary for blank label in order to permit us to // height and width node_properties["label"] = " "; else node_properties["fontsize"] = "48"; print_map(node_properties); } os << std::endl; std::set<Edge<VARIABLE_KEY>* > visited_edges; // Edges: for (MessagePasser<VARIABLE_KEY>*mp : ig.message_passers) { for (unsigned long k=0; k<mp->number_edges(); ++k) { Edge<VARIABLE_KEY>*edge = mp->get_edge_out(k); if (visited_edges.find(edge) != visited_edges.end()) continue; visited_edges.insert(edge); visited_edges.insert(edge->get_opposite_edge_ptr()); std::map<std::string, std::string> edge_properties; edge_properties["fontsize"] = "32"; os << "\t\"" << edge->source << "\" -- \"" << edge->dest << "\""; for (unsigned int i=0; i<edge->variables_ptr->size(); ++i) { edge_properties["label"] += to_string( (*edge->variables_ptr)[i] ); if (i != edge->variables_ptr->size()-1) edge_properties["label"] += ","; } /* // Edge color: // Color edges red when they've passed: if (edge->dest->edge_received(edge->dest_edge_index)) edge_properties["color"] = "red"; // Color edges green when they are elligible to pass: else if (mp->ready_to_send_message_ab_initio(k)) edge_properties["color"] = "green"; */ print_map(edge_properties); } } os << "}" << std::endl; } template <typename VARIABLE_KEY> void write_graph_to_dot_file(const InferenceGraph<VARIABLE_KEY> & ig, const std::string & fname) { std::ofstream fout(fname); graph_to_dot(ig, fout); fout.close(); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/draw_dot.py
.py
944
33
import pygraphviz as pgv import sys def main(argv): if len(argv) not in (2,3,4,5): print('Usage: draw_dot.py <graph .dot> <output image file> [layout, default is neato; optionally multiple layouts separated by ","] [overlap mode {scale, false}, default is false] [label edges {0,1}]') else: layouts = ['neato'] if len(argv) >= 3: layouts = argv[2].split(',') G = pgv.AGraph(argv[0]) overlap='false' if len(argv) >= 4: overlap=argv[3] label_edges=True if len(argv) >= 5: label_edges = bool(int(argv[4])) if not label_edges: for e in G.edges(): e.attr['label'] = ' ' for lo in layouts[:-1]: G.layout(prog=lo) G.layout(prog=layouts[-1], args='-Goverlap=' + overlap + ' -Gsplines=true') G.draw(argv[1]) if __name__ == "__main__": main(sys.argv[1:])
Python
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/LogDouble.hpp
.hpp
5,826
201
#ifndef _LOGDOUBLE_H #define _LOGDOUBLE_H #include <math.h> #include <limits> #include <iostream> #include <assert.h> #include "ComparableMixin.hpp" #include "sign.hpp" // TODO: test for compatibility with Vector<LogDouble>, which will // initialize sign to zero, log_absolute_value to zero. class LogDouble : public ComparableMixin<LogDouble> { private: signed char _sign; double _log_absolute_value; static double logaddexp(double log_a, double log_b) { // returns the log( exp(log_a) + exp(log_b) ) // if both are infinite, taking the difference will result in a NaN; // simply return infinity if (isinf(log_a) && isinf(log_b)) return log_a; if ( log_a > log_b ) return logaddexp_first_larger(log_a, log_b); else return logaddexp_first_larger(log_b, log_a); } static double logaddexp_first_larger(double log_a, double log_b) { // Note: this check is for internal testing, and can be removed for greater speed assert( log_a >= log_b ); if ( log_a == -std::numeric_limits<double>::infinity() ) return log_b; return log1p( exp(log_b-log_a) ) + log_a; } static double logsubabsexp(double log_a, double log_b) { // returns the log( abs( exp(log_a) - exp(log_b) ) ) if ( log_a > log_b ) return logsubexp_first_larger(log_a, log_b); else return logsubexp_first_larger(log_b, log_a); } static double logsubexp_first_larger(double log_a, double log_b) { // Note: this check is for internal testing, and can be removed for greater speed assert(log_a >= log_b); if ( log_a == -std::numeric_limits<double>::infinity() ) return log_b; return log1p( -exp(log_b-log_a) ) + log_a; } public: LogDouble() { _log_absolute_value = std::numeric_limits<double>::quiet_NaN(); _sign = 1; } explicit LogDouble(double x) { if ( x == 0.0 ) _sign = 1; else _sign = (signed char) ::sign(x); _log_absolute_value = log(fabs(x)); } static LogDouble create_from_log_absolute_value(double log_absolute_value_param) { LogDouble result; result._log_absolute_value = log_absolute_value_param; result._sign = 1; return result; } // +=, -=, *=, /= const LogDouble & operator +=(const LogDouble & rhs) { // if the signs are the same, simply use logaddexp if (_sign == rhs._sign) _log_absolute_value = logaddexp(_log_absolute_value, rhs._log_absolute_value); else { double new_log_absolute_value = logsubabsexp(_log_absolute_value, rhs._log_absolute_value); if ( _log_absolute_value < rhs._log_absolute_value ) // *this "loses" _sign *= -1; _log_absolute_value = new_log_absolute_value; } return *this; } const LogDouble & operator -=(const LogDouble & rhs) { // if the signs are different, they will be the same after negation if (_sign != rhs._sign) _log_absolute_value = logaddexp(_log_absolute_value, rhs._log_absolute_value); else { double new_log_absolute_value = logsubabsexp(_log_absolute_value, rhs._log_absolute_value); if ( _log_absolute_value < rhs._log_absolute_value ) // *this "loses" _sign *= -1; _log_absolute_value = new_log_absolute_value; } return *this; } const LogDouble & operator *=(const LogDouble & rhs) { _sign *= rhs._sign; _log_absolute_value += rhs._log_absolute_value; return *this; } const LogDouble & operator /=(const LogDouble & rhs) { _sign *= rhs._sign; _log_absolute_value -= rhs._log_absolute_value; return *this; } LogDouble operator -() const { LogDouble result(*this); result._sign = -result._sign; return result; } explicit operator double() const { return _sign * exp(_log_absolute_value); } double log_absolute_value() const { return _log_absolute_value; } double sign() const { return _sign; } bool operator <(LogDouble rhs) const { return (_sign < rhs._sign) || ( _sign == rhs._sign && ( (_sign == 1 && _log_absolute_value < rhs._log_absolute_value) || (_sign == -1 && _log_absolute_value > rhs._log_absolute_value) ) ); } bool operator ==(LogDouble rhs) const { // magnitudes must be equal, and if nonzero, signs must be equal (if // it's zero, disregard sign) return _log_absolute_value == rhs._log_absolute_value && (_sign == rhs._sign || (_log_absolute_value == -std::numeric_limits<double>::infinity() ) ); } static bool is_nan(LogDouble x) { return isnan(double(x)); } static bool is_inf(LogDouble x) { return isinf(x.log_absolute_value()); } friend LogDouble exp(LogDouble rhs) { rhs._log_absolute_value = double(rhs); rhs._sign = 1; return rhs; } friend std::ostream & operator <<(std::ostream & os, LogDouble rhs) { if (rhs._sign == -1) os << '-'; os << "exp(" << rhs._log_absolute_value << ")~" << double(rhs); return os; } }; LogDouble operator +(LogDouble lhs, LogDouble rhs) { lhs += rhs; return lhs; } LogDouble operator -(LogDouble lhs, LogDouble rhs) { lhs -= rhs; return lhs; } LogDouble operator *(LogDouble lhs, LogDouble rhs) { lhs *= rhs; return lhs; } LogDouble operator /(LogDouble lhs, LogDouble rhs) { lhs /= rhs; return lhs; } LogDouble pow(LogDouble lhs, LogDouble rhs) { assert(lhs.sign() >= 0); // for all x, x^0 --> 1 if ( rhs.log_absolute_value() == -std::numeric_limits<double>::infinity() ) return LogDouble(1.0); // for all y>0 (guaranteed by previous check), 0^y --> 0 if ( lhs.log_absolute_value() == -std::numeric_limits<double>::infinity() ) return LogDouble(0.0); return LogDouble::create_from_log_absolute_value(double(rhs) * lhs.log_absolute_value()); } LogDouble fabs(LogDouble x) { return LogDouble::create_from_log_absolute_value(x.log_absolute_value()); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/draw_dot_interactive.py
.py
391
18
import pygraphviz as pgv import sys import pylab as P #P.ion() def main(argv): if len(argv) != 2: print('Usage: draw_dot.py <graph .dot> <graph .png output>') else: G = pgv.AGraph(argv[0]) G.layout(prog='circo') G.layout(prog='neato', args='-Goverlap=scale -Gsplines=true') G.draw(argv[1]) if __name__ == "__main__": main(sys.argv[1:])
Python
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/vector_ostream.hpp
.hpp
359
21
#ifndef _VECTOR_OSTREAM_HPP #define _VECTOR_OSTREAM_HPP #include <iostream> #include <vector> template <typename T> std::ostream & operator <<(std::ostream & os, std::vector<T> & rhs) { os << "{"; for (unsigned long i=0; i<rhs.size(); ++i) { os << rhs[i]; if (i+1 != rhs.size()) { os << ", "; } } os << "}"; return os; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Utility/inference_utilities.hpp
.hpp
5,536
159
#ifndef _INFERENCE_UTILITIES_HPP #define _INFERENCE_UTILITIES_HPP #include "Clock.hpp" #include <iostream> #include <algorithm> template<template <typename, typename...> class CONTAINER, typename T, typename ...OTHER_ARGS> std::vector<std::vector<T> > make_singletons(const CONTAINER<T, OTHER_ARGS...> & var_container) { std::vector<std::vector<T> > result; for (const T & t : var_container) result.push_back({t}); return result; } template <typename T> std::vector<T> flatten(const std::vector<std::vector<T> > & container) { std::vector<T> result; for (const std::vector<T> & row : container) for (const T & var : row) result.push_back(var); return result; } template <typename T> std::vector<T> from_singletons(const std::vector<std::vector<T> > & singletons) { for (const std::vector<T> & t : singletons) assert( t.size() == 1 ); return flatten(singletons); } template <typename T> void estimate_and_print_posteriors(BruteForceInferenceEngine<T> & bf, const std::vector<std::vector<T> > & singletons){ Clock c; auto result = bf.estimate_posteriors(singletons); c.ptock(); for (auto res : result) std::cout << res << std::endl; } template <typename T> void estimate_and_print_posteriors(BeliefPropagationInferenceEngine<T> & bpie, const std::vector<std::vector<T> > & singletons){ Clock c; auto result = bpie.estimate_posteriors(singletons); c.ptock(); for (auto res : result) std::cout << res << std::endl; } template <typename T> LabeledPMF<T> make_nonneg_uniform(const T & var_name, unsigned long max_val) { Tensor<double> ten({max_val+1}); ten.flat().fill(1.0); PMF pmf( {0L}, ten ); return LabeledPMF<T>({var_name}, pmf); } inline double gaussian_density(double x, const double mu, const double sigma){ double var = sigma*sigma; double dev = (x - mu); return ( exp(-(dev*dev) / (2*var)) / sigma ) / (sigma * sqrt(2*M_PI)); } inline double inverse_standard_norm_cdf(const double p) { assert(p >= 0.5); return 5.5556*(1-pow((1-p)/p, 0.1186)); } template <typename T> TableDependency<T> table_dependency_by_gaussian(const T & label, const Vector<long> & support, double goal, const double p, const double sd){ Tensor<double> pmf({support.size()}); for(unsigned int i=0; i<support.size(); ++i) pmf[i] = gaussian_density(support[i], goal, sd); TableDependency<T> td(LabeledPMF<T>({label}, PMF({(long)floor(support[0])}, pmf)), p); return td; } template <typename T> LabeledPMF<T> make_gaussian(const T & label, double mu, const double sigma, const double epsilon){ const double max_z = inverse_standard_norm_cdf(1-epsilon); const double min_z = -max_z; // z-score = (x - mu) / sigma // --> x = z*sigma + mu // Find minimum and maximum integer values beyond which tails of // Gaussian are < epsilon. double min_double_support = mu + min_z*sigma; double max_double_support = mu + max_z*sigma; long min_support = (long) floor(min_double_support); long max_support = (long) ceil(max_double_support); Tensor<double> table({ (unsigned long)(max_support - min_support + 1) }); for(unsigned long i=0; i<table.flat_size(); ++i) table[i] = gaussian_density(min_support + long(i), mu, sigma); return LabeledPMF<T>( {label}, PMF({min_support}, table) ); } template <typename T> LabeledPMF<T> make_nonneg_gaussian(const T & label, double mu, const double sigma, const double epsilon){ const double max_z = inverse_standard_norm_cdf(1-epsilon); const double min_z = -max_z; // z-score = (x - mu) / sigma // --> x = z*sigma + mu // Find minimum and maximum integer values beyond which tails of // Gaussian are < epsilon. double min_double_support = mu + min_z*sigma; double max_double_support = mu + max_z*sigma; long min_support = (long) floor(min_double_support); long max_support = (long) ceil(max_double_support); min_support = std::max(0L, min_support); assert(max_support >= min_support); Tensor<double> table({ (unsigned long)(max_support - min_support + 1) }); for(unsigned long i=0; i<table.flat_size(); ++i) table[i] = gaussian_density(min_support + long(i), mu, sigma); return LabeledPMF<T>({label}, PMF({min_support}, table)); } // Like a Gaussian but with guaranteed minimum probability (to // increase the density of tails): template <typename T> LabeledPMF<T> make_nonneg_pseudo_gaussian(const T & label, double mu, const double sigma, const double epsilon, long max_support, double pseudo_count){ const double max_z = inverse_standard_norm_cdf(1-epsilon); // z-score = (x - mu) / sigma // --> x = z*sigma + mu // Find minimum and maximum integer values beyond which tails of // Gaussian are < epsilon. double max_double_support = mu + max_z*sigma; long min_support = 0; max_support = std::max( (long) ceil(max_double_support), max_support); assert(max_support >= min_support); Tensor<double> table({ (unsigned long)(max_support - min_support + 1) }); for(unsigned long i=0; i<table.flat_size(); ++i) table[i] = std::max( gaussian_density(min_support + long(i), mu, sigma), pseudo_count); return LabeledPMF<T>({label}, PMF({min_support}, table)); } template <typename T> LabeledPMF<T> make_bernoulli(const T & var_name, double probability_x_equals_one) { assert(probability_x_equals_one >= 0.0 && probability_x_equals_one <= 1.0 && "make_bernoulli must receive a valid probability"); return LabeledPMF<T>({var_name}, PMF({0L}, Tensor<double>({2ul}, {1-probability_x_equals_one, probability_x_equals_one}))); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/eol-bspline/BSpline/BSpline.cpp
.cpp
5,056
174
// -*- mode: c++; c-basic-offset: 4; -*- /************************************************************************ * Copyright 2009 University Corporation for Atmospheric Research. * All rights reserved. * * Use of this code is subject to the standard BSD license: * * http://www.opensource.org/licenses/bsd-license.html * * See the COPYRIGHT file in the source distribution for the license text, * or see this web page: * * http://www.eol.ucar.edu/homes/granger/bspline/doc/ * *************************************************************************/ /** * @file * * This file defines the implementation for the BSpline and BSplineBase * templates. **/ #include "BSpline.h" #include "BandedMatrix.h" #include <vector> #include <algorithm> #include <iterator> #include <iostream> #include <iomanip> #include <map> #include <assert.h> namespace eol_bspline { ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // BSpline Class ////////////////////////////////////////////////////////////////////// template<class T> struct BSplineP { std::vector<T> spline; std::vector<T> A; }; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// /* * This BSpline constructor constructs and sets up a new base and * solves for the spline curve coeffiecients all at once. */ template<class T> BSpline<T>::BSpline(const T *x, int nx, const T *y, double wl, int bc_type, int num_nodes) : BSplineBase<T>(x, nx, wl, bc_type, num_nodes), s(new BSplineP<T>) { solve(y); } ////////////////////////////////////////////////////////////////////// /* * Create a new spline given a BSplineBase. */ template<class T> BSpline<T>::BSpline(BSplineBase<T> &bb, const T *y) : BSplineBase<T>(bb), s(new BSplineP<T>) { solve(y); } ////////////////////////////////////////////////////////////////////// /* * (Re)calculate the spline for the given set of y values. */ template<class T> bool BSpline<T>::solve(const T *y) { if (!OK) return false; // Any previously calculated curve is now invalid. s->spline.clear(); OK = false; // Given an array of data points over x and its precalculated // P+Q matrix, calculate the b vector and solve for the coefficients. std::vector<T> &B = s->A; std::vector<T> &A = s->A; A.clear(); A.resize(M+1); if (Debug()) std::cerr << "Solving for B..." << std::endl; // Find the mean of these data mean = 0.0; int i; for (i = 0; i < NX; ++i) { mean += y[i]; } mean = mean / (double)NX; if (Debug()) std::cerr << "Mean for y: " << mean << std::endl; int mx, m, j; for (j = 0; j < NX; ++j) { // Which node does this put us in? T &xj = base->X[j]; T yj = y[j] - mean; mx = (int)((xj - xmin) / DX); for (m = my::max(0, mx-1); m <= my::min(mx+2, M); ++m) { B[m] += yj * this->Basis(m, xj); } } if (Debug() && M < 30) { std::cerr << "Solution a for (P+Q)a = b" << std::endl; std::cerr << " b: " << B << std::endl; } // Now solve for the A vector in place. if (LU_solve_banded(base->Q, A, 3) != 0) { if (Debug()) std::cerr << "LU_solve_banded() failed." << std::endl; } else { OK = true; if (Debug()) std::cerr << "Done." << std::endl; if (Debug() && M < 30) { std::cerr << " a: " << A << std::endl; std::cerr << "LU factor of (P+Q) = " << std::endl << base->Q << std::endl; } } return (OK); } ////////////////////////////////////////////////////////////////////// template<class T> BSpline<T>::~BSpline() { delete s; } ////////////////////////////////////////////////////////////////////// template<class T> T BSpline<T>::coefficient(int n) { if (OK) if (0 <= n && n <= M) return s->A[n]; return 0; } ////////////////////////////////////////////////////////////////////// template<class T> T BSpline<T>::evaluate(T x) { T y = 0; if (OK) { int n = (int)((x - xmin)/DX); for (int i = my::max(0, n-1); i <= my::min(M, n+2); ++i) { y += s->A[i] * this->Basis(i, x); } y += mean; } return y; } ////////////////////////////////////////////////////////////////////// template<class T> T BSpline<T>::slope(T x) { T dy = 0; if (OK) { int n = (int)((x - xmin)/DX); for (int i = my::max(0, n-1); i <= my::min(M, n+2); ++i) { dy += s->A[i] * this->DBasis(i, x); } } return dy; } } // end namespace
C++
3D
OpenMS/OpenMS
src/openms/extern/eol-bspline/BSpline/BSplineLib.cpp
.cpp
867
33
/************************************************************************ * Copyright 2009 University Corporation for Atmospheric Research. * All rights reserved. * * Use of this code is subject to the standard BSD license: * * http://www.opensource.org/licenses/bsd-license.html * * See the COPYRIGHT file in the source distribution for the license text, * or see this web page: * * http://www.eol.ucar.edu/homes/granger/bspline/doc/ * *************************************************************************/ // Instantiate the BSpline templates for type #include "BSplineBase.cpp" namespace eol_bspline { /// Instantiate BSplineBase for a library template class BSplineBase<double>; template class BSplineBase<float>; /// Instantiate BSpline for a library template class BSpline<double>; template class BSpline<float>; } // end namespace
C++
3D
OpenMS/OpenMS
src/openms/extern/eol-bspline/BSpline/BSplineBase.cpp
.cpp
21,545
660
/************************************************************************ * Copyright 2009 University Corporation for Atmospheric Research. * All rights reserved. * * Use of this code is subject to the standard BSD license: * * http://www.opensource.org/licenses/bsd-license.html * * See the COPYRIGHT file in the source distribution for the license text, * or see this web page: * * http://www.eol.ucar.edu/homes/granger/bspline/doc/ * *************************************************************************/ #include "BSpline.h" #include "BandedMatrix.h" #include <vector> #include <algorithm> #include <iterator> #include <iostream> #include <iomanip> #include <map> #include <assert.h> namespace eol_bspline { /* * This class simulates a namespace for private symbols used by this template * implementation which should not pollute the global namespace. */ class my { public: template<class T> static inline T abs(const T t) { return (t < 0) ? -t : t; } template<class T> static inline const T& min(const T& a, const T& b) { return (a < b) ? a : b; } template<class T> static inline const T& max(const T& a, const T& b) { return (a > b) ? a : b; } }; ////////////////////////////////////////////////////////////////////// template<class T> class Matrix : public BandedMatrix<T> { public: Matrix &operator +=(const Matrix &B) { Matrix &A = *this; typename Matrix::size_type M = A.num_rows(); typename Matrix::size_type N = A.num_cols(); assert(M==B.num_rows()); assert(N==B.num_cols()); typename Matrix::size_type i, j; for (i=0; i<M; i++) for (j=0; j<N; j++) A[i][j] += B[i][j]; return A; } inline Matrix & operator=(const Matrix &b) { return Copy(*this, b); } inline Matrix & operator=(const T &e) { BandedMatrix<T>::operator= (e); return *this; } }; ////////////////////////////////////////////////////////////////////// // Our private state structure, which hides our use of some matrix // template classes. template<class T> struct BSplineBaseP { typedef Matrix<T> MatrixT; MatrixT Q; // Holds P+Q and its factorization std::vector<T> X; std::vector<T> Nodes; }; ////////////////////////////////////////////////////////////////////// // This array contains the beta parameter for the boundary condition // constraints. The boundary condition type--0, 1, or 2--is the first // index into the array, followed by the index of the endpoints. See the // Beta() method. template<class T> const double BSplineBase<T>::BoundaryConditions[3][4] = { // 0 1 M-1 M { -4, -1, -1, -4 }, { 0, 1, 1, 0 }, { 2, -1, -1, 2 } }; ////////////////////////////////////////////////////////////////////// template<class T> inline bool BSplineBase<T>::Debug(int on) { static bool debug = false; if (on >= 0) debug = (on > 0); return debug; } ////////////////////////////////////////////////////////////////////// template<class T> const double BSplineBase<T>::PI = 3.1415927; ////////////////////////////////////////////////////////////////////// template<class T> const char * BSplineBase<T>::ImplVersion() { return ("$Id: BSpline.cpp 6352 2008-05-05 04:40:39Z martinc $"); } ////////////////////////////////////////////////////////////////////// template<class T> const char * BSplineBase<T>::IfaceVersion() { return (_BSPLINEBASE_IFACE_ID); } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// template<class T> BSplineBase<T>::~BSplineBase() { delete base; } // This is a member-wise copy except for replacing our // private base structure with the source's, rather than just copying // the pointer. But we use the compiler's default copy constructor for // constructing our BSplineBaseP. template<class T> BSplineBase<T>::BSplineBase(const BSplineBase<T> &bb) : K(bb.K), BC(bb.BC), OK(bb.OK), base(new BSplineBaseP<T>(*bb.base)) { xmin = bb.xmin; xmax = bb.xmax; alpha = bb.alpha; waveLength = bb.waveLength; DX = bb.DX; M = bb.M; NX = base->X.size(); } ////////////////////////////////////////////////////////////////////// template<class T> BSplineBase<T>::BSplineBase(const T *x, int nx, double wl, int bc, int num_nodes) : K(2), NX(0), OK(false), base(new BSplineBaseP<T>) { setDomain(x, nx, wl, bc, num_nodes); } ////////////////////////////////////////////////////////////////////// // Methods template<class T> bool BSplineBase<T>::setDomain(const T *x, int nx, double wl, int bc, int num_nodes) { if ((nx <= 0) || (x == 0) || (wl< 0) || (bc< 0) || (bc> 2)) { return false; } OK = false; waveLength = wl; BC = bc; // Copy the x array into our storage. base->X.resize(nx); std::copy(x, x+nx, base->X.begin()); NX = static_cast<int>(base->X.size()); // The Setup() method determines the number and size of node intervals. if (Setup(num_nodes)) { if (Debug()) { std::cerr << "Using M node intervals: " << M << " of length DX: " << DX << std::endl; std::cerr << "X min: " << xmin << " ; X max: " << xmax << std::endl; std::cerr << "Data points per interval: " << (float)NX/(float)M << std::endl; std::cerr << "Nodes per wavelength: " << (float)waveLength /(float)DX << std::endl; std::cerr << "Derivative constraint degree: " << K << std::endl; } // Now we can calculate alpha and our Q matrix alpha = Alpha(waveLength); if (Debug()) { std::cerr << "Cutoff wavelength: " << waveLength << " ; " << "Alpha: " << alpha << std::endl; std::cerr << "Calculating Q..." << std::endl; } calculateQ(); if (Debug() && M < 30) { std::cerr.fill(' '); std::cerr.precision(2); std::cerr.width(5); std::cerr << base->Q << std::endl; } if (Debug()) std::cerr << "Calculating P..." << std::endl; addP(); if (Debug()) { std::cerr << "Done." << std::endl; if (M < 30) { std::cerr << "Array Q after addition of P." << std::endl; std::cerr << base->Q; } } // Now perform the LU factorization on Q if (Debug()) std::cerr << "Beginning LU factoring of P+Q..." << std::endl; if (!factor()) { if (Debug()) std::cerr << "Factoring failed." << std::endl; } else { if (Debug()) std::cerr << "Done." << std::endl; OK = true; } } return OK; } ////////////////////////////////////////////////////////////////////// /* * Calculate the alpha parameter given a wavelength. */ template<class T> double BSplineBase<T>::Alpha(double wl) { // K is the degree of the derivative constraint: 1, 2, or 3 double a = (double) (wl / (2 * PI * DX)); a *= a; // a^2 if (K == 2) a = a * a; // a^4 else if (K == 3) a = a * a * a; // a^6 return a; } ////////////////////////////////////////////////////////////////////// /* * Return the correct beta value given the node index. The value depends * on the node index and the current boundary condition type. */ template<class T> inline double BSplineBase<T>::Beta(int m) { if (m > 1 && m < M-1) return 0.0; if (m >= M-1) m -= M-3; assert(0 <= BC && BC <= 2); assert(0 <= m && m <= 3); return BoundaryConditions[BC][m]; } ////////////////////////////////////////////////////////////////////// /* * Given an array of y data points defined over the domain * of x data points in this BSplineBase, create a BSpline * object which contains the smoothed curve for the y array. */ template<class T> BSpline<T> * BSplineBase<T>::apply(const T *y) { return new BSpline<T> (*this, y); } ////////////////////////////////////////////////////////////////////// /* * Evaluate the closed basis function at node m for value x, * using the parameters for the current boundary conditions. */ template<class T> double BSplineBase<T>::Basis(int m, T x) { double y = 0; double xm = xmin + (m * DX); double z = my::abs((double)(x - xm) / (double)DX); if (z < 2.0) { z = 2 - z; y = 0.25 * (z*z*z); z -= 1.0; if (z > 0) y -= (z*z*z); } // Boundary conditions, if any, are an additional addend. if (m == 0 || m == 1) y += Beta(m) * Basis(-1, x); else if (m == M-1 || m == M) y += Beta(m) * Basis(M+1, x); return y; } ////////////////////////////////////////////////////////////////////// /* * Evaluate the deriviative of the closed basis function at node m for * value x, using the parameters for the current boundary conditions. */ template<class T> double BSplineBase<T>::DBasis(int m, T x) { double dy = 0; double xm = xmin + (m * DX); double delta = (double)(x - xm) / (double)DX; double z = my::abs(delta); if (z < 2.0) { z = 2.0 - z; dy = 0.25 * z * z; z -= 1.0; if (z > 0) { dy -= z * z; } dy *= ((delta > 0) ? -1.0 : 1.0) * 3.0 / DX; } // Boundary conditions, if any, are an additional addend. if (m == 0 || m == 1) dy += Beta(m) * DBasis(-1, x); else if (m == M-1 || m == M) dy += Beta(m) * DBasis(M+1, x); return dy; } ////////////////////////////////////////////////////////////////////// template<class T> double BSplineBase<T>::qDelta(int m1, int m2) /* * Return the integral of the product of the basis function derivative * restricted to the node domain, 0 to M. */ { // These are the products of the Kth derivative of the // normalized basis functions // given a distance m nodes apart, qparts[K-1][m], 0 <= m <= 3 // Each column is the integral over each unit domain, -2 to 2 static const double qparts[3][4][4] = { { { 0.11250, 0.63750, 0.63750, 0.11250 }, { 0.00000, 0.13125, -0.54375, 0.13125 }, { 0.00000, 0.00000, -0.22500, -0.22500 }, { 0.00000, 0.00000, 0.00000, -0.01875 } }, { { 0.75000, 2.25000, 2.25000, 0.75000 }, { 0.00000, -1.12500, -1.12500, -1.12500 }, { 0.00000, 0.00000, 0.00000, 0.00000 }, { 0.00000, 0.00000, 0.00000, 0.37500 } }, { { 2.25000, 20.25000, 20.25000, 2.25000 }, { 0.00000, -6.75000, -20.25000, -6.75000 }, { 0.00000, 0.00000, 6.75000, 6.75000 }, { 0.00000, 0.00000, 0.00000, -2.25000 } } }; if (m1 > m2) std::swap(m1, m2); if (m2 - m1 > 3) return 0.0; double q = 0; for (int m = my::max(m1-2, 0); m < my::min(m1+2, M); ++m) q += qparts[K-1][m2-m1][m-m1+2]; return q * alpha; } ////////////////////////////////////////////////////////////////////// template<class T> void BSplineBase<T>::calculateQ() { Matrix<T> &Q = base->Q; Q.setup(M+1, 3); Q = 0; if (alpha == 0) return; // First fill in the q values without the boundary constraints. int i; for (i = 0; i <= M; ++i) { Q[i][i] = qDelta(i, i); for (int j = 1; j < 4 && i+j <= M; ++j) { Q[i][i+j] = Q[i+j][i] = qDelta(i, i+j); } } // Now add the boundary constraints: // First the upper left corner. float b1, b2, q; for (i = 0; i <= 1; ++i) { b1 = Beta(i); for (int j = i; j < i+4; ++j) { b2 = Beta(j); assert(j-i >= 0 && j - i < 4); q = 0.0; if (i+1 < 4) q += b2*qDelta(-1, i); if (j+1 < 4) q += b1*qDelta(-1, j); q += b1*b2*qDelta(-1, -1); Q[j][i] = (Q[i][j] += q); } } // Then the lower right for (i = M-1; i <= M; ++i) { b1 = Beta(i); for (int j = i - 3; j <= i; ++j) { b2 = Beta(j); q = 0.0; if (M+1-i < 4) q += b2*qDelta(i, M+1); if (M+1-j < 4) q += b1*qDelta(j, M+1); q += b1*b2*qDelta(M+1, M+1); Q[j][i] = (Q[i][j] += q); } } } ////////////////////////////////////////////////////////////////////// template<class T> void BSplineBase<T>::addP() { // Add directly to Q's elements Matrix<T> &P = base->Q; std::vector<T> &X = base->X; // For each data point, sum the product of the nearest, non-zero Basis // nodes int mx, m, n, i; for (i = 0; i < NX; ++i) { // Which node does this put us in? T &x = X[i]; mx = (int)((x - xmin) / DX); // Loop over the upper triangle of nonzero basis functions, // and add in the products on each side of the diagonal. for (m = my::max(0, mx-1); m <= my::min(M, mx+2); ++m) { float pn; float pm = Basis(m, x); float sum = pm * pm; P[m][m] += sum; for (n = m+1; n <= my::min(M, mx+2); ++n) { pn = Basis(n, x); sum = pm * pn; P[m][n] += sum; P[n][m] += sum; } } } } ////////////////////////////////////////////////////////////////////// template<class T> bool BSplineBase<T>::factor() { Matrix<T> &LU = base->Q; if (LU_factor_banded(LU, 3) != 0) { if (Debug()) std::cerr << "LU_factor_banded() failed." << std::endl; return false; } if (Debug() && M < 30) std::cerr << "LU decomposition: " << std::endl << LU << std::endl; return true; } ////////////////////////////////////////////////////////////////////// template<class T> inline double BSplineBase<T>::Ratiod(int &ni, double &deltax, double &ratiof) { deltax = (xmax - xmin) / ni; ratiof = waveLength / deltax; double ratiod = (double) NX / (double) (ni + 1); return ratiod; } ////////////////////////////////////////////////////////////////////// // Setup the number of nodes (and hence deltax) for the given domain and // cutoff wavelength. According to Ooyama, the derivative constraint // approximates a lo-pass filter if the cutoff wavelength is about 4*deltax // or more, but it should at least be 2*deltax. We can increase the number // of nodes to increase the number of nodes per cutoff wavelength. // However, to get a reasonable representation of the data, the setup // enforces at least as many nodes as data points in the domain. (This // constraint assumes reasonably even distribution of data points, since // its really the density of data points which matters.) // // Return zero if the setup fails, non-zero otherwise. // // The algorithm in this routine is mostly taken from the FORTRAN // implementation by James Franklin, NOAA/HRD. // template<class T> bool BSplineBase<T>::Setup(int num_nodes) { std::vector<T> &X = base->X; // Find the min and max of the x domain xmin = X[0]; xmax = X[0]; int i; for (i = 1; i < NX; ++i) { if (X[i] < xmin) xmin = X[i]; else if (X[i] > xmax) xmax = X[i]; } int ni = 9; // Number of node intervals (NX - 1) double deltax; if (num_nodes >= 2) { // We've been told explicitly the number of nodes to use. ni = num_nodes - 1; if (waveLength == 0) { waveLength = 1.0; } } else if (waveLength == 0) { // Turn off frequency constraint and just set two node intervals per // data point. ni = NX * 2; waveLength = 1; } else if (waveLength > xmax - xmin) { return (false); } else { // Minimum acceptable number of node intervals per cutoff wavelength. static const double fmin = 2.0; double ratiof; // Nodes per wavelength for current deltax double ratiod; // Points per node interval // Increase the number of node intervals until we reach the minimum // number of intervals per cutoff wavelength, but only as long as // we can maintain at least one point per interval. do { if (Ratiod(++ni, deltax, ratiof) < 1.0) return false; } while (ratiof < fmin); // Now increase the number of intervals until we have at least 4 // intervals per cutoff wavelength, but only as long as we can // maintain at least 2 points per node interval. There's also no // point to increasing the number of intervals if we already have // 15 or more nodes per cutoff wavelength. // do { if ((ratiod = Ratiod(++ni, deltax, ratiof)) < 1.0 || ratiof > 15.0) { --ni; break; } } while (ratiof< 4 || ratiod> 2.0); } // Store the calculations in our state M = ni; DX = (xmax - xmin) / ni; return (true); } ////////////////////////////////////////////////////////////////////// template<class T> const T * BSplineBase<T>::nodes(int *nn) { if (base->Nodes.size() == 0) { base->Nodes.reserve(M+1); for (int i = 0; i <= M; ++i) { base->Nodes.push_back(xmin + (i * DX)); } } if (nn) *nn = base->Nodes.size(); assert(base->Nodes.size() == (unsigned)(M+1)); return &base->Nodes[0]; } ////////////////////////////////////////////////////////////////////// template<class T> std::ostream &operator<<(std::ostream &out, const std::vector<T> &c) { for (typename std::vector<T>::const_iterator it = c.begin(); it < c.end(); ++it) out << *it << ", "; out << std::endl; return out; } } // end namespace
C++
3D
OpenMS/OpenMS
src/openms/extern/eol-bspline/BSpline/BSplineBase.h
.h
13,351
339
/************************************************************************ * Copyright 2009 University Corporation for Atmospheric Research. * All rights reserved. * * Use of this code is subject to the standard BSD license: * * http://www.opensource.org/licenses/bsd-license.html * * See the COPYRIGHT file in the source distribution for the license text, * or see this web page: * * http://www.eol.ucar.edu/homes/granger/bspline/doc/ * *************************************************************************/ #pragma once #ifndef _BSPLINEBASE_IFACE_ID #define _BSPLINEBASE_IFACE_ID "$Id: BSpline.h 6353 2008-05-05 19:30:48Z martinc $" #endif namespace eol_bspline { /** * @file * * This file defines the BSpline library interface. * */ template <class T> class BSpline; /* * Opaque member structure to hide the matrix implementation. */ template <class T> struct BSplineBaseP; /** * @class BSplineBase * * The base class for a spline object containing the nodes for a given * domain, cutoff wavelength, and boundary condition. * To smooth a single curve, the BSpline interface contains a constructor * which both sets up the domain and solves for the spline. Subsequent * curves over the same domain can be created by apply()ing them to the * BSpline object, where apply() is a BSplineBase method. [See apply().] * New curves can also be smoothed within the same BSpline object by * calling solve() with the new set of y values. [See BSpline.] A * BSplineBase can be created on its own, in which case all of the * computations dependent on the x values, boundary conditions, and cutoff * wavelength have already been completed. * * The solution of the cubic b-spline is divided into two parts. The first * is the setup of the domain given the x values, boundary conditions, and * wavelength. The second is the solution of the spline for a set of y * values corresponding to the x values in the domain. The first part is * done in the creation of the BSplineBase object (or when calling the * setDomain method). The second part is done when creating a BSpline * object (or calling solve() on a BSpline object). * * A BSpline object can be created with either one of its constructors, or * by calling apply() on an existing BSplineBase object. Once a spline has * been solved, it can be evaluated at any x value. The following example * creates a spline curve and evaluates it over the domain: * @verbatim vector<float> x; vector<float> y; { ... } int bc = BSplineBase<float>::BC_ZERO_SECOND; BSpline<float>::Debug = true; BSpline<float> spline (x.begin(), x.size(), y.begin(), wl, bc); if (spline.ok()) { ostream_iterator<float> of(cout, "\t "); float xi = spline.Xmin(); float xs = (spline.Xmax() - xi) / 2000.0; for (; xi <= spline.Xmax(); xi += xs) { *of++ = spline.evaluate (xi); } } @endverbatim * * In the usual usage, the BSplineBase can compute a reasonable number of * nodes for the spline, balancing between a few desirable factors. There * needs to be at least 2 nodes per cutoff wavelength (preferably 4 or * more) for the derivative constraint to reliably approximate a lo-pass * filter. There should be at least 1 and preferably about 2 data points * per node (measured just by their number and not by any check of the * density of points across the domain). Lastly, of course, the fewer the * nodes then the faster the computation of the spline. The computation of * the number of nodes happens in the Setup() method during BSplineBase * construction and when setDomain() is called. If the setup fails to find * a desirable number of nodes, then the BSplineBase object will return * false from ok(). * * The ok() method returns false when a BSplineBase or BSpline could not * complete any operation successfully. In particular, as mentioned above, * ok() will return false if some problem was detected with the domain * values or if no reasonable number of nodes could be found for the given * cutoff wavelength. Also, ok() on a BSpline object will return false if * the matrix equation could not be solved, such as after BSpline * construction or after a call to apply(). * * If letting Setup() determine the number of nodes is not acceptable, the * constructors and setDomain() accept the parameter num_nodes. By * default, num_nodes is passed as zero, forcing Setup() to calculate the * number of nodes. However, if num_nodes is passed as 2 or greater, then * Setup() will bypass its own algorithm and accept the given number of * nodes instead. Obviously, it's up to the programmer to understand the * affects of the number of nodes on the representation of the data and on * the solution (or non-solution) of the spline. Remember to check the * ok() method to detect when the spline solution has failed. * * The interface for the BSplineBase and BSpline templates is defined in * the header file BSpline.h. The implementation is defined in BSpline.cpp. * Source files which will instantiate the template should include the * implementation file and @em not the interface. If the implementation * for a specific type will be linked from elsewhere, such as a * static library or Windows DLL, source files should only include the * interface file. On Windows, applications should link with the import * library BSpline.lib and make sure BSpline.dll is on the path. The DLL * contains an implementation for BSpline<float> and BSpline<double>. * For debugging, an application can include the implementation to get its * own instantiation. * * The algorithm is based on the cubic spline described by Katsuyuki Ooyama * in Montly Weather Review, Vol 115, October 1987. This implementation * has benefited from comparisons with a previous FORTRAN implementation by * James L. Franklin, NOAA/Hurricane Research Division. In particular, the * algorithm in the Setup() method is based mostly on his implementation * (VICSETUP). The Setup() method finds a suitable default for the number * of nodes given a domain and cutoff frequency. This implementation * adopts most of the same constraints, including a constraint that the * cutoff wavelength not be greater than the span of the domain values: wl * < max(x) - min(x). If this is not an acceptable constraint, then use the * num_nodes parameter to specify the number of nodes explicitly. * * The cubic b-spline is formulated as the sum of some multiple of the * basis function centered at each node in the domain. The number of nodes * is determined by the desired cutoff wavelength and a desirable number of * x values per node. The basis function is continuous and differentiable * up to the second degree. A derivative constraint is included in the * solution to achieve the effect of a low-pass frequency filter with the * given cutoff wavelength. The derivative constraint can be disabled by * specifying a wavelength value of zero, which reduces the analysis to a * least squares fit to a cubic b-spline. The domain nodes, boundary * constraints, and wavelength determine a linear system of equations, * Qa=b, where a is the vector of basis function coefficients at each node. * The coefficient vector is solved by first LU factoring along the * diagonally banded matrix Q in BSplineBase. The BSpline object then * computes the B vector for a set of y values and solves for the * coefficient vector with the LU matrix. Only the diagonal bands are * stored in memory and calculated during LU factoring and back * substitution, and the basis function is evaluated as few times as * possible in computing the diagonal matrix and B vector. * * @author Gary Granger (http://www.eol.ucar.edu/homes/granger) * @verbatim Copyright (c) 1998-2009 University Corporation for Atmospheric Research, UCAR All rights reserved. @endverbatim **/ template <class T> class BSplineBase { public: // Datum type typedef T datum_type; /// Return a string describing the implementation version. static const char *ImplVersion(); /// Return a string describing the interface version. static const char *IfaceVersion(); /** * Call this class method with a value greater than zero to enable * debug messages, or with zero to disable messages. Calling with * no arguments returns true if debugging enabled, else false. */ static bool Debug (int on = -1); /** * Boundary condition types. */ enum BoundaryConditionTypes { /// Set the endpoints of the spline to zero. BC_ZERO_ENDPOINTS = 0, /// Set the first derivative of the spline to zero at the endpoints. BC_ZERO_FIRST = 1, /// Set the second derivative to zero. BC_ZERO_SECOND = 2 }; public: /** * Construct a spline domain for the given set of x values, cutoff * wavelength, and boundary condition type. The parameters are the * same as for setDomain(). Call ok() to check whether domain * setup succeeded after construction. */ BSplineBase (const T *x, int nx, double wl, int bc_type = BC_ZERO_SECOND, int num_nodes = 0); /// Copy constructor BSplineBase (const BSplineBase &); /** * Change the domain of this base. [If this is part of a BSpline * object, this method {\em will not} change the existing curve or * re-apply the smoothing to any set of y values.] * * The x values can be in any order, but they must be of sufficient * density to support the requested cutoff wavelength. The setup of * the domain may fail because of either inconsistency between the x * density and the cutoff wavelength, or because the resulting matrix * could not be factored. If setup fails, the method returns false. * * @param x The array of x values in the domain. * @param nx The number of values in the @p x array. * @param wl The cutoff wavelength, in the same units as the * @p x values. A wavelength of zero disables * the derivative constraint. * @param bc_type The enumerated boundary condition type. If * omitted it defaults to BC_ZERO_SECOND. * @param num_nodes The number of nodes to use for the cubic b-spline. * If less than 2 a reasonable number will be * calculated automatically, if possible, taking * into account the given cutoff wavelength. * * @see ok(). */ bool setDomain (const T *x, int nx, double wl, int bc_type = BC_ZERO_SECOND, int num_nodes = 0); /** * Create a BSpline smoothed curve for the given set of NX y values. * The returned object will need to be deleted by the caller. * @param y The array of y values corresponding to each of the nX() * x values in the domain. * @see ok() */ BSpline<T> *apply (const T *y); /** * Return array of the node coordinates. Returns 0 if not ok(). The * array of nodes returned by nodes() belongs to the object and should * not be deleted; it will also be invalid if the object is destroyed. */ const T *nodes (int *nnodes); /** * Return the number of nodes (one more than the number of intervals). */ int nNodes () { return M+1; } /** * Number of original x values. */ int nX () { return NX; } /// Minimum x value found. T Xmin () { return xmin; } /// Maximum x value found. T Xmax () { return xmin + (M * DX); } /** * Return the Alpha value for a given wavelength. Note that this * depends on the current node interval length (DX). */ double Alpha (double wavelength); /** * Return alpha currently in use by this domain. */ double Alpha () { return alpha; } /** * Return the current state of the object, either ok or not ok. * Use this method to test for valid state after construction or after * a call to setDomain(). ok() will return false if either fail, such * as when an appropriate number of nodes and node interval cannot be * found for a given wavelength, or when the linear equation for the * coefficients cannot be solved. */ bool ok () { return OK; } virtual ~BSplineBase(); protected: typedef BSplineBaseP<T> Base; // Provided double waveLength; // Cutoff wavelength (l sub c) int NX; int K; // Degree of derivative constraint (currently fixed at 2) int BC; // Boundary conditions type (0,1,2) // Derived T xmax; T xmin; int M; // Number of intervals (M+1 nodes) double DX; // Interval length in same units as X double alpha; bool OK; Base *base; // Hide more complicated state members // from the public interface. bool Setup (int num_nodes = 0); void calculateQ (); double qDelta (int m1, int m2); double Beta (int m); void addP (); bool factor (); double Basis (int m, T x); double DBasis (int m, T x); static const double BoundaryConditions[3][4]; static const double PI; double Ratiod (int&, double &, double &); }; } // end namespace
Unknown
3D
OpenMS/OpenMS
src/openms/extern/eol-bspline/BSpline/BandedMatrix.h
.h
8,076
381
/* -*- mode: c++; c-basic-offset: 4; -*- */ /************************************************************************ * Copyright 2009 University Corporation for Atmospheric Research. * All rights reserved. * * Use of this code is subject to the standard BSD license: * * http://www.opensource.org/licenses/bsd-license.html * * See the COPYRIGHT file in the source distribution for the license text, * or see this web page: * * http://www.eol.ucar.edu/homes/granger/bspline/doc/ * *************************************************************************/ /** * Template for a diagonally banded matrix. **/ #ifndef _BANDEDMATRIX_ID #define _BANDEDMATRIX_ID "$Id: BandedMatrix.h 7094 2009-10-01 16:33:02Z granger $" #include <vector> #include <algorithm> #include <iostream> namespace eol_bspline { template <class T> class BandedMatrixRow; template <class T> class BandedMatrix { public: typedef unsigned int size_type; typedef T element_type; // Create a banded matrix with the same number of bands above and below // the diagonal. BandedMatrix (int N_ = 1, int nbands_off_diagonal = 0) : bands(0) { if (! setup (N_, nbands_off_diagonal)) setup (); } // Create a banded matrix by naming the first and last non-zero bands, // where the diagonal is at zero, and bands below the diagonal are // negative, bands above the diagonal are positive. BandedMatrix (int N_, int first, int last) : bands(0) { if (! setup (N_, first, last)) setup (); } // Copy constructor BandedMatrix (const BandedMatrix &b) : bands(0) { Copy (*this, b); } inline bool setup (int N_ = 1, int noff = 0) { return setup (N_, -noff, noff); } bool setup (int N_, int first, int last) { // Check our limits first and make sure they make sense. // Don't change anything until we know it will work. if (first > last || N_ <= 0) return false; // Need at least as many N_ as columns and as rows in the bands. if (N_ < abs(first) || N_ < abs(last)) return false; top = last; bot = first; N = N_; out_of_bounds = T(); // Finally setup the diagonal vectors nbands = last - first + 1; if (bands) delete[] bands; bands = new std::vector<T>[nbands]; int i; for (i = 0; i < nbands; ++i) { // The length of each array varies with its distance from the // diagonal int len = N - (abs(bot + i)); bands[i].clear (); bands[i].resize (len); } return true; } BandedMatrix<T> & operator= (const BandedMatrix<T> &b) { return Copy (*this, b); } BandedMatrix<T> & operator= (const T &e) { int i; for (i = 0; i < nbands; ++i) { std::fill_n (bands[i].begin(), bands[i].size(), e); } out_of_bounds = e; return (*this); } ~BandedMatrix () { if (bands) delete[] bands; } private: // Return false if coordinates are out of bounds inline bool check_bounds (int i, int j, int &v, int &e) const { v = (j - i) - bot; e = (i >= j) ? j : i; return !(v < 0 || v >= nbands || e < 0 || (unsigned int)e >= bands[v].size()); } static BandedMatrix & Copy (BandedMatrix &a, const BandedMatrix &b) { if (a.bands) delete[] a.bands; a.top = b.top; a.bot = b.bot; a.N = b.N; a.out_of_bounds = b.out_of_bounds; a.nbands = a.top - a.bot + 1; a.bands = new std::vector<T>[a.nbands]; int i; for (i = 0; i < a.nbands; ++i) { a.bands[i] = b.bands[i]; } return a; } public: T &element (int i, int j) { int v, e; if (check_bounds(i, j, v, e)) return (bands[v][e]); else return out_of_bounds; } const T &element (int i, int j) const { int v, e; if (check_bounds(i, j, v, e)) return (bands[v][e]); else return out_of_bounds; } inline T & operator() (int i, int j) { return element (i-1,j-1); } inline const T & operator() (int i, int j) const { return element (i-1,j-1); } size_type num_rows() const { return N; } size_type num_cols() const { return N; } const BandedMatrixRow<T> operator[] (int row) const { return BandedMatrixRow<T>(*this, row); } BandedMatrixRow<T> operator[] (int row) { return BandedMatrixRow<T>(*this, row); } private: int top; int bot; int nbands; std::vector<T> *bands; int N; T out_of_bounds; }; template <class T> std::ostream &operator<< (std::ostream &out, const BandedMatrix<T> &m) { unsigned int i, j; for (i = 0; i < m.num_rows(); ++i) { for (j = 0; j < m.num_cols(); ++j) { out << m.element (i, j) << " "; } out << std::endl; } return out; } /* * Helper class for the intermediate in the [][] operation. */ template <class T> class BandedMatrixRow { public: BandedMatrixRow (const BandedMatrix<T> &_m, int _row) : bm(_m), i(_row) { } BandedMatrixRow (BandedMatrix<T> &_m, int _row) : bm(_m), i(_row) { } ~BandedMatrixRow () {} typename BandedMatrix<T>::element_type & operator[] (int j) { return const_cast<BandedMatrix<T> &>(bm).element (i, j); } const typename BandedMatrix<T>::element_type & operator[] (int j) const { return bm.element (i, j); } private: const BandedMatrix<T> &bm; int i; }; /* * Vector multiplication */ template <class Vector, class Matrix> Vector operator* (const Matrix &m, const Vector &v) { typename Matrix::size_type M = m.num_rows(); typename Matrix::size_type N = m.num_cols(); assert (N <= v.size()); //if (M > v.size()) // return Vector(); Vector r(N); for (unsigned int i = 0; i < M; ++i) { typename Matrix::element_type sum = 0; for (unsigned int j = 0; j < N; ++j) { sum += m[i][j] * v[j]; } r[i] = sum; } return r; } /* * LU factor a diagonally banded matrix using Crout's algorithm, but * limiting the trailing sub-matrix multiplication to the non-zero * elements in the diagonal bands. Return nonzero if a problem occurs. */ template <class MT> int LU_factor_banded (MT &A, unsigned int bands) { typename MT::size_type M = A.num_rows(); typename MT::size_type N = A.num_cols(); if (M != N) return 1; typename MT::size_type i,j,k; typename MT::element_type sum; for (j = 1; j <= N; ++j) { // Check for zero pivot if ( A(j,j) == 0 ) return 1; // Calculate rows above and on diagonal. A(1,j) remains as A(1,j). for (i = (j > bands) ? j-bands : 1; i <= j; ++i) { sum = 0; for (k = (j > bands) ? j-bands : 1; k < i; ++k) { sum += A(i,k)*A(k,j); } A(i,j) -= sum; } // Calculate rows below the diagonal. for (i = j+1; (i <= M) && (i <= j+bands); ++i) { sum = 0; for (k = (i > bands) ? i-bands : 1; k < j; ++k) { sum += A(i,k)*A(k,j); } A(i,j) = (A(i,j) - sum) / A(j,j); } } return 0; } /* * Solving (LU)x = B. First forward substitute to solve for y, Ly = B. * Then backwards substitute to find x, Ux = y. Return nonzero if a * problem occurs. Limit the substitution sums to the elements on the * bands above and below the diagonal. */ template <class MT, class Vector> int LU_solve_banded(const MT &A, Vector &b, unsigned int bands) { typename MT::size_type i,j; typename MT::size_type M = A.num_rows(); typename MT::size_type N = A.num_cols(); typename MT::element_type sum; if (M != N || M == 0) return 1; // Forward substitution to find y. The diagonals of the lower // triangular matrix are taken to be 1. for (i = 2; i <= M; ++i) { sum = b[i-1]; for (j = (i > bands) ? i-bands : 1; j < i; ++j) { sum -= A(i,j)*b[j-1]; } b[i-1] = sum; } // Now for the backward substitution b[M-1] /= A(M,M); for (i = M-1; i >= 1; --i) { if (A(i,i) == 0) // oops! return 1; sum = b[i-1]; for (j = i+1; (j <= N) && (j <= i+bands); ++j) { sum -= A(i,j)*b[j-1]; } b[i-1] = sum / A(i,i); } return 0; } } // end namspace #endif /* _BANDEDMATRIX_ID */
Unknown
3D
OpenMS/OpenMS
src/openms/extern/eol-bspline/BSpline/BSpline.h
.h
3,662
123
/* -*- mode: c++; c-basic-offset: 4; -*- */ /************************************************************************ * Copyright 2009 University Corporation for Atmospheric Research. * All rights reserved. * * Use of this code is subject to the standard BSD license: * * http://www.opensource.org/licenses/bsd-license.html * * See the COPYRIGHT file in the source distribution for the license text, * or see this web page: * * http://www.eol.ucar.edu/homes/granger/bspline/doc/ * *************************************************************************/ #pragma once #include "BSplineBase.h" #include <vector> namespace eol_bspline { template <class T> struct BSplineP; /** * Used to evaluate a BSpline. * Inherits the BSplineBase domain information and interface and adds * smoothing. See the BSplineBase documentation for a summary of the * BSpline interface. */ template <class T> class BSpline : public BSplineBase<T> { public: /** * Create a single spline with the parameters required to set up * the domain and subsequently smooth the given set of y values. * The y values must correspond to each of the values in the x array. * If either the domain setup fails or the spline cannot be solved, * the state will be set to not ok. * * @see ok(). * * @param x The array of x values in the domain. * @param nx The number of values in the @p x array. * @param y The array of y values corresponding to each of the * nX() x values in the domain. * @param wl The cutoff wavelength, in the same units as the * @p x values. A wavelength of zero disables * the derivative constraint. * @param bc_type The enumerated boundary condition type. If * omitted it defaults to BC_ZERO_SECOND. * @param num_nodes The number of nodes to use for the cubic b-spline. * If less than 2 a "reasonable" number will be * calculated automatically, taking into account * the given cutoff wavelength. */ BSpline (const T *x, int nx, /* independent variable */ const T *y, /* dependent values @ ea X */ double wl, /* cutoff wavelength */ int bc_type = BSplineBase<T>::BC_ZERO_SECOND, int num_nodes = 0); /** * A BSpline curve can be derived from a separate @p base and a set * of data points @p y over that base. */ BSpline (BSplineBase<T> &base, const T *y); /** * Solve the spline curve for a new set of y values. Returns false * if the solution fails. * * @param y The array of y values corresponding to each of the nX() * x values in the domain. */ bool solve (const T *y); /** * Return the evaluation of the smoothed curve * at a particular @p x value. If current state is not ok(), returns 0. */ T evaluate (T x); /** * Return the first derivative of the spline curve at the given @p x. * Returns zero if the current state is not ok(). */ T slope (T x); /** * Return the @p n-th basis coefficient, from 0 to M. If the current * state is not ok(), or @p n is out of range, the method returns zero. */ T coefficient (int n); virtual ~BSpline(); using BSplineBase<T>::Debug; protected: using BSplineBase<T>::OK; using BSplineBase<T>::M; using BSplineBase<T>::NX; using BSplineBase<T>::DX; using BSplineBase<T>::base; using BSplineBase<T>::xmin; using BSplineBase<T>::xmax; // Our hidden state structure BSplineP<T> *s; T mean; // Fit without mean and add it in later }; } // end namespace
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BezierCurve.h
.h
6,243
179
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Array2.h> #include <Mathematics/ParametricCurve.h> namespace gte { template <int32_t N, typename Real> class BezierCurve : public ParametricCurve<N, Real> { public: // Construction and destruction. The number of control points must be // degree + 1. This object copies the input array. The domain is t // in [0,1]. To validate construction, create an object as shown: // BezierCurve<N, Real> curve(parameters); // if (!curve) { <constructor failed, handle accordingly>; } BezierCurve(int32_t degree, Vector<N, Real> const* controls) : ParametricCurve<N, Real>((Real)0, (Real)1), mDegree(degree), mNumControls(degree + 1), mChoose(mNumControls, mNumControls) { LogAssert(degree >= 2 && controls != nullptr, "Invalid input."); // Copy the controls. mControls[0].resize(mNumControls); std::copy(controls, controls + mNumControls, mControls[0].begin()); // Compute first-order differences. mControls[1].resize(static_cast<size_t>(mNumControls) - 1); for (int32_t i = 0, ip1 = 1; ip1 < mNumControls; ++i, ++ip1) { mControls[1][i] = mControls[0][ip1] - mControls[0][i]; } // Compute second-order differences. mControls[2].resize(static_cast<size_t>(mNumControls) - 2); for (int32_t i = 0, ip1 = 1, ip2 = 2; ip2 < mNumControls; ++i, ++ip1, ++ip2) { mControls[2][i] = mControls[1][ip1] - mControls[1][i]; } // Compute third-order differences. if (degree >= 3) { mControls[3].resize(static_cast<size_t>(mNumControls) - 3); for (int32_t i = 0, ip1 = 1, ip3 = 3; ip3 < mNumControls; ++i, ++ip1, ++ip3) { mControls[3][i] = mControls[2][ip1] - mControls[2][i]; } } // Compute combinatorial values Choose(n,k) and store in mChoose[n][k]. // The values mChoose[r][c] are invalid for r < c; that is, we use only // the entries for r >= c. mChoose[0][0] = (Real)1; mChoose[1][0] = (Real)1; mChoose[1][1] = (Real)1; for (int32_t i = 2; i <= mDegree; ++i) { mChoose[i][0] = (Real)1; mChoose[i][i] = (Real)1; for (int32_t j = 1; j < i; ++j) { mChoose[i][j] = mChoose[i - 1][j - 1] + mChoose[i - 1][j]; } } this->mConstructed = true; } virtual ~BezierCurve() { } // Member access. inline int32_t GetDegree() const { return mDegree; } inline int32_t GetNumControls() const { return mNumControls; } inline Vector<N, Real> const* GetControls() const { return &mControls[0][0]; } // Evaluation of the curve. The function supports derivative // calculation through order 3; that is, order <= 3 is required. If // you want/ only the position, pass in order of 0. If you want the // position and first derivative, pass in order of 1, and so on. The // output array 'jet' must have enough storage to support the maximum // order. The values are ordered as: position, first derivative, // second derivative, third derivative. virtual void Evaluate(Real t, uint32_t order, Vector<N, Real>* jet) const override { uint32_t const supOrder = ParametricCurve<N, Real>::SUP_ORDER; if (!this->mConstructed || order >= supOrder) { // Return a zero-valued jet for invalid state. for (uint32_t i = 0; i < supOrder; ++i) { jet[i].MakeZero(); } return; } // Compute position. Real omt = (Real)1 - t; jet[0] = Compute(t, omt, 0); if (order >= 1) { // Compute first derivative. jet[1] = Compute(t, omt, 1); if (order >= 2) { // Compute second derivative. jet[2] = Compute(t, omt, 2); if (order >= 3) { // Compute third derivative. if (mDegree >= 3) { jet[3] = Compute(t, omt, 3); } else { jet[3].MakeZero(); } } } } } protected: // Support for Evaluate(...). Vector<N, Real> Compute(Real t, Real omt, int32_t order) const { Vector<N, Real> result = omt * mControls[order][0]; Real tpow = t; int32_t isup = mDegree - order; for (int32_t i = 1; i < isup; ++i) { Real c = mChoose[isup][i] * tpow; result = (result + c * mControls[order][i]) * omt; tpow *= t; } result = (result + tpow * mControls[order][isup]); int32_t multiplier = 1; for (int32_t i = 0; i < order; ++i) { multiplier *= mDegree - i; } result *= (Real)multiplier; return result; } int32_t mDegree, mNumControls; std::array<std::vector<Vector<N, Real>>, ParametricCurve<N, Real>::SUP_ORDER> mControls; Array2<Real> mChoose; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ConvexPolyhedron3.h
.h
3,852
99
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/AlignedBox.h> #include <Mathematics/Vector4.h> #include <cstdint> #include <vector> namespace gte { template <typename Real> class ConvexPolyhedron3 { public: // Construction. The convex polyhedra represented by this class has // triangle faces that are counterclockwise ordered when viewed from // outside the polyhedron. No attempt is made to verify that the // polyhedron is convex; the caller is responsible for enforcing this. // The constructors move (not copy!) the input arrays. The // constructor succeeds when the number of vertices is at least 4 and // the number of indices is at least 12. If the constructor fails, // no move occurs and the member arrays have no elements. // // To support geometric algorithms that are formulated using convex // quadratic programming (such as computing the distance from a point // to a convex polyhedron), it is necessary to know the planes of the // faces and an axis-aligned bounding box. If you want either the // faces or the box, pass 'true' to the appropriate parameters. When // planes are generated, the normals are not created to be unit length // in order to support queries using exact rational arithmetic. If a // normal to a face is N = (n0,n1,n2) and V is a vertex of the face, // the plane is Dot(N,X-V) = 0 and is stored as // Dot(n0,n1,n2,-Dot(N,V)). The normals are computed to be outer // pointing. ConvexPolyhedron3() = default; ConvexPolyhedron3(std::vector<Vector3<Real>>&& inVertices, std::vector<int32_t>&& inIndices, bool wantPlanes, bool wantAlignedBox) { if (inVertices.size() >= 4 && inIndices.size() >= 12) { vertices = std::move(inVertices); indices = std::move(inIndices); if (wantPlanes) { GeneratePlanes(); } if (wantAlignedBox) { GenerateAlignedBox(); } } } // If you modifty the vertices or indices and you want the new face // planes or aligned box computed, call these functions. void GeneratePlanes() { if (vertices.size() > 0 && indices.size() > 0) { uint32_t const numTriangles = static_cast<uint32_t>(indices.size()) / 3; planes.resize(numTriangles); for (uint32_t t = 0, i = 0; t < numTriangles; ++t) { Vector3<Real> V0 = vertices[indices[i++]]; Vector3<Real> V1 = vertices[indices[i++]]; Vector3<Real> V2 = vertices[indices[i++]]; Vector3<Real> E1 = V1 - V0; Vector3<Real> E2 = V2 - V0; Vector3<Real> N = Cross(E1, E2); planes[t] = HLift(N, -Dot(N, V0)); } } } void GenerateAlignedBox() { if (vertices.size() > 0 && indices.size() > 0) { ComputeExtremes(static_cast<int32_t>(vertices.size()), vertices.data(), alignedBox.min, alignedBox.max); } } std::vector<Vector3<Real>> vertices; std::vector<int32_t> indices; std::vector<Vector4<Real>> planes; AlignedBox3<Real> alignedBox; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CosEstimate.h
.h
4,593
140
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> // Minimax polynomial approximations to cos(x). The polynomial p(x) of // degree D has only even-power terms, is required to have constant term 1, // and p(pi/2) = cos(pi/2) = 0. It minimizes the quantity // maximum{|cos(x) - p(x)| : x in [-pi/2,pi/2]} over all polynomials of // degree D subject to the constraints mentioned. namespace gte { template <typename Real> class CosEstimate { public: // The input constraint is x in [-pi/2,pi/2]. For example, // float x; // in [-pi/2,pi/2] // float result = CosEstimate<float>::Degree<4>(x); template <int32_t D> inline static Real Degree(Real x) { return Evaluate(degree<D>(), x); } // The input x can be any real number. Range reduction is used to // generate a value y in [-pi/2,pi/2] and a sign s for which // cos(y) = s*cos(x). For example, // float x; // x any real number // float result = CosEstimate<float>::DegreeRR<3>(x); template <int32_t D> inline static Real DegreeRR(Real x) { Real y, sign; Reduce(x, y, sign); Real poly = sign * Degree<D>(y); return poly; } private: // Metaprogramming and private implementation to allow specialization // of a template member function. template <int32_t D> struct degree {}; inline static Real Evaluate(degree<2>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_COS_DEG2_C1; poly = (Real)GTE_C_COS_DEG2_C0 + poly * xsqr; return poly; } inline static Real Evaluate(degree<4>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_COS_DEG4_C2; poly = (Real)GTE_C_COS_DEG4_C1 + poly * xsqr; poly = (Real)GTE_C_COS_DEG4_C0 + poly * xsqr; return poly; } inline static Real Evaluate(degree<6>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_COS_DEG6_C3; poly = (Real)GTE_C_COS_DEG6_C2 + poly * xsqr; poly = (Real)GTE_C_COS_DEG6_C1 + poly * xsqr; poly = (Real)GTE_C_COS_DEG6_C0 + poly * xsqr; return poly; } inline static Real Evaluate(degree<8>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_COS_DEG8_C4; poly = (Real)GTE_C_COS_DEG8_C3 + poly * xsqr; poly = (Real)GTE_C_COS_DEG8_C2 + poly * xsqr; poly = (Real)GTE_C_COS_DEG8_C1 + poly * xsqr; poly = (Real)GTE_C_COS_DEG8_C0 + poly * xsqr; return poly; } inline static Real Evaluate(degree<10>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_COS_DEG10_C5; poly = (Real)GTE_C_COS_DEG10_C4 + poly * xsqr; poly = (Real)GTE_C_COS_DEG10_C3 + poly * xsqr; poly = (Real)GTE_C_COS_DEG10_C2 + poly * xsqr; poly = (Real)GTE_C_COS_DEG10_C1 + poly * xsqr; poly = (Real)GTE_C_COS_DEG10_C0 + poly * xsqr; return poly; } // Support for range reduction. inline static void Reduce(Real x, Real& y, Real& sign) { // Map x to y in [-pi,pi], x = 2*pi*quotient + remainder. Real quotient = (Real)GTE_C_INV_TWO_PI * x; if (x >= (Real)0) { quotient = (Real)((int32_t)(quotient + (Real)0.5)); } else { quotient = (Real)((int32_t)(quotient - (Real)0.5)); } y = x - (Real)GTE_C_TWO_PI * quotient; // Map y to [-pi/2,pi/2] with cos(y) = sign*cos(x). if (y > (Real)GTE_C_HALF_PI) { y = (Real)GTE_C_PI - y; sign = (Real)-1; } else if (y < (Real)-GTE_C_HALF_PI) { y = (Real)-GTE_C_PI - y; sign = (Real)-1; } else { sign = (Real)1; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TriangleKey.h
.h
3,703
123
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FeatureKey.h> // An ordered triangle has V[0] = min(v0, v1, v2). Choose // (V[0], V[1], V[2]) to be a permutation of (v0, v1, v2) so that the final // is one of (v0, v1, v2), (v1, v2, v0) or (v2,v0,v1). The idea is that if // v0 corresponds to (1,0,0), v1 corresponds to (0,1,0), and v2 corresponds // to (0,0,1), the ordering (v0, v1, v2) corresponds to the 3x3 identity // matrix I; the rows are the specified 3-tuples. The permutation // (V[0], V[1], V[2]) induces a permutation of the rows of the identity // matrix to form a permutation matrix P with det(P) = 1 = det(I). // // An unordered triangle stores a permutation of (v0, v1, v2) so that // V[0] < V[1] < V[2]. namespace gte { template <bool Ordered> class TriangleKey : public FeatureKey<3, Ordered> { public: TriangleKey() { this->V = { -1, -1, -1 }; } // This constructor is specialized based on Ordered. explicit TriangleKey(int32_t v0, int32_t v1, int32_t v2) { Initialize(v0, v1, v2); } private: template <bool Dummy = Ordered> typename std::enable_if<Dummy, void>::type Initialize(int32_t v0, int32_t v1, int32_t v2) { if (v0 < v1) { if (v0 < v2) { // v0 is minimum this->V[0] = v0; this->V[1] = v1; this->V[2] = v2; } else { // v2 is minimum this->V[0] = v2; this->V[1] = v0; this->V[2] = v1; } } else { if (v1 < v2) { // v1 is minimum this->V[0] = v1; this->V[1] = v2; this->V[2] = v0; } else { // v2 is minimum this->V[0] = v2; this->V[1] = v0; this->V[2] = v1; } } } template <bool Dummy = Ordered> typename std::enable_if<!Dummy, void>::type Initialize(int32_t v0, int32_t v1, int32_t v2) { if (v0 < v1) { if (v0 < v2) { // v0 is minimum this->V[0] = v0; this->V[1] = std::min(v1, v2); this->V[2] = std::max(v1, v2); } else { // v2 is minimum this->V[0] = v2; this->V[1] = std::min(v0, v1); this->V[2] = std::max(v0, v1); } } else { if (v1 < v2) { // v1 is minimum this->V[0] = v1; this->V[1] = std::min(v2, v0); this->V[2] = std::max(v2, v0); } else { // v2 is minimum this->V[0] = v2; this->V[1] = std::min(v0, v1); this->V[2] = std::max(v0, v1); } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegment3Triangle3.h
.h
2,956
80
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3Triangle3.h> #include <Mathematics/DistPointTriangle.h> #include <Mathematics/Segment.h> // Compute the distance between a segment and a solid triangle in 3D. // // The segment is P0 + t * (P1 - P0) for 0 <= t <= 1. The direction D = P1-P0 // is generally not unit length. // // The triangle has vertices <V[0],V[1],V[2]>. A triangle point is // X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^2 b[i] = 1. // // The closest point on the segment is stored in closest[0] with parameter t. // The closest point on the triangle is closest[1] with barycentric // coordinates (b[0],b[1],b[2]). When there are infinitely many choices for the pair of closest // points, only one of them is returned. namespace gte { template <typename T> class DCPQuery<T, Segment3<T>, Triangle3<T>> { public: using LTQuery = DCPQuery<T, Line3<T>, Triangle3<T>>; using Result = typename LTQuery::Result; Result operator()(Segment3<T> const& segment, Triangle3<T> const& triangle) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector3<T> segDirection = segment.p[1] - segment.p[0]; Line3<T> line(segment.p[0], segDirection); LTQuery ltQuery{}; auto ltOutput = ltQuery(line, triangle); if (ltOutput.parameter >= zero) { if (ltOutput.parameter <= one) { result = ltOutput; } else { DCPQuery<T, Vector3<T>, Triangle3<T>> ptQuery{}; auto ptOutput = ptQuery(segment.p[1], triangle); result.sqrDistance = ptOutput.sqrDistance; result.distance = ptOutput.distance; result.parameter = one; result.barycentric = ptOutput.barycentric; result.closest[0] = segment.p[1]; result.closest[1] = ptOutput.closest[1]; } } else { DCPQuery<T, Vector3<T>, Triangle3<T>> ptQuery{}; auto ptOutput = ptQuery(segment.p[0], triangle); result.sqrDistance = ptOutput.sqrDistance; result.distance = ptOutput.distance; result.parameter = zero; result.barycentric = ptOutput.barycentric; result.closest[0] = segment.p[0]; result.closest[1] = ptOutput.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Mesh.h
.h
27,156
692
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Matrix.h> #include <Mathematics/IndexAttribute.h> #include <Mathematics/VertexAttribute.h> #include <Mathematics/Vector2.h> #include <Mathematics/Vector3.h> // The Mesh class is designed to support triangulations of surfaces of a small // number of topologies. See the documents // https://www.geometrictools.com/MeshDifferentialGeometry.pdf // https://www.geometrictools.com/MeshFactory.pdf // for details. // // You must set the vertex attribute sources before calling Update(). // // The semantic "position" is required and its source must be an array // of Real with at least 3 channels so that positions are computed as // Vector3<Real>. // // The positions are assumed to be parameterized by texture coordinates // (u,v); the position is thought of as a function P(u,v). If texture // coordinates are provided, the semantic must be "tcoord". If texture // coordinates are not provided, default texture coordinates are computed // internally as described in the mesh factory document. // // The frame for the tangent space is optional. All vectors in the frame // must have sources that are arrays of Real with at least 3 channels per // attribute. If normal vectors are provided, the semantic must be // "normal". // // Two options are supported for tangent vectors. The first option is // that the tangents are surface derivatives dP/du and dP/dv, which are // not necessarily unit length or orthogonal. The semantics must be // "dpdu" and "dpdv". The second option is that the tangents are unit // length and orthogonal, with the infrequent possibility that a vertex // is degenerate in that dP/du and dP/dv are linearly dependent. The // semantics must be "tangent" and "bitangent". // // For each provided vertex attribute, a derived class can initialize // that attribute by overriding one of the Initialize*() functions whose // stubs are defined in this class. namespace gte { enum class MeshTopology { ARBITRARY, RECTANGLE, CYLINDER, TORUS, DISK, SPHERE }; class MeshDescription { public: // Constructor for MeshTopology::ARBITRARY. The members topology, // numVertices, and numTriangles are set in the obvious manner. The // members numRows and numCols are set to zero. The remaining members // must be set explicitly by the client. MeshDescription(uint32_t inNumVertices, uint32_t inNumTriangles) : topology(MeshTopology::ARBITRARY), numVertices(inNumVertices), numTriangles(inNumTriangles), wantDynamicTangentSpaceUpdate(false), wantCCW(true), hasTangentSpaceVectors(false), allowUpdateFrame(false), numRows(0), numCols(0), rMax(0), cMax(0), rIncrement(0), constructed(false) { LogAssert(numVertices >= 3 && numTriangles >= 1, "Invalid input."); } // Constructor for topologies other than MeshTopology::ARBITRARY. // Compute the number of vertices and triangles for the mesh based on // the requested number of rows and columns. If the number of rows or // columns is invalid for the specified topology, they are modified to // be valid, in which case inNumRows/numRows and inNumCols/numCols can // differ. If the input topology is MeshTopology::ARBITRARY, then // inNumRows and inNumCols are assigned to numVertices and // numTriangles, respectively, and numRows and numCols are set to // zero. The remaining members must be set explicitly by the client. MeshDescription(MeshTopology inTopology, uint32_t inNumRows, uint32_t inNumCols) : topology(inTopology), numVertices(0), numTriangles(0), vertexAttributes{}, indexAttribute{}, wantDynamicTangentSpaceUpdate(false), wantCCW(true), hasTangentSpaceVectors(false), allowUpdateFrame(false), numRows(0), numCols(0), rMax(0), cMax(0), rIncrement(0), constructed(false) { switch (topology) { case MeshTopology::ARBITRARY: numVertices = inNumRows; numTriangles = inNumCols; numRows = 0; numCols = 0; rMax = 0; cMax = 0; rIncrement = 0; break; case MeshTopology::RECTANGLE: numRows = std::max(inNumRows, 2u); numCols = std::max(inNumCols, 2u); rMax = numRows - 1; cMax = numCols - 1; rIncrement = numCols; numVertices = (rMax + 1) * (cMax + 1); numTriangles = 2 * rMax * cMax; break; case MeshTopology::CYLINDER: numRows = std::max(inNumRows, 2u); numCols = std::max(inNumCols, 3u); rMax = numRows - 1; cMax = numCols; rIncrement = numCols + 1; numVertices = (rMax + 1) * (cMax + 1); numTriangles = 2 * rMax * cMax; break; case MeshTopology::TORUS: numRows = std::max(inNumRows, 2u); numCols = std::max(inNumCols, 3u); rMax = numRows; cMax = numCols; rIncrement = numCols + 1; numVertices = (rMax + 1) * (cMax + 1); numTriangles = 2 * rMax * cMax; break; case MeshTopology::DISK: numRows = std::max(inNumRows, 1u); numCols = std::max(inNumCols, 3u); rMax = numRows - 1; cMax = numCols; rIncrement = numCols + 1; numVertices = (rMax + 1) * (cMax + 1) + 1; numTriangles = 2 * rMax * cMax + numCols; break; case MeshTopology::SPHERE: numRows = std::max(inNumRows, 1u); numCols = std::max(inNumCols, 3u); rMax = numRows - 1; cMax = numCols; rIncrement = numCols + 1; numVertices = (rMax + 1) * (cMax + 1) + 2; numTriangles = 2 * rMax * cMax + 2 * numCols; break; } } MeshTopology topology; uint32_t numVertices; uint32_t numTriangles; std::vector<VertexAttribute> vertexAttributes; IndexAttribute indexAttribute; bool wantDynamicTangentSpaceUpdate; // default: false bool wantCCW; // default: true // For internal use only. bool hasTangentSpaceVectors; bool allowUpdateFrame; uint32_t numRows, numCols; uint32_t rMax, cMax, rIncrement; // After an attempt to construct a Mesh or Mesh-derived object, // examine this value to determine whether the construction was // successful. bool constructed; }; template <typename Real> class Mesh { public: // Construction and destruction. This constructor is for ARBITRARY // topology. The vertices and indices must already be assigned by the // client. Derived classes use the protected constructor, but // assignment of vertices and indices occurs in the derived-class // constructors. Mesh(MeshDescription const& description, std::vector<MeshTopology> const& validTopologies) : mDescription(description), mPositions(nullptr), mNormals(nullptr), mTangents(nullptr), mBitangents(nullptr), mDPDUs(nullptr), mDPDVs(nullptr), mTCoords(nullptr), mPositionStride(0), mNormalStride(0), mTangentStride(0), mBitangentStride(0), mDPDUStride(0), mDPDVStride(0), mTCoordStride(0) { mDescription.constructed = false; for (auto const& topology : validTopologies) { if (mDescription.topology == topology) { mDescription.constructed = true; break; } } LogAssert(mDescription.indexAttribute.source != nullptr, "The mesh needs triangles/indices in Mesh constructor."); // Set sources for the requested vertex attributes. mDescription.hasTangentSpaceVectors = false; mDescription.allowUpdateFrame = mDescription.wantDynamicTangentSpaceUpdate; for (auto const& attribute : mDescription.vertexAttributes) { if (attribute.source != nullptr && attribute.stride > 0) { if (attribute.semantic == "position") { mPositions = reinterpret_cast<Vector3<Real>*>(attribute.source); mPositionStride = attribute.stride; continue; } if (attribute.semantic == "normal") { mNormals = reinterpret_cast<Vector3<Real>*>(attribute.source); mNormalStride = attribute.stride; continue; } if (attribute.semantic == "tangent") { mTangents = reinterpret_cast<Vector3<Real>*>(attribute.source); mTangentStride = attribute.stride; mDescription.hasTangentSpaceVectors = true; continue; } if (attribute.semantic == "bitangent") { mBitangents = reinterpret_cast<Vector3<Real>*>(attribute.source); mBitangentStride = attribute.stride; mDescription.hasTangentSpaceVectors = true; continue; } if (attribute.semantic == "dpdu") { mDPDUs = reinterpret_cast<Vector3<Real>*>(attribute.source); mDPDUStride = attribute.stride; mDescription.hasTangentSpaceVectors = true; continue; } if (attribute.semantic == "dpdv") { mDPDVs = reinterpret_cast<Vector3<Real>*>(attribute.source); mDPDVStride = attribute.stride; mDescription.hasTangentSpaceVectors = true; continue; } if (attribute.semantic == "tcoord") { mTCoords = reinterpret_cast<Vector2<Real>*>(attribute.source); mTCoordStride = attribute.stride; continue; } } } LogAssert(mPositions != nullptr, "The mesh needs positions in Mesh constructor."); // The initial value of allowUpdateFrame is the client request // about wanting dynamic tangent-space updates. If the vertex // attributes do not include tangent-space vectors, then dynamic // updates are not necessary. If tangent-space vectors are // present, the update algorithm requires texture coordinates // (mTCoords must be nonnull) or must compute local coordinates // (mNormals must be nonnull). if (mDescription.allowUpdateFrame) { if (!mDescription.hasTangentSpaceVectors) { mDescription.allowUpdateFrame = false; } if (!mTCoords && !mNormals) { mDescription.allowUpdateFrame = false; } } if (mDescription.allowUpdateFrame) { mUTU.resize(mDescription.numVertices); mDTU.resize(mDescription.numVertices); } } virtual ~Mesh() { } // No copying or assignment is allowed. Mesh(Mesh const&) = delete; Mesh& operator=(Mesh const&) = delete; // Member accessors. inline MeshDescription const& GetDescription() const { return mDescription; } // If the underlying geometric data varies dynamically, call this // function to update whatever vertex attributes are specified by // the vertex pool. void Update() { LogAssert(mDescription.constructed, "The Mesh object failed the construction."); UpdatePositions(); if (mDescription.allowUpdateFrame) { UpdateFrame(); } else if (mNormals) { UpdateNormals(); } // else: The mesh has no frame data, so there is nothing to do. } protected: // Access the vertex attributes. inline Vector3<Real>& Position(uint32_t i) { char* positions = reinterpret_cast<char*>(mPositions); return *reinterpret_cast<Vector3<Real>*>(positions + i * mPositionStride); } inline Vector3<Real>& Normal(uint32_t i) { char* normals = reinterpret_cast<char*>(mNormals); return *reinterpret_cast<Vector3<Real>*>(normals + i * mNormalStride); } inline Vector3<Real>& Tangent(uint32_t i) { char* tangents = reinterpret_cast<char*>(mTangents); return *reinterpret_cast<Vector3<Real>*>(tangents + i * mTangentStride); } inline Vector3<Real>& Bitangent(uint32_t i) { char* bitangents = reinterpret_cast<char*>(mBitangents); return *reinterpret_cast<Vector3<Real>*>(bitangents + i * mBitangentStride); } inline Vector3<Real>& DPDU(uint32_t i) { char* dpdus = reinterpret_cast<char*>(mDPDUs); return *reinterpret_cast<Vector3<Real>*>(dpdus + i * mDPDUStride); } inline Vector3<Real>& DPDV(uint32_t i) { char* dpdvs = reinterpret_cast<char*>(mDPDVs); return *reinterpret_cast<Vector3<Real>*>(dpdvs + i * mDPDVStride); } inline Vector2<Real>& TCoord(uint32_t i) { char* tcoords = reinterpret_cast<char*>(mTCoords); return *reinterpret_cast<Vector2<Real>*>(tcoords + i * mTCoordStride); } // Compute the indices for non-arbitrary topologies. This function is // called by derived classes. void ComputeIndices() { uint32_t t = 0; for (uint32_t r = 0, i = 0; r < mDescription.rMax; ++r) { uint32_t v0 = i, v1 = v0 + 1; i += mDescription.rIncrement; uint32_t v2 = i, v3 = v2 + 1; for (uint32_t c = 0; c < mDescription.cMax; ++c, ++v0, ++v1, ++v2, ++v3) { if (mDescription.wantCCW) { mDescription.indexAttribute.SetTriangle(t++, v0, v1, v2); mDescription.indexAttribute.SetTriangle(t++, v1, v3, v2); } else { mDescription.indexAttribute.SetTriangle(t++, v0, v2, v1); mDescription.indexAttribute.SetTriangle(t++, v1, v2, v3); } } } if (mDescription.topology == MeshTopology::DISK) { uint32_t v0 = 0, v1 = 1, v2 = mDescription.numVertices - 1; for (uint32_t c = 0; c < mDescription.numCols; ++c, ++v0, ++v1) { if (mDescription.wantCCW) { mDescription.indexAttribute.SetTriangle(t++, v0, v2, v1); } else { mDescription.indexAttribute.SetTriangle(t++, v0, v1, v2); } } } else if (mDescription.topology == MeshTopology::SPHERE) { uint32_t v0 = 0, v1 = 1, v2 = mDescription.numVertices - 2; for (uint32_t c = 0; c < mDescription.numCols; ++c, ++v0, ++v1) { if (mDescription.wantCCW) { mDescription.indexAttribute.SetTriangle(t++, v0, v2, v1); } else { mDescription.indexAttribute.SetTriangle(t++, v0, v1, v2); } } v0 = (mDescription.numRows - 1) * mDescription.numCols; v1 = v0 + 1; v2 = mDescription.numVertices - 1; for (uint32_t c = 0; c < mDescription.numCols; ++c, ++v0, ++v1) { if (mDescription.wantCCW) { mDescription.indexAttribute.SetTriangle(t++, v0, v2, v1); } else { mDescription.indexAttribute.SetTriangle(t++, v0, v1, v2); } } } } // The Update() function allows derived classes to use algorithms // different from least-squares fitting to compute the normals (when // no tangent-space information is requested) or to compute the frame // (normals and tangent space). The UpdatePositions() is a stub; the // base-class has no knowledge about how positions should be modified. // A derived class, however, might choose to use dynamic updating // and override UpdatePositions(). The base-class UpdateNormals() // computes vertex normals as averages of area-weighted triangle // normals (nonparametric approach). The base-class UpdateFrame() // uses a least-squares algorithm for estimating the tangent space // (parametric approach). virtual void UpdatePositions() { } virtual void UpdateNormals() { // Compute normal vector as normalized weighted averages of triangle // normal vectors. // Set the normals to zero to allow accumulation of triangle normals. Vector3<Real> zero{ (Real)0, (Real)0, (Real)0 }; for (uint32_t i = 0; i < mDescription.numVertices; ++i) { Normal(i) = zero; } // Accumulate the triangle normals. for (uint32_t t = 0; t < mDescription.numTriangles; ++t) { // Get the positions for the triangle. uint32_t v0, v1, v2; mDescription.indexAttribute.GetTriangle(t, v0, v1, v2); Vector3<Real> P0 = Position(v0); Vector3<Real> P1 = Position(v1); Vector3<Real> P2 = Position(v2); // Get the edge vectors. Vector3<Real> E1 = P1 - P0; Vector3<Real> E2 = P2 - P0; // Compute a triangle normal show length is twice the area of the // triangle. Vector3<Real> triangleNormal = Cross(E1, E2); // Accumulate the triangle normals. Normal(v0) += triangleNormal; Normal(v1) += triangleNormal; Normal(v2) += triangleNormal; } // Normalize the normals. for (uint32_t i = 0; i < mDescription.numVertices; ++i) { Normalize(Normal(i), true); } } virtual void UpdateFrame() { if (!mTCoords) { // We need to compute vertex normals first in order to compute // local texture coordinates. The vertex normals are recomputed // later based on estimated tangent vectors. UpdateNormals(); } // Use the least-squares algorithm to estimate the tangent-space vectors // and, if requested, normal vectors. Matrix<2, 2, Real> zero2x2; // initialized to zero Matrix<3, 2, Real> zero3x2; // initialized to zero std::fill(mUTU.begin(), mUTU.end(), zero2x2); std::fill(mDTU.begin(), mDTU.end(), zero3x2); for (uint32_t t = 0; t < mDescription.numTriangles; ++t) { // Get the positions and differences for the triangle. uint32_t v0, v1, v2; mDescription.indexAttribute.GetTriangle(t, v0, v1, v2); Vector3<Real> P0 = Position(v0); Vector3<Real> P1 = Position(v1); Vector3<Real> P2 = Position(v2); Vector3<Real> D10 = P1 - P0; Vector3<Real> D20 = P2 - P0; Vector3<Real> D21 = P2 - P1; if (mTCoords) { // Get the texture coordinates and differences for the triangle. Vector2<Real> C0 = TCoord(v0); Vector2<Real> C1 = TCoord(v1); Vector2<Real> C2 = TCoord(v2); Vector2<Real> U10 = C1 - C0; Vector2<Real> U20 = C2 - C0; Vector2<Real> U21 = C2 - C1; // Compute the outer products. Matrix<2, 2, Real> outerU10 = OuterProduct(U10, U10); Matrix<2, 2, Real> outerU20 = OuterProduct(U20, U20); Matrix<2, 2, Real> outerU21 = OuterProduct(U21, U21); Matrix<3, 2, Real> outerD10 = OuterProduct(D10, U10); Matrix<3, 2, Real> outerD20 = OuterProduct(D20, U20); Matrix<3, 2, Real> outerD21 = OuterProduct(D21, U21); // Keep a running sum of U^T*U and D^T*U. mUTU[v0] += outerU10 + outerU20; mUTU[v1] += outerU10 + outerU21; mUTU[v2] += outerU20 + outerU21; mDTU[v0] += outerD10 + outerD20; mDTU[v1] += outerD10 + outerD21; mDTU[v2] += outerD20 + outerD21; } else { // Compute local coordinates and differences for the triangle. Vector3<Real> basis[3]; basis[0] = Normal(v0); ComputeOrthogonalComplement(1, basis, true); Vector2<Real> U10{ Dot(basis[1], D10), Dot(basis[2], D10) }; Vector2<Real> U20{ Dot(basis[1], D20), Dot(basis[2], D20) }; mUTU[v0] += OuterProduct(U10, U10) + OuterProduct(U20, U20); mDTU[v0] += OuterProduct(D10, U10) + OuterProduct(D20, U20); basis[0] = Normal(v1); ComputeOrthogonalComplement(1, basis, true); Vector2<Real> U01{ Dot(basis[1], D10), Dot(basis[2], D10) }; Vector2<Real> U21{ Dot(basis[1], D21), Dot(basis[2], D21) }; mUTU[v1] += OuterProduct(U01, U01) + OuterProduct(U21, U21); mDTU[v1] += OuterProduct(D10, U01) + OuterProduct(D21, U21); basis[0] = Normal(v2); ComputeOrthogonalComplement(1, basis, true); Vector2<Real> U02{ Dot(basis[1], D20), Dot(basis[2], D20) }; Vector2<Real> U12{ Dot(basis[1], D21), Dot(basis[2], D21) }; mUTU[v2] += OuterProduct(U02, U02) + OuterProduct(U12, U12); mDTU[v2] += OuterProduct(D20, U02) + OuterProduct(D21, U12); } } for (uint32_t i = 0; i < mDescription.numVertices; ++i) { Matrix<3, 2, Real> jacobian = mDTU[i] * Inverse(mUTU[i]); Vector3<Real> basis[3]; basis[0] = { jacobian(0, 0), jacobian(1, 0), jacobian(2, 0) }; basis[1] = { jacobian(0, 1), jacobian(1, 1), jacobian(2, 1) }; if (mDPDUs) { DPDU(i) = basis[0]; } if (mDPDVs) { DPDV(i) = basis[1]; } ComputeOrthogonalComplement(2, basis, true); if (mNormals) { Normal(i) = basis[2]; } if (mTangents) { Tangent(i) = basis[0]; } if (mBitangents) { Bitangent(i) = basis[1]; } } } // Constructor inputs. // The client requests this via the constructor; however, if it is // requested and the vertex attributes do not contain entries for // "tangent", "bitangent", "dpdu", or "dpdv", then this member is // set to false. MeshDescription mDescription; // Copied from mVertexAttributes when available. Vector3<Real>* mPositions; Vector3<Real>* mNormals; Vector3<Real>* mTangents; Vector3<Real>* mBitangents; Vector3<Real>* mDPDUs; Vector3<Real>* mDPDVs; Vector2<Real>* mTCoords; size_t mPositionStride; size_t mNormalStride; size_t mTangentStride; size_t mBitangentStride; size_t mDPDUStride; size_t mDPDVStride; size_t mTCoordStride; // When dynamic tangent-space updates are requested, the update algorithm // requires texture coordinates (user-specified or non-local). It is // possible to create a vertex-adjacent set (with indices into the // vertex array) for each mesh vertex; however, instead we rely on a // triangle iteration and incrementally store the information needed for // the estimation of the tangent space. Each vertex has associated // matrices D and U, but we need to store only U^T*U and D^T*U. See the // PDF for details. std::vector<Matrix<2, 2, Real>> mUTU; std::vector<Matrix<3, 2, Real>> mDTU; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3Cylinder3.h
.h
10,352
259
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/Cylinder3.h> #include <Mathematics/Vector3.h> // The queries consider the cylinder to be a solid. namespace gte { template <typename T> class FIQuery<T, Line3<T>, Cylinder3<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } bool intersect; size_t numIntersections; std::array<T, 2> parameter; std::array<Vector3<T>, 2> point; }; Result operator()(Line3<T> const& line, Cylinder3<T> const& cylinder) { Result result{}; DoQuery(line.origin, line.direction, cylinder, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& lineOrigin, Vector3<T> const& lineDirection, Cylinder3<T> const& cylinder, Result& result) { // Create a coordinate system for the cylinder. In this system, // the cylinder segment center C is the origin and the cylinder // axis direction W is the z-axis. U and V are the other // coordinate axis directions. If P = x*U+y*V+z*W, the cylinder // is x^2 + y^2 = r^2, where r is the cylinder radius. The end // caps are |z| = h/2, where h is the cylinder height. std::array<Vector3<T>, 3> basis{}; // {W, U, V} basis[0] = cylinder.axis.direction; ComputeOrthogonalComplement(1, basis.data()); auto const& W = basis[0]; auto const& U = basis[1]; auto const& V = basis[2]; T halfHeight = static_cast<T>(0.5) * cylinder.height; T rSqr = cylinder.radius * cylinder.radius; // Convert incoming line origin to capsule coordinates. Vector3<T> diff = lineOrigin - cylinder.axis.origin; Vector3<T> P{ Dot(U, diff), Dot(V, diff), Dot(W, diff) }; // Get the z-value, in cylinder coordinates, of the incoming // line's unit-length direction. T const zero = static_cast<T>(0); T dz = Dot(W, lineDirection); if (std::fabs(dz) == static_cast<T>(1)) { // The line is parallel to the cylinder axis. Determine // whether the line intersects the cylinder end disks. T radialSqrDist = rSqr - P[0] * P[0] - P[1] * P[1]; if (radialSqrDist >= zero) { // The line intersects the cylinder end disks. result.intersect = true; result.numIntersections = 2; if (dz > zero) { result.parameter[0] = -P[2] - halfHeight; result.parameter[1] = -P[2] + halfHeight; } else { result.parameter[0] = P[2] - halfHeight; result.parameter[1] = P[2] + halfHeight; } } // else: The line is outside the cylinder, no intersection. return; } // Convert the incoming line unit-length direction to cylinder // coordinates. Vector3<T> D{ Dot(U, lineDirection), Dot(V, lineDirection), dz }; if (D[2] == zero) { // The line is perpendicular to the cylinder axis. if (std::fabs(P[2]) <= halfHeight) { // Test intersection of line P+t*D with infinite cylinder // x^2+y^2 = r^2. This reduces to computing the roots of a // quadratic equation. If P = (px,py,pz) and // D = (dx,dy,dz), then the quadratic equation is // (dx^2+dy^2)*t^2+2*(px*dx+py*dy)*t+(px^2+py^2-r^2) = 0. T a0 = P[0] * P[0] + P[1] * P[1] - rSqr; T a1 = P[0] * D[0] + P[1] * D[1]; T a2 = D[0] * D[0] + D[1] * D[1]; T discr = a1 * a1 - a0 * a2; if (discr > zero) { // The line intersects the cylinder in two places. result.intersect = true; result.numIntersections = 2; T root = std::sqrt(discr); result.parameter[0] = (-a1 - root) / a2; result.parameter[1] = (-a1 + root) / a2; } else if (discr == zero) { // The line is tangent to the cylinder. result.intersect = true; result.numIntersections = 1; result.parameter[0] = -a1 / a2; result.parameter[1] = result.parameter[0]; } // else: The line does not intersect the cylinder. } // else: The line is outside the planes of the cylinder end // disks. return; } // At this time, the line direction is neither parallel nor // perpendicular to the cylinder axis. The line must // intersect both planes of the end disk, the intersection with // the cylinder being a segment. The t-interval of the segment // is [t0,t1]. // Test for intersections with the planes of the end disks. T t0 = (-halfHeight - P[2]) / D[2]; T xTmp = P[0] + t0 * D[0]; T yTmp = P[1] + t0 * D[1]; if (xTmp * xTmp + yTmp * yTmp <= rSqr) { // Plane intersection inside the bottom cylinder end disk. result.parameter[result.numIntersections++] = t0; } T t1 = (+halfHeight - P[2]) / D[2]; xTmp = P[0] + t1 * D[0]; yTmp = P[1] + t1 * D[1]; if (xTmp * xTmp + yTmp * yTmp <= rSqr) { // Plane intersection inside the top cylinder end disk. result.parameter[result.numIntersections++] = t1; } if (result.numIntersections < 2) { // Test for intersection with the cylinder wall. T a0 = P[0] * P[0] + P[1] * P[1] - rSqr; T a1 = P[0] * D[0] + P[1] * D[1]; T a2 = D[0] * D[0] + D[1] * D[1]; T discr = a1 * a1 - a0 * a2; if (discr > zero) { T root = std::sqrt(discr); T tValue = (-a1 - root) / a2; if (t0 <= t1) { if (t0 <= tValue && tValue <= t1) { result.parameter[result.numIntersections++] = tValue; } } else { if (t1 <= tValue && tValue <= t0) { result.parameter[result.numIntersections++] = tValue; } } if (result.numIntersections < 2) { tValue = (-a1 + root) / a2; if (t0 <= t1) { if (t0 <= tValue && tValue <= t1) { result.parameter[result.numIntersections++] = tValue; } } else { if (t1 <= tValue && tValue <= t0) { result.parameter[result.numIntersections++] = tValue; } } } // else: Line intersects end disk and cylinder wall. } else if (discr == zero) { T tValue = -a1 / a2; if (t0 <= t1) { if (t0 <= tValue && tValue <= t1) { result.parameter[result.numIntersections++] = tValue; } } else { if (t1 <= tValue && tValue <= t0) { result.parameter[result.numIntersections++] = tValue; } } } // else: Line does not intersect cylinder wall. } // else: Line intersects both top and bottom cylinder end disks. if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } } else if (result.numIntersections == 1) { result.intersect = true; result.parameter[1] = result.parameter[0]; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CurveExtractorSquares.h
.h
18,955
471
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/CurveExtractor.h> // The level set extraction algorithm implemented here is described // in Section 3 of the document // https://www.geometrictools.com/Documentation/ExtractLevelCurves.pdf namespace gte { // The image type T must be one of the integer types: int8_t, int16_t, // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations // are performed using int64_t. The type Real is for extraction to // floating-point vertices. template <typename T, typename Real> class CurveExtractorSquares : public CurveExtractor<T, Real> { public: // Convenience type definitions. typedef typename CurveExtractor<T, Real>::Vertex Vertex; typedef typename CurveExtractor<T, Real>::Edge Edge; // The input is a 2D image with lexicographically ordered pixels (x,y) // stored in a linear array. Pixel (x,y) is stored in the array at // location index = x + xBound * y. The inputs xBound and yBound must // each be 2 or larger so that there is at least one image square to // process. The inputPixels must be nonnull and point to contiguous // storage that contains at least xBound * yBound elements. CurveExtractorSquares(int32_t xBound, int32_t yBound, T const* inputPixels) : CurveExtractor<T, Real>(xBound, yBound, inputPixels) { } // Extract level curves and return rational vertices. Use the // base-class Extract if you want real-valued vertices. virtual void Extract(T level, std::vector<Vertex>& vertices, std::vector<Edge>& edges) override { // Adjust the image so that the level set is F(x,y) = 0. int64_t levelI64 = static_cast<int64_t>(level); for (size_t i = 0; i < this->mPixels.size(); ++i) { int64_t inputI64 = static_cast<int64_t>(this->mInputPixels[i]); this->mPixels[i] = inputI64 - levelI64; } vertices.clear(); edges.clear(); for (int32_t y = 0, yp = 1; yp < this->mYBound; ++y, ++yp) { for (int32_t x = 0, xp = 1; xp < this->mXBound; ++x, ++xp) { // Get the image values at the corners of the square. int32_t i00 = x + this->mXBound * y; int32_t i10 = i00 + 1; int32_t i01 = i00 + this->mXBound; int32_t i11 = i10 + this->mXBound; int64_t f00 = this->mPixels[i00]; int64_t f10 = this->mPixels[i10]; int64_t f01 = this->mPixels[i01]; int64_t f11 = this->mPixels[i11]; // Construct the vertices and edges of the level curve in // the square. The x, xp, y and yp values are implicitly // converted from int32_t to int64_t (which is guaranteed to // be correct). ProcessSquare(vertices, edges, x, xp, y, yp, f00, f10, f11, f01); } } } protected: void ProcessSquare(std::vector<Vertex>& vertices, std::vector<Edge>& edges, int64_t x, int64_t xp, int64_t y, int64_t yp, int64_t f00, int64_t f10, int64_t f11, int64_t f01) { int64_t xn0, yn0, xn1, yn1, d0, d1, d2, d3, det; if (f00 != 0) { // convert to case "+***" if (f00 < 0) { f00 = -f00; f10 = -f10; f11 = -f11; f01 = -f01; } if (f10 > 0) { if (f11 > 0) { if (f01 > 0) { // ++++ return; } else if (f01 < 0) { // +++- d0 = f11 - f01; xn0 = f11 * x - f01 * xp; d1 = f00 - f01; yn1 = f00 * yp - f01 * y; this->AddEdge(vertices, edges, xn0, d0, yp, 1, x, 1, yn1, d1); } else { // +++0 this->AddVertex(vertices, x, 1, yp, 1); } } else if (f11 < 0) { d0 = f10 - f11; yn0 = f10 * yp - f11 * y; if (f01 > 0) { // ++-+ d1 = f01 - f11; xn1 = f01 * xp - f11 * x; this->AddEdge(vertices, edges, xp, 1, yn0, d0, xn1, d1, yp, 1); } else if (f01 < 0) { // ++-- d1 = f01 - f00; yn1 = f01 * y - f00 * yp; this->AddEdge(vertices, edges, x, 1, yn1, d1, xp, 1, yn0, d0); } else { // ++-0 this->AddEdge(vertices, edges, x, 1, yp, 1, xp, 1, yn0, d0); } } else { if (f01 > 0) { // ++0+ this->AddVertex(vertices, xp, 1, yp, 1); } else if (f01 < 0) { // ++0- d0 = f01 - f00; yn0 = f01 * y - f00 * yp; this->AddEdge(vertices, edges, xp, 1, yp, 1, x, 1, yn0, d0); } else { // ++00 this->AddEdge(vertices, edges, xp, 1, yp, 1, x, 1, yp, 1); } } } else if (f10 < 0) { d0 = f00 - f10; xn0 = f00 * xp - f10 * x; if (f11 > 0) { d1 = f11 - f10; yn1 = f11 * y - f10 * yp; if (f01 > 0) { // +-++ this->AddEdge(vertices, edges, xn0, d0, y, 1, xp, 1, yn1, d1); } else if (f01 < 0) { // +-+- d3 = f11 - f01; xn1 = f11 * x - f01 * xp; d2 = f01 - f00; yn0 = f01 * y - f00 * yp; if (d0*d3 > 0) { det = xn1 * d0 - xn0 * d3; } else { det = xn0 * d3 - xn1 * d0; } if (det > 0) { this->AddEdge(vertices, edges, xn1, d3, yp, 1, xp, 1, yn1, d1); this->AddEdge(vertices, edges, xn0, d0, y, 1, x, 1, yn0, d2); } else if (det < 0) { this->AddEdge(vertices, edges, xn1, d3, yp, 1, x, 1, yn0, d2); this->AddEdge(vertices, edges, xn0, d0, y, 1, xp, 1, yn1, d1); } else { this->AddEdge(vertices, edges, xn0, d0, yn0, d2, xn0, d0, y, 1); this->AddEdge(vertices, edges, xn0, d0, yn0, d2, xn0, d0, yp, 1); this->AddEdge(vertices, edges, xn0, d0, yn0, d2, x, 1, yn0, d2); this->AddEdge(vertices, edges, xn0, d0, yn0, d2, xp, 1, yn0, d2); } } else { // +-+0 this->AddEdge(vertices, edges, xn0, d0, y, 1, xp, 1, yn1, d1); this->AddVertex(vertices, x, 1, yp, 1); } } else if (f11 < 0) { if (f01 > 0) { // +--+ d1 = f11 - f01; xn1 = f11 * x - f01 * xp; this->AddEdge(vertices, edges, xn0, d0, y, 1, xn1, d1, yp, 1); } else if (f01 < 0) { // +--- d1 = f01 - f00; yn1 = f01 * y - f00 * yp; this->AddEdge(vertices, edges, x, 1, yn1, d1, xn0, d0, y, 1); } else { // +--0 this->AddEdge(vertices, edges, x, 1, yp, 1, xn0, d0, y, 1); } } else { if (f01 > 0) { // +-0+ this->AddEdge(vertices, edges, xp, 1, yp, 1, xn0, d0, y, 1); } else if (f01 < 0) { // +-0- d1 = f01 - f00; yn1 = f01 * y - f00 * yp; this->AddEdge(vertices, edges, x, 1, yn1, d1, xn0, d0, y, 1); this->AddVertex(vertices, xp, 1, yp, 1); } else { // +-00 this->AddEdge(vertices, edges, xp, 1, yp, 1, xn0, d0, yp, 1); this->AddEdge(vertices, edges, xn0, d0, yp, 1, x, 1, yp, 1); this->AddEdge(vertices, edges, xn0, d0, yp, 1, xn0, d0, y, 1); } } } else { if (f11 > 0) { if (f01 > 0) { // +0++ this->AddVertex(vertices, xp, 1, y, 1); } else if (f01 < 0) { // +0+- d0 = f11 - f01; xn0 = f11 * x - f01 * xp; d1 = f00 - f01; yn1 = f00 * yp - f01 * y; this->AddEdge(vertices, edges, xn0, d0, yp, 1, x, 1, yn1, d1); this->AddVertex(vertices, xp, 1, y, 1); } else { // +0+0 this->AddVertex(vertices, xp, 1, y, 1); this->AddVertex(vertices, x, 1, yp, 1); } } else if (f11 < 0) { if (f01 > 0) { // +0-+ d0 = f11 - f01; xn0 = f11 * x - f01 * xp; this->AddEdge(vertices, edges, xp, 1, y, 1, xn0, d0, yp, 1); } else if (f01 < 0) { // +0-- d0 = f01 - f00; yn0 = f01 * y - f00 * yp; this->AddEdge(vertices, edges, xp, 1, y, 1, x, 1, yn0, d0); } else { // +0-0 this->AddEdge(vertices, edges, xp, 1, y, 1, x, 1, yp, 1); } } else { if (f01 > 0) { // +00+ this->AddEdge(vertices, edges, xp, 1, y, 1, xp, 1, yp, 1); } else if (f01 < 0) { // +00- d0 = f00 - f01; yn0 = f00 * yp - f01 * y; this->AddEdge(vertices, edges, xp, 1, y, 1, xp, 1, yn0, d0); this->AddEdge(vertices, edges, xp, 1, yn0, d0, xp, 1, yp, 1); this->AddEdge(vertices, edges, xp, 1, yn0, d0, x, 1, yn0, d0); } else { // +000 this->AddEdge(vertices, edges, x, 1, yp, 1, x, 1, y, 1); this->AddEdge(vertices, edges, x, 1, y, 1, xp, 1, y, 1); } } } } else if (f10 != 0) { // convert to case 0+** if (f10 < 0) { f10 = -f10; f11 = -f11; f01 = -f01; } if (f11 > 0) { if (f01 > 0) { // 0+++ this->AddVertex(vertices, x, 1, y, 1); } else if (f01 < 0) { // 0++- d0 = f11 - f01; xn0 = f11 * x - f01 * xp; this->AddEdge(vertices, edges, x, 1, y, 1, xn0, d0, yp, 1); } else { // 0++0 this->AddEdge(vertices, edges, x, 1, yp, 1, x, 1, y, 1); } } else if (f11 < 0) { if (f01 > 0) { // 0+-+ d0 = f10 - f11; yn0 = f10 * yp - f11 * y; d1 = f01 - f11; xn1 = f01 * xp - f11 * x; this->AddEdge(vertices, edges, xp, 1, yn0, d0, xn1, d1, yp, 1); this->AddVertex(vertices, x, 1, y, 1); } else if (f01 < 0) { // 0+-- d0 = f10 - f11; yn0 = f10 * yp - f11 * y; this->AddEdge(vertices, edges, x, 1, y, 1, xp, 1, yn0, d0); } else { // 0+-0 d0 = f10 - f11; yn0 = f10 * yp - f11 * y; this->AddEdge(vertices, edges, x, 1, y, 1, x, 1, yn0, d0); this->AddEdge(vertices, edges, x, 1, yn0, d0, x, 1, yp, 1); this->AddEdge(vertices, edges, x, 1, yn0, d0, xp, 1, yn0, d0); } } else { if (f01 > 0) { // 0+0+ this->AddVertex(vertices, x, 1, y, 1); this->AddVertex(vertices, xp, 1, yp, 1); } else if (f01 < 0) { // 0+0- this->AddEdge(vertices, edges, x, 1, y, 1, xp, 1, yp, 1); } else { // 0+00 this->AddEdge(vertices, edges, xp, 1, yp, 1, x, 1, yp, 1); this->AddEdge(vertices, edges, x, 1, yp, 1, x, 1, y, 1); } } } else if (f11 != 0) { // convert to case 00+* if (f11 < 0) { f11 = -f11; f01 = -f01; } if (f01 > 0) { // 00++ this->AddEdge(vertices, edges, x, 1, y, 1, xp, 1, y, 1); } else if (f01 < 0) { // 00+- d0 = f01 - f11; xn0 = f01 * xp - f11 * x; this->AddEdge(vertices, edges, x, 1, y, 1, xn0, d0, y, 1); this->AddEdge(vertices, edges, xn0, d0, y, 1, xp, 1, y, 1); this->AddEdge(vertices, edges, xn0, d0, y, 1, xn0, d0, yp, 1); } else { // 00+0 this->AddEdge(vertices, edges, xp, 1, y, 1, xp, 1, yp, 1); this->AddEdge(vertices, edges, xp, 1, yp, 1, x, 1, yp, 1); } } else if (f01 != 0) { // cases 000+ or 000- this->AddEdge(vertices, edges, x, 1, y, 1, xp, 1, y, 1); this->AddEdge(vertices, edges, xp, 1, y, 1, xp, 1, yp, 1); } else { // case 0000 this->AddEdge(vertices, edges, x, 1, y, 1, xp, 1, y, 1); this->AddEdge(vertices, edges, xp, 1, y, 1, xp, 1, yp, 1); this->AddEdge(vertices, edges, xp, 1, yp, 1, x, 1, yp, 1); this->AddEdge(vertices, edges, x, 1, yp, 1, x, 1, y, 1); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSNumber.h
.h
45,754
1,426
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.07.04 #pragma once #include <Mathematics/BitHacks.h> #include <Mathematics/Math.h> #include <Mathematics/IEEEBinary.h> #include <istream> #include <ostream> // The class BSNumber (binary scientific number) is designed to provide exact // arithmetic for robust algorithms, typically those for which we need to know // the exact sign of determinants. The template parameter UInteger must // have support for at least the following public interface. The fstream // objects for Write/Read must be created using std::ios::binary. The return // value of Write/Read is 'true' iff the operation was successful. // // class UInteger // { // public: // UInteger(); // UInteger(UInteger const& number); // UInteger(uint32_t number); // UInteger(uint64_t number); // UInteger& operator=(UInteger const& number); // UInteger(UInteger&& number); // UInteger& operator=(UInteger&& number); // void SetNumBits(int32_t numBits); // int32_t GetNumBits() const; // bool operator==(UInteger const& number) const; // bool operator< (UInteger const& number) const; // void Add(UInteger const& n0, UInteger const& n1); // void Sub(UInteger const& n0, UInteger const& n1); // void Mul(UInteger const& n0, UInteger const& n1); // void ShiftLeft(UInteger const& number, int32_t shift); // int32_t ShiftRightToOdd(UInteger const& number); // int32_t RoundUp(); // uint64_t GetPrefix(int32_t numRequested) const; // bool Write(std::ofstream& output) const; // bool Read(std::ifstream& input); // }; // // GTEngine currently has 32-bits-per-word storage for UInteger. See the // classes UIntegerAP32 (arbitrary precision), UIntegerFP32<N> (fixed // precision), and UIntegerALU32 (arithmetic logic unit shared by the previous // two classes). The document at the following link describes the design, // implementation, and use of BSNumber and BSRational. // https://www.geometrictools.com/Documentation/ArbitraryPrecision.pdf // Support for unit testing algorithm correctness. The invariant for a // nonzero BSNumber is that the UInteger part is a positive odd number. // Expose this define to allow validation of the invariant. #define GTE_VALIDATE_BSNUMBER // Enable this to throw exceptions in ConvertFrom when infinities or NaNs // are the floating-point inputs. BSNumber does not have representations // for these numbers. #define GTE_THROW_ON_CONVERT_FROM_INFINITY_OR_NAN // Support for debugging algorithms that use exact rational arithmetic. Each // BSNumber and BSRational has a double-precision member that is exposed when // the conditional define is enabled. Be aware that this can be very slow // because of the conversion to double-precision whenever new objects are // created by arithmetic operations. As a faster alternative, you can add // temporary code in your algorithms that explicitly convert specific rational // numbers to double precision. //#define GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE namespace gte { template <typename UInteger> class BSRational; template <typename UInteger> class BSNumber { public: // Construction and destruction. The default constructor generates the // zero BSNumber. BSNumber() : mSign(0), mBiasedExponent(0) { #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = 0.0; #endif } BSNumber(float number) { ConvertFrom<IEEEBinary32>(number); #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = static_cast<double>(number); #endif } BSNumber(double number) { ConvertFrom<IEEEBinary64>(number); #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = number; #endif } BSNumber(int32_t number) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = static_cast<double>(number); #endif if (number == 0) { mSign = 0; mBiasedExponent = 0; } else { if (number < 0) { mSign = -1; number = -number; } else { mSign = 1; } mBiasedExponent = BitHacks::GetTrailingBit(number); mUInteger = (uint32_t)number; } #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif } BSNumber(uint32_t number) { if (number == 0) { mSign = 0; mBiasedExponent = 0; } else { mSign = 1; mBiasedExponent = BitHacks::GetTrailingBit(number); mUInteger = number; } #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = static_cast<double>(number); #endif } BSNumber(int64_t number) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = static_cast<double>(number); #endif if (number == 0) { mSign = 0; mBiasedExponent = 0; } else { if (number < 0) { mSign = -1; number = -number; } else { mSign = 1; } mBiasedExponent = BitHacks::GetTrailingBit(number); mUInteger = (uint64_t)number; } #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif } BSNumber(uint64_t number) { if (number == 0) { mSign = 0; mBiasedExponent = 0; } else { mSign = 1; mBiasedExponent = BitHacks::GetTrailingBit(number); mUInteger = number; } #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = static_cast<double>(number); #endif } // The number must be of the form "x" or "+x" or "-x", where x is a // positive integer with nonzero leading digit. BSNumber(std::string const& number) { LogAssert(number.size() > 0, "A number must be specified."); // Get the leading '+' or '-' if it exists. std::string intNumber; int32_t sign; if (number[0] == '+') { intNumber = number.substr(1); sign = +1; LogAssert(intNumber.size() > 1, "Invalid number format."); } else if (number[0] == '-') { intNumber = number.substr(1); sign = -1; LogAssert(intNumber.size() > 1, "Invalid number format."); } else { intNumber = number; sign = +1; } *this = ConvertToInteger(intNumber); mSign = sign; #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = static_cast<double>(*this); #endif } BSNumber(char const* number) : BSNumber(std::string(number)) { } ~BSNumber() = default; // Copy semantics. BSNumber(BSNumber const& number) { *this = number; } BSNumber& operator=(BSNumber const& number) { mSign = number.mSign; mBiasedExponent = number.mBiasedExponent; mUInteger = number.mUInteger; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = number.mValue; #endif return *this; } // Move semantics. BSNumber(BSNumber&& number) noexcept { *this = std::move(number); } BSNumber& operator=(BSNumber&& number) noexcept { mSign = number.mSign; mBiasedExponent = number.mBiasedExponent; mUInteger = std::move(number.mUInteger); number.mSign = 0; number.mBiasedExponent = 0; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = number.mValue; number.mValue = 0.0; #endif return *this; } // Implicit conversions. These always use the default rounding mode, // round-to-nearest-ties-to-even. inline operator float() const { return ConvertTo<IEEEBinary32>(); } inline operator double() const { return ConvertTo<IEEEBinary64>(); } // Member access. inline void SetSign(int32_t sign) { mSign = sign; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } inline int32_t GetSign() const { return mSign; } inline void SetBiasedExponent(int32_t biasedExponent) { mBiasedExponent = biasedExponent; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } inline int32_t GetBiasedExponent() const { return mBiasedExponent; } inline void SetExponent(int32_t exponent) { mBiasedExponent = exponent - mUInteger.GetNumBits() + 1; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } inline int32_t GetExponent() const { return mBiasedExponent + mUInteger.GetNumBits() - 1; } inline UInteger const& GetUInteger() const { return mUInteger; } inline UInteger& GetUInteger() { return mUInteger; } // Comparisons. bool operator==(BSNumber const& number) const { return (mSign == number.mSign ? EqualIgnoreSign(*this, number) : false); } bool operator!=(BSNumber const& number) const { return !operator==(number); } bool operator< (BSNumber const& number) const { if (mSign > 0) { if (number.mSign <= 0) { return false; } // Both numbers are positive. return LessThanIgnoreSign(*this, number); } else if (mSign < 0) { if (number.mSign >= 0) { return true; } // Both numbers are negative. return LessThanIgnoreSign(number, *this); } else { return number.mSign > 0; } } bool operator<=(BSNumber const& number) const { return !number.operator<(*this); } bool operator> (BSNumber const& number) const { return number.operator<(*this); } bool operator>=(BSNumber const& number) const { return !operator<(number); } // Unary operations. BSNumber operator+() const { return *this; } BSNumber operator-() const { BSNumber result = *this; result.mSign = -result.mSign; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) result.mValue = (double)result; #endif return result; } // Arithmetic. BSNumber operator+(BSNumber const& n1) const { BSNumber const& n0 = *this; if (n0.mSign == 0) { return n1; } if (n1.mSign == 0) { return n0; } if (n0.mSign > 0) { if (n1.mSign > 0) { // n0 + n1 = |n0| + |n1| return AddIgnoreSign(n0, n1, +1); } else // n1.mSign < 0 { if (!EqualIgnoreSign(n0, n1)) { if (LessThanIgnoreSign(n1, n0)) { // n0 + n1 = |n0| - |n1| > 0 return SubIgnoreSign(n0, n1, +1); } else { // n0 + n1 = -(|n1| - |n0|) < 0 return SubIgnoreSign(n1, n0, -1); } } // else n0 + n1 = 0 } } else // n0.mSign < 0 { if (n1.mSign < 0) { // n0 + n1 = -(|n0| + |n1|) return AddIgnoreSign(n0, n1, -1); } else // n1.mSign > 0 { if (!EqualIgnoreSign(n0, n1)) { if (LessThanIgnoreSign(n1, n0)) { // n0 + n1 = -(|n0| - |n1|) < 0 return SubIgnoreSign(n0, n1, -1); } else { // n0 + n1 = |n1| - |n0| > 0 return SubIgnoreSign(n1, n0, +1); } } // else n0 + n1 = 0 } } return BSNumber(); // = 0 } BSNumber operator-(BSNumber const& n1) const { BSNumber const& n0 = *this; if (n0.mSign == 0) { return -n1; } if (n1.mSign == 0) { return n0; } if (n0.mSign > 0) { if (n1.mSign < 0) { // n0 - n1 = |n0| + |n1| return AddIgnoreSign(n0, n1, +1); } else // n1.mSign > 0 { if (!EqualIgnoreSign(n0, n1)) { if (LessThanIgnoreSign(n1, n0)) { // n0 - n1 = |n0| - |n1| > 0 return SubIgnoreSign(n0, n1, +1); } else { // n0 - n1 = -(|n1| - |n0|) < 0 return SubIgnoreSign(n1, n0, -1); } } // else n0 - n1 = 0 } } else // n0.mSign < 0 { if (n1.mSign > 0) { // n0 - n1 = -(|n0| + |n1|) return AddIgnoreSign(n0, n1, -1); } else // n1.mSign < 0 { if (!EqualIgnoreSign(n0, n1)) { if (LessThanIgnoreSign(n1, n0)) { // n0 - n1 = -(|n0| - |n1|) < 0 return SubIgnoreSign(n0, n1, -1); } else { // n0 - n1 = |n1| - |n0| > 0 return SubIgnoreSign(n1, n0, +1); } } // else n0 - n1 = 0 } } return BSNumber(); // = 0 } BSNumber operator*(BSNumber const& number) const { BSNumber result; // = 0 int32_t sign = mSign * number.mSign; if (sign != 0) { result.mSign = sign; result.mBiasedExponent = mBiasedExponent + number.mBiasedExponent; result.mUInteger.Mul(mUInteger, number.mUInteger); } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) result.mValue = (double)result; #endif #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(result.IsValid(), "Invalid BSNumber."); #endif return result; } BSNumber& operator+=(BSNumber const& number) { *this = operator+(number); return *this; } BSNumber& operator-=(BSNumber const& number) { *this = operator-(number); return *this; } BSNumber& operator*=(BSNumber const& number) { *this = operator*(number); return *this; } // Disk input/output. The fstream objects should be created using // std::ios::binary. The return value is 'true' iff the operation // was successful. bool Write(std::ostream& output) const { if (output.write((char const*)&mSign, sizeof(mSign)).bad()) { return false; } if (output.write((char const*)&mBiasedExponent, sizeof(mBiasedExponent)).bad()) { return false; } return mUInteger.Write(output); } bool Read(std::istream& input) { if (input.read((char*)&mSign, sizeof(mSign)).bad()) { return false; } if (input.read((char*)&mBiasedExponent, sizeof(mBiasedExponent)).bad()) { return false; } return mUInteger.Read(input); } #if defined(GTE_VALIDATE_BSNUMBER) bool IsValid() const { if (mSign != 0) { return mUInteger.GetNumBits() > 0 && mUInteger.GetSize() > 0 && (mUInteger.GetBits()[0] & 0x00000001u) == 1u; } else { return mBiasedExponent == 0 && mUInteger.GetNumBits() == 0 && mUInteger.GetSize() == 0; } } #endif private: // Helper for converting a string to a BSNumber. The string must be // valid for a nonnegative integer without a leading '+' sign. static BSNumber ConvertToInteger(std::string const& number) { int32_t digit = static_cast<int32_t>(number.back()) - static_cast<int32_t>('0'); BSNumber x(digit); if (number.size() > 1) { LogAssert(number.find_first_of("123456789") == 0, "Invalid number format."); LogAssert(number.find_first_not_of("0123456789") == std::string::npos, "Invalid number format."); BSNumber ten(10), pow10(10); for (size_t i = 1, j = number.size() - 2; i < number.size(); ++i, --j) { digit = static_cast<int32_t>(number[j]) - static_cast<int32_t>('0'); if (digit > 0) { x += BSNumber(digit) * pow10; } pow10 *= ten; } } #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(x.IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) x.mValue = (double)x; #endif return x; } // Helpers for operator==, operator<, operator+, operator-. static bool EqualIgnoreSign(BSNumber const& n0, BSNumber const& n1) { return n0.mBiasedExponent == n1.mBiasedExponent && n0.mUInteger == n1.mUInteger; } static bool LessThanIgnoreSign(BSNumber const& n0, BSNumber const& n1) { int32_t e0 = n0.GetExponent(), e1 = n1.GetExponent(); if (e0 < e1) { return true; } if (e0 > e1) { return false; } return n0.mUInteger < n1.mUInteger; } // Add two positive numbers. static BSNumber AddIgnoreSign(BSNumber const& n0, BSNumber const& n1, int32_t resultSign) { BSNumber result, temp; int32_t diff = n0.mBiasedExponent - n1.mBiasedExponent; if (diff > 0) { temp.mUInteger.ShiftLeft(n0.mUInteger, diff); result.mUInteger.Add(temp.mUInteger, n1.mUInteger); result.mBiasedExponent = n1.mBiasedExponent; } else if (diff < 0) { temp.mUInteger.ShiftLeft(n1.mUInteger, -diff); result.mUInteger.Add(n0.mUInteger, temp.mUInteger); result.mBiasedExponent = n0.mBiasedExponent; } else { temp.mUInteger.Add(n0.mUInteger, n1.mUInteger); int32_t shift = result.mUInteger.ShiftRightToOdd(temp.mUInteger); result.mBiasedExponent = n0.mBiasedExponent + shift; } result.mSign = resultSign; #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(result.IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) result.mValue = (double)result; #endif return result; } // Subtract two positive numbers where n0 > n1. static BSNumber SubIgnoreSign(BSNumber const& n0, BSNumber const& n1, int32_t resultSign) { BSNumber result, temp; int32_t diff = n0.mBiasedExponent - n1.mBiasedExponent; if (diff > 0) { temp.mUInteger.ShiftLeft(n0.mUInteger, diff); result.mUInteger.Sub(temp.mUInteger, n1.mUInteger); result.mBiasedExponent = n1.mBiasedExponent; } else if (diff < 0) { temp.mUInteger.ShiftLeft(n1.mUInteger, -diff); result.mUInteger.Sub(n0.mUInteger, temp.mUInteger); result.mBiasedExponent = n0.mBiasedExponent; } else { temp.mUInteger.Sub(n0.mUInteger, n1.mUInteger); int32_t shift = result.mUInteger.ShiftRightToOdd(temp.mUInteger); result.mBiasedExponent = n0.mBiasedExponent + shift; } result.mSign = resultSign; #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(result.IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) result.mValue = (double)result; #endif return result; } // Support for conversions from floating-point numbers to BSNumber. template <typename IEEE> void ConvertFrom(typename IEEE::FloatType number) { IEEE x(number); // Extract sign s, biased exponent e, and trailing significand t. typename IEEE::UIntType s = x.GetSign(); typename IEEE::UIntType e = x.GetBiased(); typename IEEE::UIntType t = x.GetTrailing(); if (e == 0) { if (t == 0) // zeros { // x = (-1)^s * 0 mSign = 0; mBiasedExponent = 0; } else // subnormal numbers { // x = (-1)^s * 0.t * 2^{1-EXPONENT_BIAS} int32_t last = BitHacks::GetTrailingBit(t); int32_t diff = IEEE::NUM_TRAILING_BITS - last; mSign = (s > 0 ? -1 : 1); mBiasedExponent = IEEE::MIN_SUB_EXPONENT - diff; mUInteger = (t >> last); } } else if (e < IEEE::MAX_BIASED_EXPONENT) // normal numbers { // x = (-1)^s * 1.t * 2^{e-EXPONENT_BIAS} if (t > 0) { int32_t last = BitHacks::GetTrailingBit(t); int32_t diff = IEEE::NUM_TRAILING_BITS - last; mSign = (s > 0 ? -1 : 1); mBiasedExponent = static_cast<int32_t>(e) - IEEE::EXPONENT_BIAS - diff; mUInteger = ((t | IEEE::SUP_TRAILING) >> last); } else { mSign = (s > 0 ? -1 : 1); mBiasedExponent = static_cast<int32_t>(e) - IEEE::EXPONENT_BIAS; mUInteger = (typename IEEE::UIntType)1; } } else // e == MAX_BIASED_EXPONENT, special numbers { if (t == 0) // infinities { // x = (-1)^s * infinity #if defined(GTE_THROW_ON_CONVERT_FROM_INFINITY_OR_NAN) LogError("BSNumber does not have a representation for infinities."); #else // Return (-1)^s * 2^{1+EXPONENT_BIAS} for a graceful // exit. mSign = (s > 0 ? -1 : 1); mBiasedExponent = 1 + IEEE::EXPONENT_BIAS; mUInteger = (typename IEEE::UIntType)1; #endif } else // not-a-number (NaN) { #if defined(GTE_THROW_ON_CONVERT_FROM_INFINITY_OR_NAN) LogError("BSNumber does not have a representation for NaNs."); #else // Return 0 for a graceful exit. mSign = 0; mBiasedExponent = 0; #endif } } } // Support for conversions from BSNumber to floating-point numbers. template <typename IEEE> typename IEEE::FloatType ConvertTo() const { typename IEEE::UIntType s = (mSign < 0 ? 1 : 0); typename IEEE::UIntType e, t; if (mSign != 0) { // The conversions use round-to-nearest-ties-to-even // semantics. int32_t exponent = GetExponent(); if (exponent < IEEE::MIN_EXPONENT) { if (exponent < IEEE::MIN_EXPONENT - 1 || mUInteger.GetNumBits() == 1) { // x = 1.0*2^{MIN_EXPONENT-1}, round to zero. e = 0; t = 0; } else { // Round to min subnormal. e = 0; t = 1; } } else if (exponent < IEEE::MIN_SUB_EXPONENT) { // The second input is in {0, ..., NUM_TRAILING_BITS-1}. t = GetTrailing<IEEE>(0, IEEE::MIN_SUB_EXPONENT - exponent - 1); if (t & IEEE::SUP_TRAILING) { // Leading NUM_SIGNIFICAND_BITS bits were all 1, so // round to min normal. e = 1; t = 0; } else { e = 0; } } else if (exponent <= IEEE::EXPONENT_BIAS) { e = static_cast<uint32_t>(static_cast<typename IEEE::UIntType>(exponent) + IEEE::EXPONENT_BIAS); t = GetTrailing<IEEE>(1, 0); if (t & (IEEE::SUP_TRAILING << 1)) { // Carry-out occurred, so increase exponent by 1 and // shift right to compensate. ++e; t >>= 1; } // Eliminate the leading 1 (implied for normals). t &= ~IEEE::SUP_TRAILING; } else { // Set to infinity. e = IEEE::MAX_BIASED_EXPONENT; t = 0; } } else { // The input is zero. e = 0; t = 0; } IEEE x(s, e, t); return x.number; } template <typename IEEE> typename IEEE::UIntType GetTrailing(int32_t normal, int32_t sigma) const { int32_t const numRequested = IEEE::NUM_SIGNIFICAND_BITS + normal; // We need numRequested bits to determine rounding direction. // These are stored in the high-order bits of 'prefix'. uint64_t prefix = mUInteger.GetPrefix(numRequested); // The first bit index after the implied binary point for // rounding. int32_t diff = numRequested - sigma; int32_t roundBitIndex = 64 - diff; // Determine value based on round-to-nearest-ties-to-even. uint64_t mask = (1ull << roundBitIndex); uint64_t round; if (prefix & mask) { // The first bit of the remainder is 1. if (mUInteger.GetNumBits() == diff) { // The first bit of the remainder is the lowest-order bit // of mBits[0]. Apply the ties-to-even rule. if (prefix & (mask << 1)) { // The last bit of the trailing significand is odd, // so round up. round = 1; } else { // The last bit of the trailing significand is even, // so round down. round = 0; } } else { // The first bit of the remainder is not the lowest-order // bit of mBits[0]. The remainder as a fraction is larger // than 1/2, so round up. round = 1; } } else { // The first bit of the remainder is 0, so round down. round = 0; } // Get the unrounded trailing significand. uint64_t trailing = prefix >> (roundBitIndex + 1); // Apply the rounding. trailing += round; return static_cast<typename IEEE::UIntType>(trailing); } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) public: // List this first so that it shows up first in the debugger watch // window. double mValue; private: #endif // The number 0 is represented by: mSign = 0, mBiasedExponent = 0 and // mUInteger = 0. For nonzero numbers, mSign != 0 and mUInteger > 0. int32_t mSign; int32_t mBiasedExponent; UInteger mUInteger; // BSRational depends on the design of BSNumber, so allow it to have // full access to the implementation. friend class BSRational<UInteger>; }; // Explicit conversion to a user-specified precision. The rounding // mode is one of the flags provided in <cfenv>. The modes are // FE_TONEAREST: round to nearest ties to even // FE_DOWNWARD: round towards negative infinity // FE_TOWARDZERO: round towards zero // FE_UPWARD: round towards positive infinity template <typename UInteger> void Convert(BSNumber<UInteger> const& input, int32_t precision, int32_t roundingMode, BSNumber<UInteger>& output) { if (precision <= 0) { LogError("Precision must be positive."); } int64_t const maxSize = static_cast<int64_t>(UInteger::GetMaxSize()); int64_t const excess = 32LL * maxSize - static_cast<int64_t>(precision); if (excess <= 0) { LogError("The maximum precision has been exceeded."); } if (input.GetSign() == 0) { output = BSNumber<UInteger>(0); return; } // Let p = precision and n+1 be the number of bits of the input. // Compute n+1-p. If it is nonpositive, then the requested precision // is already satisfied by the input. int32_t np1mp = input.GetUInteger().GetNumBits() - precision; if (np1mp <= 0) { output = input; return; } // At this point, the requested number of bits is smaller than the // number of bits in the input. Round the input to the smaller number // of bits using the specified rounding mode. UInteger& outW = output.GetUInteger(); outW.SetNumBits(precision); outW.SetAllBitsToZero(); int32_t const outSize = outW.GetSize(); int32_t const precisionM1 = precision - 1; int32_t const outLeading = precisionM1 % 32; uint32_t outMask = (1 << outLeading); auto& outBits = outW.GetBits(); int32_t outCurrent = outSize - 1; UInteger const& inW = input.GetUInteger(); int32_t const inSize = inW.GetSize(); int32_t const inLeading = (inW.GetNumBits() - 1) % 32; uint32_t inMask = (1 << inLeading); auto const& inBits = inW.GetBits(); int32_t inCurrent = inSize - 1; int32_t lastBit = -1; for (int32_t i = precisionM1; i >= 0; --i) { if (inBits[inCurrent] & inMask) { outBits[outCurrent] |= outMask; lastBit = 1; } else { lastBit = 0; } if (inMask == 0x00000001u) { --inCurrent; inMask = 0x80000000u; } else { inMask >>= 1; } if (outMask == 0x00000001u) { --outCurrent; outMask = 0x80000000u; } else { outMask >>= 1; } } // At this point as a sequence of bits, r = u_{n-p} ... u_0. int32_t sign = input.GetSign(); int32_t outExponent = input.GetExponent(); if (roundingMode == FE_TONEAREST) { // Determine whether u_{n-p} is positive. uint32_t positive = (inBits[inCurrent] & inMask) != 0u; if (positive && (np1mp > 1 || lastBit == 1)) { // round up outExponent += outW.RoundUp(); } // else round down, equivalent to truncating the r bits } else if (roundingMode == FE_UPWARD) { // The remainder r must be positive because n-p >= 0 and u_0 = 1. if (sign > 0) { // round up outExponent += outW.RoundUp(); } // else round down, equivalent to truncating the r bits } else if (roundingMode == FE_DOWNWARD) { // The remainder r must be positive because n-p >= 0 and u_0 = 1. if (sign < 0) { // Round down. This is the round-up operation applied to // w, but the final sign is negative which amounts to // rounding down. outExponent += outW.RoundUp(); } // else round down, equivalent to truncating the r bits } else if (roundingMode != FE_TOWARDZERO) { // Currently, no additional implementation-dependent modes // are supported for rounding. LogError("Implementation-dependent rounding mode not supported."); } // else roundingMode == FE_TOWARDZERO. Truncate the r bits, which // requires no additional work. // Shift the bits if necessary to obtain the invariant that BSNumber // objects have bit patterns that are odd integers. if (outW.GetNumBits() > 0 && (outW.GetBits()[0] & 1u) == 0) { UInteger temp = outW; outExponent += outW.ShiftRightToOdd(temp); } // Do not use SetExponent(outExponent) at this step. The number of // requested bits is 'precision' but outW.GetNumBits() will be // different when round-up occurs, and SetExponent accesses // outW.GetNumBits(). output.SetSign(sign); output.SetBiasedExponent(outExponent - static_cast<int32_t>(precisionM1)); #if defined (GTE_VALIDATE_BSNUMBER) LogAssert(output.IsValid(), "Invalid BSNumber."); #endif #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) output.mValue = static_cast<double>(output); #endif } } namespace std { // TODO: Allow for implementations of the math functions in which a // specified precision is used when computing the result. template <typename UInteger> inline gte::BSNumber<UInteger> acos(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::acos((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> acosh(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::acosh((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> asin(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::asin((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> asinh(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::asinh((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> atan(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::atan((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> atanh(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::atanh((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> atan2(gte::BSNumber<UInteger> const& y, gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::atan2((double)y, (double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> ceil(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::ceil((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> cos(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::cos((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> cosh(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::cosh((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> exp(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::exp((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> exp2(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::exp2((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> fabs(gte::BSNumber<UInteger> const& x) { return (x.GetSign() >= 0 ? x : -x); } template <typename UInteger> inline gte::BSNumber<UInteger> floor(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::floor((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> fmod(gte::BSNumber<UInteger> const& x, gte::BSNumber<UInteger> const& y) { return (gte::BSNumber<UInteger>)std::fmod((double)x, (double)y); } template <typename UInteger> inline gte::BSNumber<UInteger> frexp(gte::BSNumber<UInteger> const& x, int32_t* exponent) { if (x.GetSign() != 0) { gte::BSNumber<UInteger> result = x; *exponent = result.GetExponent() + 1; result.SetExponent(-1); return result; } else { *exponent = 0; return gte::BSNumber<UInteger>(0); } } template <typename UInteger> inline gte::BSNumber<UInteger> ldexp(gte::BSNumber<UInteger> const& x, int32_t exponent) { gte::BSNumber<UInteger> result = x; result.SetBiasedExponent(result.GetBiasedExponent() + exponent); return result; } template <typename UInteger> inline gte::BSNumber<UInteger> log(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::log((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> log2(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::log2((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> log10(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::log10((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> pow(gte::BSNumber<UInteger> const& x, gte::BSNumber<UInteger> const& y) { return (gte::BSNumber<UInteger>)std::pow((double)x, (double)y); } template <typename UInteger> inline gte::BSNumber<UInteger> sin(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::sin((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> sinh(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::sinh((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> sqrt(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::sqrt((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> tan(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::tan((double)x); } template <typename UInteger> inline gte::BSNumber<UInteger> tanh(gte::BSNumber<UInteger> const& x) { return (gte::BSNumber<UInteger>)std::tanh((double)x); } // Type trait that says BSNumber is a signed type. template <typename UInteger> struct is_signed<gte::BSNumber<UInteger>> : true_type {}; } namespace gte { template <typename UInteger> inline BSNumber<UInteger> atandivpi(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)atandivpi((double)x); } template <typename UInteger> inline BSNumber<UInteger> atan2divpi(BSNumber<UInteger> const& y, BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)atan2divpi((double)y, (double)x); } template <typename UInteger> inline BSNumber<UInteger> clamp(BSNumber<UInteger> const& x, BSNumber<UInteger> const& xmin, BSNumber<UInteger> const& xmax) { return (BSNumber<UInteger>)clamp((double)x, (double)xmin, (double)xmax); } template <typename UInteger> inline BSNumber<UInteger> cospi(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)cospi((double)x); } template <typename UInteger> inline BSNumber<UInteger> exp10(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)exp10((double)x); } template <typename UInteger> inline BSNumber<UInteger> invsqrt(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)invsqrt((double)x); } template <typename UInteger> inline int32_t isign(BSNumber<UInteger> const& x) { return isign((double)x); } template <typename UInteger> inline BSNumber<UInteger> saturate(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)saturate((double)x); } template <typename UInteger> inline BSNumber<UInteger> sign(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)sign((double)x); } template <typename UInteger> inline BSNumber<UInteger> sinpi(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)sinpi((double)x); } template <typename UInteger> inline BSNumber<UInteger> sqr(BSNumber<UInteger> const& x) { return (BSNumber<UInteger>)sqr((double)x); } // See the comments in Math.h about trait is_arbitrary_precision. template <typename UInteger> struct is_arbitrary_precision_internal<BSNumber<UInteger>> : std::true_type {}; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSPPolygon2.h
.h
30,008
874
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Vector2.h> #include <Mathematics/EdgeKey.h> #include <list> #include <map> #include <memory> #include <vector> #define GTE_BSPPOLYGON2_ENABLE_DEBUG_PRINT #if defined(GTE_BSPPOLYGON2_ENABLE_DEBUG_PRINT) #include <fstream> #endif namespace gte { template <typename Real> class BSPPolygon2 { public: // vertices typedef Vector2<Real> Vertex; typedef std::map<Vertex, int32_t> VMap; typedef std::vector<Vertex> VArray; // edges typedef EdgeKey<true> Edge; typedef std::map<Edge, int32_t> EMap; typedef std::vector<Edge> EArray; // Construction and destruction. BSPPolygon2(Real epsilon) : mEpsilon(epsilon >= (Real)0 ? epsilon : (Real)0) { } ~BSPPolygon2() { } // Copy semantics. BSPPolygon2(BSPPolygon2 const& polygon) { *this = polygon; } BSPPolygon2& operator=(BSPPolygon2 const& polygon) { mEpsilon = polygon.mEpsilon; mVMap = polygon.mVMap; mVArray = polygon.mVArray; mEMap = polygon.mEMap; mEArray = polygon.mEArray; mTree = (polygon.mTree ? polygon.mTree->GetCopy() : nullptr); return *this; } // Move semantics. BSPPolygon2(BSPPolygon2&& polygon) noexcept { *this = std::move(polygon); } BSPPolygon2& operator=(BSPPolygon2&& polygon) noexcept { mEpsilon = polygon.mEpsilon; mVMap = std::move(polygon.mVMap); mVArray = std::move(polygon.mVArray); mEMap = std::move(polygon.mEMap); mEArray = std::move(polygon.mEArray); mTree = polygon.mTree; polygon.mTree = nullptr; return *this; } // Support for deferred construction. int32_t InsertVertex(Vertex const& vertex) { auto iter = mVMap.find(vertex); if (iter != mVMap.end()) { // Vertex already in map, just return its unique index. return iter->second; } // Vertex not in map, insert it and assign it a unique index. int32_t i = static_cast<int32_t>(mVArray.size()); mVMap.insert(std::make_pair(vertex, i)); mVArray.push_back(vertex); return i; } int32_t InsertEdge(Edge const& edge) { LogAssert(edge.V[0] != edge.V[1], "Degenerate edges not allowed."); auto iter = mEMap.find(edge); if (iter != mEMap.end()) { // Edge already in map, just return its unique index. return iter->second; } // Edge not in map, insert it and assign it a unique index. int32_t i = static_cast<int32_t>(mEArray.size()); mEMap.insert(std::make_pair(edge, i)); mEArray.push_back(edge); return i; } void Finalize() { // The BSPTree2 constructor is badly designed. The '*this' // is passed as non-const but the previous code in this function // passed 'this->mEArray' as const. The mEArray can be modified // via '*this' in the BSPTree2 class, which led to an infinite // loop in a test data set for a bug report. For now, make a // copy of mEArray and pass it. EArray eArray = mEArray; mTree = std::make_shared<BSPTree2>(*this, eArray, mEpsilon); } // Member access. inline int32_t GetNumVertices() const { return static_cast<int32_t>(mVMap.size()); } inline Vertex const& GetVertex(int32_t i) const { return mVArray[i]; } inline int32_t GetNumEdges() const { return static_cast<int32_t>(mEMap.size()); } inline Edge const& GetEdge(int32_t i) const { return mEArray[i]; } // negation BSPPolygon2 operator~() const { LogAssert(mTree != nullptr, "Tree must exist."); BSPPolygon2 neg(mEpsilon); neg.mVMap = mVMap; neg.mVArray = mVArray; for (auto const& element : mEMap) { auto const& edge = element.first; neg.InsertEdge(Edge(edge.V[1], edge.V[0])); } neg.mTree = mTree->GetCopy(); neg.mTree->Negate(); return neg; } // intersection BSPPolygon2 operator&(BSPPolygon2 const& polygon) const { LogAssert(mTree != nullptr, "Tree must exist."); BSPPolygon2 intersect(mEpsilon); GetInsideEdgesFrom(polygon, intersect); polygon.GetInsideEdgesFrom(*this, intersect); intersect.Finalize(); return intersect; } // union BSPPolygon2 operator|(BSPPolygon2 const& polygon) const { return ~(~*this & ~polygon); } // difference BSPPolygon2 operator-(BSPPolygon2 const& polygon) const { return *this & ~polygon; } // exclusive or BSPPolygon2 operator^(BSPPolygon2 const& polygon) const { return (*this - polygon) | (polygon - *this); } // point location (-1 inside, 0 on polygon, 1 outside) int32_t PointLocation(Vertex const& vertex) const { LogAssert(mTree != nullptr, "Tree must exist."); return mTree->PointLocation(*this, vertex); } #if defined(GTE_BSPPOLYGON2_ENABLE_DEBUG_PRINT) // debugging support void Print(std::string const& filename) const { std::ofstream output(filename); int32_t const numVertices = GetNumVertices(); output << "vquantity = " << numVertices << std::endl; for (int32_t i = 0; i < numVertices; ++i) { output << i << " (" << mVArray[i][0] << ',' << mVArray[i][1] << ')' << std::endl; } output << std::endl; int32_t const numEdges = GetNumEdges(); output << "equantity = " << numEdges << std::endl; for (int32_t i = 0; i < numEdges; ++i) { output << " <" << mEArray[i].V[0] << ',' << mEArray[i].V[1] << '>' << std::endl; } output << std::endl; output << "bsp tree" << std::endl; if (mTree) { mTree->Print(output, 0, 'r'); } output << std::endl; output.close(); } #endif private: // Binary space partitioning tree support for polygon Boolean // operations. class BSPTree2 { public: // Construction and destruction. BSPTree2(Real epsilon) : mEpsilon(epsilon >= (Real)0 ? epsilon : (Real)0) { } BSPTree2(BSPPolygon2& polygon, EArray const& edges, Real epsilon) : mEpsilon(epsilon >= (Real)0 ? epsilon : (Real)0) { LogAssert(edges.size() > 0, "Invalid input."); // Construct splitting line from first edge. Vertex end0 = polygon.GetVertex(edges[0].V[0]); Vertex end1 = polygon.GetVertex(edges[0].V[1]); // Add edge to coincident list. mCoincident.push_back(edges[0]); // Split remaining edges. EArray posArray, negArray; for (size_t i = 1; i < edges.size(); ++i) { int32_t v0 = edges[i].V[0]; int32_t v1 = edges[i].V[1]; Vertex vertex0 = polygon.GetVertex(v0); Vertex vertex1 = polygon.GetVertex(v1); Vertex intr; int32_t vmid; switch (Classify(end0, end1, vertex0, vertex1, intr)) { case TRANSVERSE_POSITIVE: // modify edge <V0,V1> to <V0,I>, add new edge <I,V1> vmid = polygon.InsertVertex(intr); if (vmid == v0 || vmid == v1) { // The intersection point is within epsilon of an // endpoint. mCoincident.push_back(edges[i]); } else { polygon.SplitEdge(v0, v1, vmid); posArray.push_back(Edge(vmid, v1)); negArray.push_back(Edge(v0, vmid)); } break; case TRANSVERSE_NEGATIVE: // modify edge <V0,V1> to <V0,I>, add new edge <I,V1> vmid = polygon.InsertVertex(intr); if (vmid == v0 || vmid == v1) { // The intersection point is within epsilon of an // endpoint. mCoincident.push_back(edges[i]); } else { polygon.SplitEdge(v0, v1, vmid); posArray.push_back(Edge(v0, vmid)); negArray.push_back(Edge(vmid, v1)); } break; case ALL_POSITIVE: posArray.push_back(edges[i]); break; case ALL_NEGATIVE: negArray.push_back(edges[i]); break; default: // COINCIDENT mCoincident.push_back(edges[i]); break; } } if (posArray.size() > 0) { mPosChild = std::make_shared<BSPTree2>(polygon, posArray, mEpsilon); } if (negArray.size() > 0) { mNegChild = std::make_shared<BSPTree2>(polygon, negArray, mEpsilon); } } ~BSPTree2() { } // Disallow copying and assignment. Use GetCopy() instead to // obtain a deep copy of the BSP tree. BSPTree2(const BSPTree2&) = delete; BSPTree2& operator= (const BSPTree2&) = delete; std::shared_ptr<BSPTree2> GetCopy() const { auto tree = std::make_shared<BSPTree2>(mEpsilon); tree->mCoincident = mCoincident; if (mPosChild) { tree->mPosChild = mPosChild->GetCopy(); } if (mNegChild) { tree->mNegChild = mNegChild->GetCopy(); } return tree; } // Polygon Boolean operation support. void Negate() { // Reverse coincident edge directions. for (auto& edge : mCoincident) { std::swap(edge.V[0], edge.V[1]); } // Swap positive and negative subtrees. std::swap(mPosChild, mNegChild); if (mPosChild) { mPosChild->Negate(); } if (mNegChild) { mNegChild->Negate(); } } void GetPartition(BSPPolygon2 const& polygon, Vertex const& v0, Vertex const& v1, BSPPolygon2& pos, BSPPolygon2& neg, BSPPolygon2& coSame, BSPPolygon2& coDiff) const { // Construct splitting line from first coincident edge. Vertex end0 = polygon.GetVertex(mCoincident[0].V[0]); Vertex end1 = polygon.GetVertex(mCoincident[0].V[1]); Vertex intr; switch (Classify(end0, end1, v0, v1, intr)) { case TRANSVERSE_POSITIVE: GetPosPartition(polygon, intr, v1, pos, neg, coSame, coDiff); GetNegPartition(polygon, v0, intr, pos, neg, coSame, coDiff); break; case TRANSVERSE_NEGATIVE: GetPosPartition(polygon, v0, intr, pos, neg, coSame, coDiff); GetNegPartition(polygon, intr, v1, pos, neg, coSame, coDiff); break; case ALL_POSITIVE: GetPosPartition(polygon, v0, v1, pos, neg, coSame, coDiff); break; case ALL_NEGATIVE: GetNegPartition(polygon, v0, v1, pos, neg, coSame, coDiff); break; default: // COINCIDENT GetCoPartition(polygon, v0, v1, pos, neg, coSame, coDiff); break; } } // Point-in-polygon support (-1 outside, 0 on polygon, +1 inside). int32_t PointLocation(BSPPolygon2 const& polygon, Vertex const& vertex) const { // Construct splitting line from first coincident edge. Vertex end0 = polygon.GetVertex(mCoincident[0].V[0]); Vertex end1 = polygon.GetVertex(mCoincident[0].V[1]); switch (Classify(end0, end1, vertex)) { case ALL_POSITIVE: if (mPosChild) { return mPosChild->PointLocation(polygon, vertex); } else { return 1; } case ALL_NEGATIVE: if (mNegChild) { return mNegChild->PointLocation(polygon, vertex); } else { return -1; } default: // COINCIDENT return CoPointLocation(polygon, vertex); } } #if defined(GTE_BSPPOLYGON2_ENABLE_DEBUG_PRINT) void Print(std::ofstream& outFile, int32_t level, char type) const { for (size_t i = 0; i < mCoincident.size(); ++i) { for (int32_t j = 0; j < 4 * level; ++j) { outFile << ' '; } outFile << type << " <" << mCoincident[i].V[0] << ',' << mCoincident[i].V[1] << ">" << std::endl; } if (mPosChild) { mPosChild->Print(outFile, level + 1, 'p'); } if (mNegChild) { mNegChild->Print(outFile, level + 1, 'n'); } } #endif private: enum { TRANSVERSE_POSITIVE, TRANSVERSE_NEGATIVE, ALL_POSITIVE, ALL_NEGATIVE, COINCIDENT }; int32_t Classify(Vertex const& end0, Vertex const& end1, Vertex const& v0, Vertex const& v1, Vertex& intr) const { Vertex dir = end1 - end0; Vertex nor = Perp(dir); Vertex diff0 = v0 - end0; Vertex diff1 = v1 - end0; Real d0 = Dot(nor, diff0); Real d1 = Dot(nor, diff1); if (d0 * d1 < (Real)0) { // Edge <V0,V1> transversely crosses line. Compute point // of intersection I = V0 + t*(V1 - V0). Real t = d0 / (d0 - d1); if (t > mEpsilon) { if (t < (Real)1 - mEpsilon) { intr = v0 + t * (v1 - v0); if (d1 > (Real)0) { return TRANSVERSE_POSITIVE; } else { return TRANSVERSE_NEGATIVE; } } else { // T is effectively 1 (numerical round-off issue), // so set d1 = 0 and go on to other cases. d1 = (Real)0; } } else { // T is effectively 0 (numerical round-off issue), so // set d0 = 0 and go on to other cases. d0 = (Real)0; } } if (d0 > (Real)0 || d1 > (Real)0) { // edge on positive side of line return ALL_POSITIVE; } if (d0 < (Real)0 || d1 < (Real)0) { // edge on negative side of line return ALL_NEGATIVE; } return COINCIDENT; } void GetPosPartition(BSPPolygon2 const& polygon, Vertex const& v0, Vertex const& v1, BSPPolygon2& pos, BSPPolygon2& neg, BSPPolygon2& coSame, BSPPolygon2& coDiff) const { if (mPosChild) { mPosChild->GetPartition(polygon, v0, v1, pos, neg, coSame, coDiff); } else { int32_t i0 = pos.InsertVertex(v0); int32_t i1 = pos.InsertVertex(v1); pos.InsertEdge(Edge(i0, i1)); } } void GetNegPartition(BSPPolygon2 const& polygon, Vertex const& v0, Vertex const& v1, BSPPolygon2& pos, BSPPolygon2& neg, BSPPolygon2& coSame, BSPPolygon2& coDiff) const { if (mNegChild) { mNegChild->GetPartition(polygon, v0, v1, pos, neg, coSame, coDiff); } else { int32_t i0 = neg.InsertVertex(v0); int32_t i1 = neg.InsertVertex(v1); neg.InsertEdge(Edge(i0, i1)); } } class Interval { public: Interval(Real inT0, Real inT1, bool inSameDir, bool inTouching) : t0(inT0), t1(inT1), sameDir(inSameDir), touching(inTouching) { } Real t0, t1; bool sameDir, touching; }; void GetCoPartition(BSPPolygon2 const& polygon, Vertex const& v0, Vertex const& v1, BSPPolygon2& pos, BSPPolygon2& neg, BSPPolygon2& coSame, BSPPolygon2& coDiff) const { // Segment the line containing V0 and V1 by the coincident // intervals that intersect <V0,V1>. Vertex dir = v1 - v0; Real tmax = Dot(dir, dir); Vertex end0, end1; Real t0, t1; bool sameDir; std::list<Interval> intervals; typename std::list<Interval>::iterator iter; for (auto const& edge : mCoincident) { end0 = polygon.GetVertex(edge.V[0]); end1 = polygon.GetVertex(edge.V[1]); t0 = Dot(dir, end0 - v0); if (std::fabs(t0) <= mEpsilon) { t0 = (Real)0; } else if (std::fabs(t0 - tmax) <= mEpsilon) { t0 = tmax; } t1 = Dot(dir, end1 - v0); if (std::fabs(t1) <= mEpsilon) { t1 = (Real)0; } else if (std::fabs(t1 - tmax) <= mEpsilon) { t1 = tmax; } sameDir = (t1 > t0); if (!sameDir) { Real save = t0; t0 = t1; t1 = save; } if (t1 > (Real)0 && t0 < tmax) { if (intervals.empty()) { intervals.push_front(Interval(t0, t1, sameDir, true)); } else { for (iter = intervals.begin(); iter != intervals.end(); ++iter) { if (std::fabs(t1 - iter->t0) <= mEpsilon) { t1 = iter->t0; } if (t1 <= iter->t0) { // [t0,t1] is on the left of [I.t0,I.t1] intervals.insert(iter, Interval(t0, t1, sameDir, true)); break; } // Theoretically, the intervals are disjoint // or intersect only at an end point. The // assert makes sure that [t0,t1] is to the // right of [I.t0,I.t1]. if (std::fabs(t0 - iter->t1) <= mEpsilon) { t0 = iter->t1; } LogAssert(t0 >= iter->t1, "Invalid ordering in BSPTree2::GetCoPartition."); auto last = std::prev(intervals.end()); if (iter == last) { intervals.push_back(Interval(t0, t1, sameDir, true)); break; } } } } } if (intervals.empty()) { GetPosPartition(polygon, v0, v1, pos, neg, coSame, coDiff); GetNegPartition(polygon, v0, v1, pos, neg, coSame, coDiff); return; } // Insert outside intervals between the touching intervals. // It is possible that two touching intervals are adjacent, // so this is not just a simple alternation of touching and // outside intervals. Interval& front = intervals.front(); if (front.t0 > (Real)0) { intervals.push_front(Interval((Real)0, front.t0, front.sameDir, false)); } else { front.t0 = (Real)0; } Interval& back = intervals.back(); if (back.t1 < tmax) { intervals.push_back(Interval(back.t1, tmax, back.sameDir, false)); } else { back.t1 = tmax; } typename std::list<Interval>::iterator iter0 = intervals.begin(); typename std::list<Interval>::iterator iter1 = intervals.begin(); for (++iter1; iter1 != intervals.end(); ++iter0, ++iter1) { t0 = iter0->t1; t1 = iter1->t0; if (t1 - t0 > mEpsilon) { iter0 = intervals.insert(iter1, Interval(t0, t1, true, false)); } } // Process the segmentation. Real invTMax = (Real)1 / tmax; t0 = intervals.front().t0 * invTMax; end1 = v0 + (intervals.front().t0 * invTMax) * dir; for (iter = intervals.begin(); iter != intervals.end(); ++iter) { end0 = end1; t1 = iter->t1 * invTMax; end1 = v0 + (iter->t1 * invTMax) * dir; if (iter->touching) { Edge edge; if (iter->sameDir) { edge.V[0] = coSame.InsertVertex(end0); edge.V[1] = coSame.InsertVertex(end1); if (edge.V[0] != edge.V[1]) { coSame.InsertEdge(edge); } } else { edge.V[0] = coDiff.InsertVertex(end1); edge.V[1] = coDiff.InsertVertex(end0); if (edge.V[0] != edge.V[1]) { coDiff.InsertEdge(edge); } } } else { GetPosPartition(polygon, end0, end1, pos, neg, coSame, coDiff); GetNegPartition(polygon, end0, end1, pos, neg, coSame, coDiff); } } } // point-in-polygon support int32_t Classify(Vertex const& end0, Vertex const& end1, Vertex const& vertex) const { Vertex dir = end1 - end0; Vertex nor = Perp(dir); Vertex diff = vertex - end0; Real c = Dot(nor, diff); if (c > mEpsilon) { return ALL_POSITIVE; } if (c < -mEpsilon) { return ALL_NEGATIVE; } return COINCIDENT; } int32_t CoPointLocation(BSPPolygon2 const& polygon, Vertex const& vertex) const { for (auto const& edge : mCoincident) { Vertex end0 = polygon.GetVertex(edge.V[0]); Vertex end1 = polygon.GetVertex(edge.V[1]); Vertex dir = end1 - end0; Vertex diff = vertex - end0; Real tmax = Dot(dir, dir); Real t = Dot(dir, diff); if (-mEpsilon <= t && t <= tmax + mEpsilon) { return 0; } } // It does not matter which subtree you use. if (mPosChild) { return mPosChild->PointLocation(polygon, vertex); } if (mNegChild) { return mNegChild->PointLocation(polygon, vertex); } return 0; } Real mEpsilon; EArray mCoincident; std::shared_ptr<BSPTree2> mPosChild; std::shared_ptr<BSPTree2> mNegChild; }; private: void SplitEdge(int32_t v0, int32_t v1, int32_t vmid) { // Find the edge in the map to get the edge-array index. auto iter = mEMap.find(Edge(v0, v1)); LogAssert(iter != mEMap.end(), "Edge does not exist."); int32_t eIndex = iter->second; // Delete edge <V0,V1>. mEMap.erase(iter); // Insert edge <V0,VM>. mEArray[eIndex].V[1] = vmid; mEMap.insert(std::make_pair(mEArray[eIndex], eIndex)); // Insert edge <VM,V1>. InsertEdge(Edge(vmid, v1)); } void GetInsideEdgesFrom(BSPPolygon2 const& polygon, BSPPolygon2& inside) const { LogAssert(mTree != nullptr, "Tree must exist."); BSPPolygon2 ignore(mEpsilon); const int32_t numEdges = polygon.GetNumEdges(); for (int32_t i = 0; i < numEdges; ++i) { int32_t v0 = polygon.mEArray[i].V[0]; int32_t v1 = polygon.mEArray[i].V[1]; Vertex vertex0 = polygon.mVArray[v0]; Vertex vertex1 = polygon.mVArray[v1]; mTree->GetPartition(*this, vertex0, vertex1, ignore, inside, inside, ignore); } } Real mEpsilon; VMap mVMap; VArray mVArray; EMap mEMap; EArray mEArray; std::shared_ptr<BSPTree2> mTree; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RootsPolynomial.h
.h
41,862
1,070
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> #include <algorithm> #include <cstdint> #include <map> #include <vector> // The Find functions return the number of roots, if any, and this number // of elements of the outputs are valid. If the polynomial is identically // zero, Find returns 1. // // Some root-bounding algorithms for real-valued roots are mentioned next for // the polynomial p(t) = c[0] + c[1]*t + ... + c[d-1]*t^{d-1} + c[d]*t^d. // // 1. The roots must be contained by the interval [-M,M] where // M = 1 + max{|c[0]|, ..., |c[d-1]|}/|c[d]| >= 1 // is called the Cauchy bound. // // 2. You may search for roots in the interval [-1,1]. Define // q(t) = t^d*p(1/t) = c[0]*t^d + c[1]*t^{d-1} + ... + c[d-1]*t + c[d] // The roots of p(t) not in [-1,1] are the roots of q(t) in [-1,1]. // // 3. Between two consecutive roots of the derivative p'(t), say, r0 < r1, // the function p(t) is strictly monotonic on the open interval (r0,r1). // If additionally, p(r0) * p(r1) <= 0, then p(x) has a unique root on // the closed interval [r0,r1]. Thus, one can compute the derivatives // through order d for p(t), find roots for the derivative of order k+1, // then use these to bound roots for the derivative of order k. // // 4. Sturm sequences of polynomials may be used to determine bounds on the // roots. This is a more sophisticated approach to root bounding than item 3. // Moreover, a Sturm sequence allows you to compute the number of real-valued // roots on a specified interval. // // 5. For the low-degree Solve* functions, see // https://www.geometrictools.com/Documentation/LowDegreePolynomialRoots.pdf // FOR INTERNAL USE ONLY (unit testing). Do not define the symbol // GTE_ROOTS_LOW_DEGREE_UNIT_TEST in your own code. #if defined(GTE_ROOTS_LOW_DEGREE_UNIT_TEST) extern void RootsLowDegreeBlock(int32_t); #define GTE_ROOTS_LOW_DEGREE_BLOCK(block) RootsLowDegreeBlock(block) #else #define GTE_ROOTS_LOW_DEGREE_BLOCK(block) #endif namespace gte { template <typename Real> class RootsPolynomial { public: // Low-degree root finders. These use exact rational arithmetic for // theoretically correct root classification. The roots themselves // are computed with mixed types (rational and floating-point // arithmetic). The Rational type must support rational arithmetic // (+, -, *, /); for example, BSRational<UIntegerAP32> suffices. The // Rational class must have single-input constructors where the input // is type Real. This ensures you can call the Solve* functions with // floating-point inputs; they will be converted to Rational // implicitly. The highest-order coefficients must be nonzero // (p2 != 0 for quadratic, p3 != 0 for cubic, and p4 != 0 for // quartic). template <typename Rational> static void SolveQuadratic(Rational const& p0, Rational const& p1, Rational const& p2, std::map<Real, int32_t>& rmMap) { Rational const rat2 = 2; Rational q0 = p0 / p2; Rational q1 = p1 / p2; Rational q1half = q1 / rat2; Rational c0 = q0 - q1half * q1half; std::map<Rational, int32_t> rmLocalMap; SolveDepressedQuadratic(c0, rmLocalMap); rmMap.clear(); for (auto& rm : rmLocalMap) { Rational root = rm.first - q1half; rmMap.insert(std::make_pair((Real)root, rm.second)); } } template <typename Rational> static void SolveCubic(Rational const& p0, Rational const& p1, Rational const& p2, Rational const& p3, std::map<Real, int32_t>& rmMap) { Rational const rat2 = 2, rat3 = 3; Rational q0 = p0 / p3; Rational q1 = p1 / p3; Rational q2 = p2 / p3; Rational q2third = q2 / rat3; Rational c0 = q0 - q2third * (q1 - rat2 * q2third * q2third); Rational c1 = q1 - q2 * q2third; std::map<Rational, int32_t> rmLocalMap; SolveDepressedCubic(c0, c1, rmLocalMap); rmMap.clear(); for (auto& rm : rmLocalMap) { Rational root = rm.first - q2third; rmMap.insert(std::make_pair((Real)root, rm.second)); } } template <typename Rational> static void SolveQuartic(Rational const& p0, Rational const& p1, Rational const& p2, Rational const& p3, Rational const& p4, std::map<Real, int32_t>& rmMap) { Rational const rat2 = 2, rat3 = 3, rat4 = 4, rat6 = 6; Rational q0 = p0 / p4; Rational q1 = p1 / p4; Rational q2 = p2 / p4; Rational q3 = p3 / p4; Rational q3fourth = q3 / rat4; Rational q3fourthSqr = q3fourth * q3fourth; Rational c0 = q0 - q3fourth * (q1 - q3fourth * (q2 - q3fourthSqr * rat3)); Rational c1 = q1 - rat2 * q3fourth * (q2 - rat4 * q3fourthSqr); Rational c2 = q2 - rat6 * q3fourthSqr; std::map<Rational, int32_t> rmLocalMap; SolveDepressedQuartic(c0, c1, c2, rmLocalMap); rmMap.clear(); for (auto& rm : rmLocalMap) { Rational root = rm.first - q3fourth; rmMap.insert(std::make_pair((Real)root, rm.second)); } } // Return only the number of real-valued roots and their // multiplicities. info.size() is the number of real-valued roots // and info[i] is the multiplicity of root corresponding to index i. template <typename Rational> static void GetRootInfoQuadratic(Rational const& p0, Rational const& p1, Rational const& p2, std::vector<int32_t>& info) { Rational const rat2 = 2; Rational q0 = p0 / p2; Rational q1 = p1 / p2; Rational q1half = q1 / rat2; Rational c0 = q0 - q1half * q1half; info.clear(); info.reserve(2); GetRootInfoDepressedQuadratic(c0, info); } template <typename Rational> static void GetRootInfoCubic(Rational const& p0, Rational const& p1, Rational const& p2, Rational const& p3, std::vector<int32_t>& info) { Rational const rat2 = 2, rat3 = 3; Rational q0 = p0 / p3; Rational q1 = p1 / p3; Rational q2 = p2 / p3; Rational q2third = q2 / rat3; Rational c0 = q0 - q2third * (q1 - rat2 * q2third * q2third); Rational c1 = q1 - q2 * q2third; info.clear(); info.reserve(3); GetRootInfoDepressedCubic(c0, c1, info); } template <typename Rational> static void GetRootInfoQuartic(Rational const& p0, Rational const& p1, Rational const& p2, Rational const& p3, Rational const& p4, std::vector<int32_t>& info) { Rational const rat2 = 2, rat3 = 3, rat4 = 4, rat6 = 6; Rational q0 = p0 / p4; Rational q1 = p1 / p4; Rational q2 = p2 / p4; Rational q3 = p3 / p4; Rational q3fourth = q3 / rat4; Rational q3fourthSqr = q3fourth * q3fourth; Rational c0 = q0 - q3fourth * (q1 - q3fourth * (q2 - q3fourthSqr * rat3)); Rational c1 = q1 - rat2 * q3fourth * (q2 - rat4 * q3fourthSqr); Rational c2 = q2 - rat6 * q3fourthSqr; info.clear(); info.reserve(4); GetRootInfoDepressedQuartic(c0, c1, c2, info); } // General equations: sum_{i=0}^{d} c(i)*t^i = 0. The input array 'c' // must have at least d+1 elements and the output array 'root' must // have at least d elements. // Find the roots on (-infinity,+infinity). static int32_t Find(int32_t degree, Real const* c, uint32_t maxIterations, Real* roots) { if (degree >= 0 && c) { Real const zero = (Real)0; while (degree >= 0 && c[degree] == zero) { --degree; } if (degree > 0) { // Compute the Cauchy bound. Real const one = (Real)1; Real invLeading = one / c[degree]; Real maxValue = zero; for (int32_t i = 0; i < degree; ++i) { Real value = std::fabs(c[i] * invLeading); if (value > maxValue) { maxValue = value; } } Real bound = one + maxValue; return FindRecursive(degree, c, -bound, bound, maxIterations, roots); } else if (degree == 0) { // The polynomial is a nonzero constant. return 0; } else { // The polynomial is identically zero. roots[0] = zero; return 1; } } else { // Invalid degree or c. return 0; } } // If you know that p(tmin) * p(tmax) <= 0, then there must be at // least one root in [tmin, tmax]. Compute it using bisection. static bool Find(int32_t degree, Real const* c, Real tmin, Real tmax, uint32_t maxIterations, Real& root) { Real const zero = (Real)0; Real pmin = Evaluate(degree, c, tmin); if (pmin == zero) { root = tmin; return true; } Real pmax = Evaluate(degree, c, tmax); if (pmax == zero) { root = tmax; return true; } if (pmin * pmax > zero) { // It is not known whether the interval bounds a root. return false; } if (tmin >= tmax) { // Invalid ordering of interval endpoitns. return false; } for (uint32_t i = 1; i <= maxIterations; ++i) { root = ((Real)0.5) * (tmin + tmax); // This test is designed for 'float' or 'double' when tmin // and tmax are consecutive floating-point numbers. if (root == tmin || root == tmax) { break; } Real p = Evaluate(degree, c, root); Real product = p * pmin; if (product < zero) { tmax = root; pmax = p; } else if (product > zero) { tmin = root; pmin = p; } else { break; } } return true; } private: // Support for the Solve* functions. template <typename Rational> static void SolveDepressedQuadratic(Rational const& c0, std::map<Rational, int32_t>& rmMap) { Rational const zero = 0; if (c0 < zero) { // Two simple roots. Rational root1 = (Rational)std::sqrt((double)-c0); Rational root0 = -root1; rmMap.insert(std::make_pair(root0, 1)); rmMap.insert(std::make_pair(root1, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(0); } else if (c0 == zero) { // One double root. rmMap.insert(std::make_pair(zero, 2)); GTE_ROOTS_LOW_DEGREE_BLOCK(1); } else // c0 > 0 { // A complex-conjugate pair of roots. // Complex z0 = -q1/2 - i*sqrt(c0); // Complex z0conj = -q1/2 + i*sqrt(c0); GTE_ROOTS_LOW_DEGREE_BLOCK(2); } } template <typename Rational> static void SolveDepressedCubic(Rational const& c0, Rational const& c1, std::map<Rational, int32_t>& rmMap) { // Handle the special case of c0 = 0, in which case the polynomial // reduces to a depressed quadratic. Rational const zero = 0; if (c0 == zero) { SolveDepressedQuadratic(c1, rmMap); auto iter = rmMap.find(zero); if (iter != rmMap.end()) { // The quadratic has a root of zero, so the multiplicity // must be increased. ++iter->second; GTE_ROOTS_LOW_DEGREE_BLOCK(3); } else { // The quadratic does not have a root of zero. Insert the // one for the cubic. rmMap.insert(std::make_pair(zero, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(4); } return; } // Handle the special case of c0 != 0 and c1 = 0. double const oneThird = 1.0 / 3.0; if (c1 == zero) { // One simple real root. Rational root0; if (c0 > zero) { root0 = (Rational)-std::pow((double)c0, oneThird); GTE_ROOTS_LOW_DEGREE_BLOCK(5); } else { root0 = (Rational)std::pow(-(double)c0, oneThird); GTE_ROOTS_LOW_DEGREE_BLOCK(6); } rmMap.insert(std::make_pair(root0, 1)); // One complex conjugate pair. // Complex z0 = root0*(-1 - i*sqrt(3))/2; // Complex z0conj = root0*(-1 + i*sqrt(3))/2; return; } // At this time, c0 != 0 and c1 != 0. Rational const rat2 = 2, rat3 = 3, rat4 = 4, rat27 = 27, rat108 = 108; Rational delta = -(rat4 * c1 * c1 * c1 + rat27 * c0 * c0); if (delta > zero) { // Three simple roots. Rational deltaDiv108 = delta / rat108; Rational betaRe = -c0 / rat2; Rational betaIm = std::sqrt(deltaDiv108); Rational theta = std::atan2(betaIm, betaRe); Rational thetaDiv3 = theta / rat3; double angle = (double)thetaDiv3; Rational cs = (Rational)std::cos(angle); Rational sn = (Rational)std::sin(angle); Rational rhoSqr = betaRe * betaRe + betaIm * betaIm; Rational rhoPowThird = (Rational)std::pow((double)rhoSqr, 1.0 / 6.0); Rational temp0 = rhoPowThird * cs; Rational temp1 = rhoPowThird * sn * (Rational)std::sqrt(3.0); Rational root0 = rat2 * temp0; Rational root1 = -temp0 - temp1; Rational root2 = -temp0 + temp1; rmMap.insert(std::make_pair(root0, 1)); rmMap.insert(std::make_pair(root1, 1)); rmMap.insert(std::make_pair(root2, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(7); } else if (delta < zero) { // One simple root. Rational deltaDiv108 = delta / rat108; Rational temp0 = -c0 / rat2; Rational temp1 = (Rational)std::sqrt(-(double)deltaDiv108); Rational temp2 = temp0 - temp1; Rational temp3 = temp0 + temp1; if (temp2 >= zero) { temp2 = (Rational)std::pow((double)temp2, oneThird); GTE_ROOTS_LOW_DEGREE_BLOCK(8); } else { temp2 = (Rational)-std::pow(-(double)temp2, oneThird); GTE_ROOTS_LOW_DEGREE_BLOCK(9); } if (temp3 >= zero) { temp3 = (Rational)std::pow((double)temp3, oneThird); GTE_ROOTS_LOW_DEGREE_BLOCK(10); } else { temp3 = (Rational)-std::pow(-(double)temp3, oneThird); GTE_ROOTS_LOW_DEGREE_BLOCK(11); } Rational root0 = temp2 + temp3; rmMap.insert(std::make_pair(root0, 1)); // One complex conjugate pair. // Complex z0 = (-root0 - i*sqrt(3*root0*root0+4*c1))/2; // Complex z0conj = (-root0 + i*sqrt(3*root0*root0+4*c1))/2; } else // delta = 0 { // One simple root and one double root. Rational root0 = -rat3 * c0 / (rat2 * c1); Rational root1 = -rat2 * root0; rmMap.insert(std::make_pair(root0, 2)); rmMap.insert(std::make_pair(root1, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(12); } } template <typename Rational> static void SolveDepressedQuartic(Rational const& c0, Rational const& c1, Rational const& c2, std::map<Rational, int32_t>& rmMap) { // Handle the special case of c0 = 0, in which case the polynomial // reduces to a depressed cubic. Rational const zero = 0; if (c0 == zero) { SolveDepressedCubic(c1, c2, rmMap); auto iter = rmMap.find(zero); if (iter != rmMap.end()) { // The cubic has a root of zero, so the multiplicity must // be increased. ++iter->second; GTE_ROOTS_LOW_DEGREE_BLOCK(13); } else { // The cubic does not have a root of zero. Insert the one // for the quartic. rmMap.insert(std::make_pair(zero, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(14); } return; } // Handle the special case of c1 = 0, in which case the quartic is // a biquadratic // x^4 + c1*x^2 + c0 = (x^2 + c2/2)^2 + (c0 - c2^2/4) if (c1 == zero) { SolveBiquadratic(c0, c2, rmMap); return; } // At this time, c0 != 0 and c1 != 0, which is a requirement for // the general solver that must use a root of a special cubic // polynomial. Rational const rat2 = 2, rat4 = 4, rat8 = 8, rat12 = 12, rat16 = 16; Rational const rat27 = 27, rat36 = 36; Rational c0sqr = c0 * c0, c1sqr = c1 * c1, c2sqr = c2 * c2; Rational delta = c1sqr * (-rat27 * c1sqr + rat4 * c2 * (rat36 * c0 - c2sqr)) + rat16 * c0 * (c2sqr * (c2sqr - rat8 * c0) + rat16 * c0sqr); Rational a0 = rat12 * c0 + c2sqr; Rational a1 = rat4 * c0 - c2sqr; if (delta > zero) { if (c2 < zero && a1 < zero) { // Four simple real roots. std::map<Real, int32_t> rmCubicMap; SolveCubic(c1sqr - rat4 * c0 * c2, rat8 * c0, rat4 * c2, -rat8, rmCubicMap); Rational t = (Rational)rmCubicMap.rbegin()->first; Rational alphaSqr = rat2 * t - c2; Rational alpha = (Rational)std::sqrt((double)alphaSqr); double sgnC1; if (c1 > zero) { sgnC1 = 1.0; GTE_ROOTS_LOW_DEGREE_BLOCK(15); } else { sgnC1 = -1.0; GTE_ROOTS_LOW_DEGREE_BLOCK(16); } Rational arg = t * t - c0; Rational beta = (Rational)(sgnC1 * std::sqrt(std::max((double)arg, 0.0))); Rational D0 = alphaSqr - rat4 * (t + beta); Rational sqrtD0 = (Rational)std::sqrt(std::max((double)D0, 0.0)); Rational D1 = alphaSqr - rat4 * (t - beta); Rational sqrtD1 = (Rational)std::sqrt(std::max((double)D1, 0.0)); Rational root0 = (alpha - sqrtD0) / rat2; Rational root1 = (alpha + sqrtD0) / rat2; Rational root2 = (-alpha - sqrtD1) / rat2; Rational root3 = (-alpha + sqrtD1) / rat2; rmMap.insert(std::make_pair(root0, 1)); rmMap.insert(std::make_pair(root1, 1)); rmMap.insert(std::make_pair(root2, 1)); rmMap.insert(std::make_pair(root3, 1)); } else // c2 >= 0 or a1 >= 0 { // Two complex-conjugate pairs. The values alpha, D0 // and D1 are those of the if-block. // Complex z0 = (alpha - i*sqrt(-D0))/2; // Complex z0conj = (alpha + i*sqrt(-D0))/2; // Complex z1 = (-alpha - i*sqrt(-D1))/2; // Complex z1conj = (-alpha + i*sqrt(-D1))/2; GTE_ROOTS_LOW_DEGREE_BLOCK(17); } } else if (delta < zero) { // Two simple real roots, one complex-conjugate pair. std::map<Real, int32_t> rmCubicMap; SolveCubic(c1sqr - rat4 * c0 * c2, rat8 * c0, rat4 * c2, -rat8, rmCubicMap); Rational t = (Rational)rmCubicMap.rbegin()->first; Rational alphaSqr = rat2 * t - c2; Rational alpha = (Rational)std::sqrt(std::max((double)alphaSqr, 0.0)); double sgnC1; if (c1 > zero) { sgnC1 = 1.0; // Leads to BLOCK(18) } else { sgnC1 = -1.0; // Leads to BLOCK(19) } Rational arg = t * t - c0; Rational beta = (Rational)(sgnC1 * std::sqrt(std::max((double)arg, 0.0))); Rational root0, root1; if (sgnC1 > 0.0) { Rational D1 = alphaSqr - rat4 * (t - beta); Rational sqrtD1 = (Rational)std::sqrt(std::max((double)D1, 0.0)); root0 = (-alpha - sqrtD1) / rat2; root1 = (-alpha + sqrtD1) / rat2; // One complex conjugate pair. // Complex z0 = (alpha - i*sqrt(-D0))/2; // Complex z0conj = (alpha + i*sqrt(-D0))/2; GTE_ROOTS_LOW_DEGREE_BLOCK(18); } else { Rational D0 = alphaSqr - rat4 * (t + beta); Rational sqrtD0 = (Rational)std::sqrt(std::max((double)D0, 0.0)); root0 = (alpha - sqrtD0) / rat2; root1 = (alpha + sqrtD0) / rat2; // One complex conjugate pair. // Complex z0 = (-alpha - i*sqrt(-D1))/2; // Complex z0conj = (-alpha + i*sqrt(-D1))/2; GTE_ROOTS_LOW_DEGREE_BLOCK(19); } rmMap.insert(std::make_pair(root0, 1)); rmMap.insert(std::make_pair(root1, 1)); } else // delta = 0 { if (a1 > zero || (c2 > zero && (a1 != zero || c1 != zero))) { // One double real root, one complex-conjugate pair. Rational const rat9 = 9; Rational root0 = -c1 * a0 / (rat9 * c1sqr - rat2 * c2 * a1); rmMap.insert(std::make_pair(root0, 2)); // One complex conjugate pair. // Complex z0 = -root0 - i*sqrt(c2 + root0^2); // Complex z0conj = -root0 + i*sqrt(c2 + root0^2); GTE_ROOTS_LOW_DEGREE_BLOCK(20); } else { Rational const rat3 = 3; if (a0 != zero) { // One double real root, two simple real roots. Rational const rat9 = 9; Rational root0 = -c1 * a0 / (rat9 * c1sqr - rat2 * c2 * a1); Rational alpha = rat2 * root0; Rational beta = c2 + rat3 * root0 * root0; Rational discr = alpha * alpha - rat4 * beta; Rational temp1 = (Rational)std::sqrt((double)discr); Rational root1 = (-alpha - temp1) / rat2; Rational root2 = (-alpha + temp1) / rat2; rmMap.insert(std::make_pair(root0, 2)); rmMap.insert(std::make_pair(root1, 1)); rmMap.insert(std::make_pair(root2, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(21); } else { // One triple real root, one simple real root. Rational root0 = -rat3 * c1 / (rat4 * c2); Rational root1 = -rat3 * root0; rmMap.insert(std::make_pair(root0, 3)); rmMap.insert(std::make_pair(root1, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(22); } } } } template <typename Rational> static void SolveBiquadratic(Rational const& c0, Rational const& c2, std::map<Rational, int32_t>& rmMap) { // Solve 0 = x^4 + c2*x^2 + c0 = (x^2 + c2/2)^2 + a1, where // a1 = c0 - c2^2/2. We know that c0 != 0 at the time of the // function call, so x = 0 is not a root. The condition c1 = 0 // implies the quartic Delta = 256*c0*a1^2. Rational const zero = 0, rat2 = 2, rat256 = 256; Rational c2Half = c2 / rat2; Rational a1 = c0 - c2Half * c2Half; Rational delta = rat256 * c0 * a1 * a1; if (delta > zero) { if (c2 < zero) { if (a1 < zero) { // Four simple roots. Rational temp0 = (Rational)std::sqrt(-(double)a1); Rational temp1 = -c2Half - temp0; Rational temp2 = -c2Half + temp0; Rational root1 = (Rational)std::sqrt((double)temp1); Rational root0 = -root1; Rational root2 = (Rational)std::sqrt((double)temp2); Rational root3 = -root2; rmMap.insert(std::make_pair(root0, 1)); rmMap.insert(std::make_pair(root1, 1)); rmMap.insert(std::make_pair(root2, 1)); rmMap.insert(std::make_pair(root3, 1)); GTE_ROOTS_LOW_DEGREE_BLOCK(23); } else // a1 > 0 { // Two simple complex conjugate pairs. // double thetaDiv2 = atan2(sqrt(a1), -c2/2) / 2.0; // double cs = cos(thetaDiv2), sn = sin(thetaDiv2); // double length = pow(c0, 0.25); // Complex z0 = length*(cs + i*sn); // Complex z0conj = length*(cs - i*sn); // Complex z1 = length*(-cs + i*sn); // Complex z1conj = length*(-cs - i*sn); GTE_ROOTS_LOW_DEGREE_BLOCK(24); } } else // c2 >= 0 { // Two simple complex conjugate pairs. // Complex z0 = -i*sqrt(c2/2 - sqrt(-a1)); // Complex z0conj = +i*sqrt(c2/2 - sqrt(-a1)); // Complex z1 = -i*sqrt(c2/2 + sqrt(-a1)); // Complex z1conj = +i*sqrt(c2/2 + sqrt(-a1)); GTE_ROOTS_LOW_DEGREE_BLOCK(25); } } else if (delta < zero) { // Two simple real roots. Rational temp0 = (Rational)std::sqrt(-(double)a1); Rational temp1 = -c2Half + temp0; Rational root1 = (Rational)std::sqrt((double)temp1); Rational root0 = -root1; rmMap.insert(std::make_pair(root0, 1)); rmMap.insert(std::make_pair(root1, 1)); // One complex conjugate pair. // Complex z0 = -i*sqrt(c2/2 + sqrt(-a1)); // Complex z0conj = +i*sqrt(c2/2 + sqrt(-a1)); GTE_ROOTS_LOW_DEGREE_BLOCK(26); } else // delta = 0 { if (c2 < zero) { // Two double real roots. Rational root1 = (Rational)std::sqrt(-(double)c2Half); Rational root0 = -root1; rmMap.insert(std::make_pair(root0, 2)); rmMap.insert(std::make_pair(root1, 2)); GTE_ROOTS_LOW_DEGREE_BLOCK(27); } else // c2 > 0 { // Two double complex conjugate pairs. // Complex z0 = -i*sqrt(c2/2); // multiplicity 2 // Complex z0conj = +i*sqrt(c2/2); // multiplicity 2 GTE_ROOTS_LOW_DEGREE_BLOCK(28); } } } // Support for the GetNumRoots* functions. template <typename Rational> static void GetRootInfoDepressedQuadratic(Rational const& c0, std::vector<int32_t>& info) { Rational const zero = 0; if (c0 < zero) { // Two simple roots. info.push_back(1); info.push_back(1); } else if (c0 == zero) { // One double root. info.push_back(2); // root is zero } else // c0 > 0 { // A complex-conjugate pair of roots. } } template <typename Rational> static void GetRootInfoDepressedCubic(Rational const& c0, Rational const& c1, std::vector<int32_t>& info) { // Handle the special case of c0 = 0, in which case the polynomial // reduces to a depressed quadratic. Rational const zero = 0; if (c0 == zero) { if (c1 == zero) { info.push_back(3); // triple root of zero } else { info.push_back(1); // simple root of zero GetRootInfoDepressedQuadratic(c1, info); } return; } Rational const rat4 = 4, rat27 = 27; Rational delta = -(rat4 * c1 * c1 * c1 + rat27 * c0 * c0); if (delta > zero) { // Three simple real roots. info.push_back(1); info.push_back(1); info.push_back(1); } else if (delta < zero) { // One simple real root. info.push_back(1); } else // delta = 0 { // One simple real root and one double real root. info.push_back(1); info.push_back(2); } } template <typename Rational> static void GetRootInfoDepressedQuartic(Rational const& c0, Rational const& c1, Rational const& c2, std::vector<int32_t>& info) { // Handle the special case of c0 = 0, in which case the polynomial // reduces to a depressed cubic. Rational const zero = 0; if (c0 == zero) { if (c1 == zero) { if (c2 == zero) { info.push_back(4); // quadruple root of zero } else { info.push_back(2); // double root of zero GetRootInfoDepressedQuadratic(c2, info); } } else { info.push_back(1); // simple root of zero GetRootInfoDepressedCubic(c1, c2, info); } return; } // Handle the special case of c1 = 0, in which case the quartic is // a biquadratic // x^4 + c1*x^2 + c0 = (x^2 + c2/2)^2 + (c0 - c2^2/4) if (c1 == zero) { GetRootInfoBiquadratic(c0, c2, info); return; } // At this time, c0 != 0 and c1 != 0, which is a requirement for // the general solver that must use a root of a special cubic // polynomial. Rational const rat4 = 4, rat8 = 8, rat12 = 12, rat16 = 16; Rational const rat27 = 27, rat36 = 36; Rational c0sqr = c0 * c0, c1sqr = c1 * c1, c2sqr = c2 * c2; Rational delta = c1sqr * (-rat27 * c1sqr + rat4 * c2 * (rat36 * c0 - c2sqr)) + rat16 * c0 * (c2sqr * (c2sqr - rat8 * c0) + rat16 * c0sqr); Rational a0 = rat12 * c0 + c2sqr; Rational a1 = rat4 * c0 - c2sqr; if (delta > zero) { if (c2 < zero && a1 < zero) { // Four simple real roots. info.push_back(1); info.push_back(1); info.push_back(1); info.push_back(1); } else // c2 >= 0 or a1 >= 0 { // Two complex-conjugate pairs. } } else if (delta < zero) { // Two simple real roots, one complex-conjugate pair. info.push_back(1); info.push_back(1); } else // delta = 0 { if (a1 > zero || (c2 > zero && (a1 != zero || c1 != zero))) { // One double real root, one complex-conjugate pair. info.push_back(2); } else { if (a0 != zero) { // One double real root, two simple real roots. info.push_back(2); info.push_back(1); info.push_back(1); } else { // One triple real root, one simple real root. info.push_back(3); info.push_back(1); } } } } template <typename Rational> static void GetRootInfoBiquadratic(Rational const& c0, Rational const& c2, std::vector<int32_t>& info) { // Solve 0 = x^4 + c2*x^2 + c0 = (x^2 + c2/2)^2 + a1, where // a1 = c0 - c2^2/2. We know that c0 != 0 at the time of the // function call, so x = 0 is not a root. The condition c1 = 0 // implies the quartic Delta = 256*c0*a1^2. Rational const zero = 0, rat2 = 2, rat256 = 256; Rational c2Half = c2 / rat2; Rational a1 = c0 - c2Half * c2Half; Rational delta = rat256 * c0 * a1 * a1; if (delta > zero) { if (c2 < zero) { if (a1 < zero) { // Four simple roots. info.push_back(1); info.push_back(1); info.push_back(1); info.push_back(1); } else // a1 > 0 { // Two simple complex conjugate pairs. } } else // c2 >= 0 { // Two simple complex conjugate pairs. } } else if (delta < zero) { // Two simple real roots, one complex conjugate pair. info.push_back(1); info.push_back(1); } else // delta = 0 { if (c2 < zero) { // Two double real roots. info.push_back(2); info.push_back(2); } else // c2 > 0 { // Two double complex conjugate pairs. } } } // Support for the Find functions. static int32_t FindRecursive(int32_t degree, Real const* c, Real tmin, Real tmax, uint32_t maxIterations, Real* roots) { // The base of the recursion. Real const zero = (Real)0; Real root = zero; if (degree == 1) { int32_t numRoots; if (c[1] != zero) { root = -c[0] / c[1]; numRoots = 1; } else if (c[0] == zero) { root = zero; numRoots = 1; } else { numRoots = 0; } if (numRoots > 0 && tmin <= root && root <= tmax) { roots[0] = root; return 1; } return 0; } // Find the roots of the derivative polynomial scaled by 1/degree. // The scaling avoids the factorial growth in the coefficients; // for example, without the scaling, the high-order term x^d // becomes (d!)*x through multiple differentiations. With the // scaling we instead get x. This leads to better numerical // behavior of the root finder. int32_t derivDegree = degree - 1; std::vector<Real> derivCoeff(static_cast<size_t>(derivDegree) + 1); std::vector<Real> derivRoots(derivDegree); for (int32_t i = 0, ip1 = 1; i <= derivDegree; ++i, ++ip1) { derivCoeff[i] = c[ip1] * (Real)(ip1) / (Real)degree; } int32_t numDerivRoots = FindRecursive(degree - 1, &derivCoeff[0], tmin, tmax, maxIterations, &derivRoots[0]); int32_t numRoots = 0; if (numDerivRoots > 0) { // Find root on [tmin,derivRoots[0]]. if (Find(degree, c, tmin, derivRoots[0], maxIterations, root)) { roots[numRoots++] = root; } // Find root on [derivRoots[i],derivRoots[i+1]]. for (int32_t i = 0, ip1 = 1; i <= numDerivRoots - 2; ++i, ++ip1) { if (Find(degree, c, derivRoots[i], derivRoots[ip1], maxIterations, root)) { roots[numRoots++] = root; } } // Find root on [derivRoots[numDerivRoots-1],tmax]. if (Find(degree, c, derivRoots[static_cast<size_t>(numDerivRoots) - 1], tmax, maxIterations, root)) { roots[numRoots++] = root; } } else { // The polynomial is monotone on [tmin,tmax], so has at most one root. if (Find(degree, c, tmin, tmax, maxIterations, root)) { roots[numRoots++] = root; } } return numRoots; } static Real Evaluate(int32_t degree, Real const* c, Real t) { int32_t i = degree; Real result = c[i]; while (--i >= 0) { result = t * result + c[i]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RiemannianGeodesic.h
.h
18,254
454
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/GMatrix.h> #include <Mathematics/LinearSystem.h> #include <functional> // Computing geodesics on a surface is a differential geometric topic that // involves Riemannian geometry. The algorithm for constructing geodesics // that is implemented here uses a multiresolution approach. A description // of the algorithm is in the document // https://www.geometrictools.com/Documentation/RiemannianGeodesics.pdf namespace gte { template <typename Real> class RiemannianGeodesic { public: // Construction and destruction. The input dimension must be two or // larger. RiemannianGeodesic(int32_t dimension) : integralSamples(16), searchSamples(32), derivativeStep((Real)1e-04), subdivisions(7), refinements(8), searchRadius((Real)1), refineCallback([]() {}), mDimension(dimension >= 2 ? dimension : 2), mMetric(mDimension, mDimension), mMetricInverse(mDimension, mDimension), mChristoffel1(mDimension), mChristoffel2(mDimension), mMetricDerivative(mDimension), mMetricInverseExists(true), mSubdivide(0), mRefine(0), mCurrentQuantity(0), mIntegralStep((Real)1 / ((Real)integralSamples - (Real)1)), mSearchStep((Real)1 / (Real)searchSamples), mDerivativeFactor((Real)0.5 / derivativeStep) { LogAssert(dimension >= 2, "Dimension must be at least 2."); for (int32_t i = 0; i < mDimension; ++i) { mChristoffel1[i].SetSize(mDimension, mDimension); mChristoffel2[i].SetSize(mDimension, mDimension); mMetricDerivative[i].SetSize(mDimension, mDimension); } } virtual ~RiemannianGeodesic() { } // Tweakable parameters. // 1. The integral samples are the number of samples used in the // Trapezoid Rule numerical integrator. // 2. The search samples are the number of samples taken along a ray // for the steepest descent algorithm used to refine the vertices // of the polyline approximation to the geodesic curve. // 3. The derivative step is the value of h used for centered // difference approximations df/dx = (f(x+h)-f(x-h))/(2*h) in the // steepest descent algorithm. // 4. The number of subdivisions indicates how many times the polyline // segments should be subdivided. The number of polyline vertices // will be pow(2,subdivisions)+1. // 5. The number of refinements per subdivision. Setting this to a // positive value appears necessary when the geodesic curve has a // large length. // 6. The search radius is the distance over which the steepest // descent algorithm searches for a minimum on the line whose // direction is the estimated gradient. The default of 1 means the // search interval is [-L,L], where L is the length of the gradient. // If the search radius is r, then the interval is [-r*L,r*L]. int32_t integralSamples; // default = 16 int32_t searchSamples; // default = 32 Real derivativeStep; // default = 0.0001 int32_t subdivisions; // default = 7 int32_t refinements; // default = 8 Real searchRadius; // default = 1.0 // The dimension of the manifold. inline int32_t GetDimension() const { return mDimension; } // Returns the length of the line segment connecting the points. Real ComputeSegmentLength(GVector<Real> const& point0, GVector<Real> const& point1) { // The Trapezoid Rule is used for integration of the length // integral. The ComputeMetric function internally modifies // mMetric, which means the qForm values are actually varying // even though diff does not. GVector<Real> diff = point1 - point0; GVector<Real> temp(mDimension); // Evaluate the integrand at point0. ComputeMetric(point0); Real qForm = Dot(diff, mMetric * diff); LogAssert(qForm > (Real)0, "Unexpected condition."); Real length = std::sqrt(qForm); // Evaluate the integrand at point1. ComputeMetric(point1); qForm = Dot(diff, mMetric * diff); LogAssert(qForm > (Real)0, "Unexpected condition."); length += std::sqrt(qForm); length *= (Real)0.5; int32_t imax = integralSamples - 2; for (int32_t i = 1; i <= imax; ++i) { // Evaluate the integrand at point0+t*(point1-point0). Real t = mIntegralStep * static_cast<Real>(i); temp = point0 + t * diff; ComputeMetric(temp); qForm = Dot(diff, mMetric * diff); LogAssert(qForm > (Real)0, "Unexpected condition."); length += std::sqrt(qForm); } length *= mIntegralStep; return length; } // Compute the total length of the polyline. The lengths of the // segments are computed relative to the metric tensor. Real ComputeTotalLength(int32_t quantity, std::vector<GVector<Real>> const& path) { LogAssert(quantity >= 2, "Path must have at least two points."); Real length = ComputeSegmentLength(path[0], path[1]); for (int32_t i = 1, ip1 = 2; ip1 < quantity; ++i, ++ip1) { length += ComputeSegmentLength(path[i], path[ip1]); } return length; } // Returns a polyline approximation to a geodesic curve connecting the // points. void ComputeGeodesic(GVector<Real> const& end0, GVector<Real> const& end1, int32_t& quantity, std::vector<GVector<Real>>& path) { LogAssert(subdivisions < 32, "Exceeds maximum iterations."); quantity = (1 << subdivisions) + 1; path.resize(quantity); for (int32_t i = 0; i < quantity; ++i) { path[i].SetSize(mDimension); } mCurrentQuantity = 2; path[0] = end0; path[1] = end1; for (mSubdivide = 1; mSubdivide <= subdivisions; ++mSubdivide) { // A subdivision essentially doubles the number of points. int32_t newQuantity = 2 * mCurrentQuantity - 1; LogAssert(newQuantity <= quantity, "Unexpected condition."); // Copy the old points so that there are slots for the // midpoints during the subdivision, the slots interleaved // between the old points. for (int32_t i = mCurrentQuantity - 1; i > 0; --i) { size_t twoI = 2 * static_cast<size_t>(i); path[twoI] = path[i]; } // Subdivide the polyline. for (int32_t i = 0; i <= mCurrentQuantity - 2; ++i) { size_t twoI = 2 * static_cast<size_t>(i); Subdivide(path[twoI], path[twoI + 1], path[twoI + 2]); } mCurrentQuantity = newQuantity; // Refine the current polyline vertices. for (mRefine = 1; mRefine <= refinements; ++mRefine) { for (int32_t i = 1, im1 = 0, ip1 = 2; i <= mCurrentQuantity - 2; ++i, ++im1, ++ip1) { Refine(path[im1], path[i], path[ip1]); } } } LogAssert(mCurrentQuantity == quantity, "Unexpected condition."); mSubdivide = 0; mRefine = 0; mCurrentQuantity = 0; } // Start with the midpoint M of the line segment (E0,E1) and use a // steepest descent algorithm to move M so that // Length(E0,M) + Length(M,E1) < Length(E0,E1) // This is essentially a relaxation scheme that inserts points into // the current polyline approximation to the geodesic curve. bool Subdivide(GVector<Real> const& end0, GVector<Real>& mid, GVector<Real> const& end1) { mid = (Real)0.5 * (end0 + end1); auto save = refineCallback; refineCallback = []() {}; bool changed = Refine(end0, mid, end1); refineCallback = save; return changed; } // Apply the steepest descent algorithm to move the midpoint M of the // line segment (E0,E1) so that // Length(E0,M) + Length(M,E1) < Length(E0,E1) // This is essentially a relaxation scheme that inserts points into // the current polyline approximation to the geodesic curve. bool Refine(GVector<Real> const& end0, GVector<Real>& mid, GVector<Real> const& end1) { // Estimate the gradient vector for the function // F(m) = Length(e0,m) + Length(m,e1). GVector<Real> temp = mid; GVector<Real> gradient(mDimension); for (int32_t i = 0; i < mDimension; ++i) { temp[i] = mid[i] + derivativeStep; gradient[i] = ComputeSegmentLength(end0, temp); gradient[i] += ComputeSegmentLength(temp, end1); temp[i] = mid[i] - derivativeStep; gradient[i] -= ComputeSegmentLength(end0, temp); gradient[i] -= ComputeSegmentLength(temp, end1); temp[i] = mid[i]; gradient[i] *= mDerivativeFactor; } // Compute the length sum for the current midpoint. Real length0 = ComputeSegmentLength(end0, mid); Real length1 = ComputeSegmentLength(mid, end1); Real oldLength = length0 + length1; Real tRay, newLength; GVector<Real> pRay(mDimension); Real multiplier = mSearchStep * searchRadius; Real minLength = oldLength; GVector<Real> minPoint = mid; for (int32_t i = -searchSamples; i <= searchSamples; ++i) { tRay = multiplier * static_cast<Real>(i); pRay = mid - tRay * gradient; length0 = ComputeSegmentLength(end0, pRay); length1 = ComputeSegmentLength(end1, pRay); newLength = length0 + length1; if (newLength < minLength) { minLength = newLength; minPoint = pRay; } } mid = minPoint; refineCallback(); return minLength < oldLength; } // A callback that is executed during each call of Refine. std::function<void(void)> refineCallback; // Information to be used during the callback. inline int32_t GetSubdivisionStep() const { return mSubdivide; } inline int32_t GetRefinementStep() const { return mRefine; } inline int32_t GetCurrentQuantity() const { return mCurrentQuantity; } // Curvature computations to measure how close the approximating // polyline is to a geodesic. // Returns the total curvature of the line segment connecting the // points. Real ComputeSegmentCurvature(GVector<Real> const& point0, GVector<Real> const& point1) { // The Trapezoid Rule is used for integration of the curvature // integral. The ComputeIntegrand function internally modifies // mMetric, which means the curvature values are actually varying // even though diff does not. GVector<Real> diff = point1 - point0; GVector<Real> temp(mDimension); // Evaluate the integrand at point0. Real curvature = ComputeIntegrand(point0, diff); // Evaluate the integrand at point1. curvature += ComputeIntegrand(point1, diff); curvature *= (Real)0.5; int32_t imax = integralSamples - 2; for (int32_t i = 1; i <= imax; ++i) { // Evaluate the integrand at point0+t*(point1-point0). Real t = mIntegralStep * static_cast<Real>(i); temp = point0 + t * diff; curvature += ComputeIntegrand(temp, diff); } curvature *= mIntegralStep; return curvature; } // Compute the total curvature of the polyline. The curvatures of the // segments are computed relative to the metric tensor. Real ComputeTotalCurvature(int32_t quantity, std::vector<GVector<Real>> const& path) { LogAssert(quantity >= 2, "Path must have at least two points."); Real curvature = ComputeSegmentCurvature(path[0], path[1]); for (int32_t i = 1, ip1 = 2; ip1 < quantity; ++i, ++ip1) { curvature += ComputeSegmentCurvature(path[i], path[ip1]); } return curvature; } protected: // Support for ComputeSegmentCurvature. Real ComputeIntegrand(GVector<Real> const& pos, GVector<Real> const& der) { ComputeMetric(pos); ComputeChristoffel1(pos); ComputeMetricInverse(); ComputeChristoffel2(); // g_{ij}*der_{i}*der_{j} Real qForm0 = Dot(der, mMetric * der); LogAssert(qForm0 > (Real)0, "Unexpected condition."); // gamma_{kij}*der_{k}*der_{i}*der_{j} GMatrix<Real> mat(mDimension, mDimension); for (int32_t k = 0; k < mDimension; ++k) { mat += der[k] * mChristoffel1[k]; } // This product can be negative because mat is not guaranteed to // be positive semidefinite. No assertion is added. Real qForm1 = Dot(der, mat * der); Real ratio = -qForm1 / qForm0; // Compute the acceleration. GVector<Real> acc = ratio * der; for (int32_t k = 0; k < mDimension; ++k) { acc[k] += Dot(der, mChristoffel2[k] * der); } // Compute the curvature. Real curvature = std::sqrt(Dot(acc, mMetric * acc)); return curvature; } // Compute the metric tensor for the specified point. Derived classes // are responsible for implementing this function. virtual void ComputeMetric(GVector<Real> const& point) = 0; // Compute the Christoffel symbols of the first kind for the current // point. Derived classes are responsible for implementing this // function. virtual void ComputeChristoffel1(GVector<Real> const& point) = 0; // Compute the inverse of the current metric tensor. The function // returns 'true' iff the inverse exists. bool ComputeMetricInverse() { mMetricInverse = Inverse(mMetric, &mMetricInverseExists); return mMetricInverseExists; } // Compute the derivative of the metric tensor for the current state. // This is a triply indexed quantity, the values computed using the // Christoffel symbols of the first kind. void ComputeMetricDerivative() { for (int32_t derivative = 0; derivative < mDimension; ++derivative) { for (int32_t i0 = 0; i0 < mDimension; ++i0) { for (int32_t i1 = 0; i1 < mDimension; ++i1) { mMetricDerivative[derivative](i0, i1) = mChristoffel1[derivative](i0, i1) + mChristoffel1[derivative](i1, i0); } } } } // Compute the Christoffel symbols of the second kind for the current // state. The values depend on the inverse of the metric tensor, so // they may be computed only when the inverse exists. The function // returns 'true' whenever the inverse metric tensor exists. bool ComputeChristoffel2() { for (int32_t i2 = 0; i2 < mDimension; ++i2) { for (int32_t i0 = 0; i0 < mDimension; ++i0) { for (int32_t i1 = 0; i1 < mDimension; ++i1) { Real fValue = (Real)0; for (int32_t j = 0; j < mDimension; ++j) { fValue += mMetricInverse(i2, j) * mChristoffel1[j](i0, i1); } mChristoffel2[i2](i0, i1) = fValue; } } } return mMetricInverseExists; } int32_t mDimension; GMatrix<Real> mMetric; GMatrix<Real> mMetricInverse; std::vector<GMatrix<Real>> mChristoffel1; std::vector<GMatrix<Real>> mChristoffel2; std::vector<GMatrix<Real>> mMetricDerivative; bool mMetricInverseExists; // Progress parameters that are useful to mRefineCallback. int32_t mSubdivide, mRefine, mCurrentQuantity; // Derived tweaking parameters. Real mIntegralStep; // = 1/(mIntegralQuantity-1) Real mSearchStep; // = 1/mSearchQuantity Real mDerivativeFactor; // = 1/(2*mDerivativeStep) }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprOrthogonalLine3.h
.h
4,824
130
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/Line.h> #include <Mathematics/SymmetricEigensolver3x3.h> #include <Mathematics/Vector3.h> // Least-squares fit of a line to (x,y,z) data by using distance measurements // orthogonal to the proposed line. The return value is 'true' if and only if // the fit is unique (always successful, 'true' when a minimum eigenvalue is // unique). The mParameters value is a line with (P,D) = (origin,direction). // The error for S = (x0,y0,z0) is (S-P)^T*(I - D*D^T)*(S-P). namespace gte { template <typename Real> class ApprOrthogonalLine3 : public ApprQuery<Real, Vector3<Real>> { public: // Initialize the model parameters to zero. ApprOrthogonalLine3() : mParameters(Vector3<Real>::Zero(), Vector3<Real>::Zero()) { } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numPoints, Vector3<Real> const* points, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numPoints, points, numIndices, indices)) { // Compute the mean of the points. Vector3<Real> mean = Vector3<Real>::Zero(); int32_t const* currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { mean += points[*currentIndex++]; } Real invSize = (Real)1 / (Real)numIndices; mean *= invSize; if (std::isfinite(mean[0]) && std::isfinite(mean[1])) { // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (Real)0; currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { Vector3<Real> diff = points[*currentIndex++] - mean; covar00 += diff[0] * diff[0]; covar01 += diff[0] * diff[1]; covar02 += diff[0] * diff[2]; covar11 += diff[1] * diff[1]; covar12 += diff[1] * diff[2]; covar22 += diff[2] * diff[2]; } covar00 *= invSize; covar01 *= invSize; covar02 *= invSize; covar11 *= invSize; covar12 *= invSize; covar22 *= invSize; // Solve the eigensystem. SymmetricEigensolver3x3<Real> es; std::array<Real, 3> eval; std::array<std::array<Real, 3>, 3> evec; es(covar00, covar01, covar02, covar11, covar12, covar22, false, +1, eval, evec); // The line direction is the eigenvector in the direction // of largest variance of the points. mParameters.origin = mean; mParameters.direction = evec[2]; // The fitted line is unique when the maximum eigenvalue // has multiplicity 1. return eval[1] < eval[2]; } } mParameters = Line3<Real>(Vector3<Real>::Zero(), Vector3<Real>::Zero()); return false; } // Get the parameters for the best fit. Line3<Real> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return 2; } virtual Real Error(Vector3<Real> const& point) const override { Vector3<Real> diff = point - mParameters.origin; Real sqrlen = Dot(diff, diff); Real dot = Dot(diff, mParameters.direction); Real error = std::fabs(sqrlen - dot * dot); return error; } virtual void CopyParameters(ApprQuery<Real, Vector3<Real>> const* input) override { auto source = dynamic_cast<ApprOrthogonalLine3<Real> const*>(input); if (source) { *this = *source; } } private: Line3<Real> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CurvatureFlow3.h
.h
2,496
62
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/PdeFilter3.h> namespace gte { template <typename Real> class CurvatureFlow3 : public PdeFilter3<Real> { public: CurvatureFlow3(int32_t xBound, int32_t yBound, int32_t zBound, Real xSpacing, Real ySpacing, Real zSpacing, Real const* data, int32_t const* mask, Real borderValue, typename PdeFilter<Real>::ScaleType scaleType) : PdeFilter3<Real>(xBound, yBound, zBound, xSpacing, ySpacing, zSpacing, data, mask, borderValue, scaleType) { } virtual ~CurvatureFlow3() { } protected: virtual void OnUpdateSingle(int32_t x, int32_t y, int32_t z) override { this->LookUp27(x, y, z); Real ux = this->mHalfInvDx * (this->mUpzz - this->mUmzz); Real uy = this->mHalfInvDy * (this->mUzpz - this->mUzmz); Real uz = this->mHalfInvDz * (this->mUzzp - this->mUzzm); Real uxx = this->mInvDxDx * (this->mUpzz - (Real)2 * this->mUzzz + this->mUmzz); Real uxy = this->mFourthInvDxDy * (this->mUmmz + this->mUppz - this->mUpmz - this->mUmpz); Real uxz = this->mFourthInvDxDz * (this->mUmzm + this->mUpzp - this->mUpzm - this->mUmzp); Real uyy = this->mInvDyDy * (this->mUzpz - (Real)2 * this->mUzzz + this->mUzmz); Real uyz = this->mFourthInvDyDz * (this->mUzmm + this->mUzpp - this->mUzpm - this->mUzmp); Real uzz = this->mInvDzDz * (this->mUzzp - (Real)2 * this->mUzzz + this->mUzzm); Real denom = ux * ux + uy * uy + uz * uz; if (denom > (Real)0) { Real numer0 = uy * (uxx*uy - uxy * ux) + ux * (uyy*ux - uxy * uy); Real numer1 = uz * (uxx*uz - uxz * ux) + ux * (uzz*ux - uxz * uz); Real numer2 = uz * (uyy*uz - uyz * uy) + uy * (uzz*uy - uyz * uz); Real numer = numer0 + numer1 + numer2; this->mBuffer[this->mDst][z][y][x] = this->mUzzz + this->mTimeStep * numer / denom; } else { this->mBuffer[this->mDst][z][y][x] = this->mUzzz; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSRational.h
.h
32,756
1,046
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/BSNumber.h> // See the comments in BSNumber.h about the UInteger requirements. The // denominator of a BSRational is chosen to be positive, which allows some // simplification of comparisons. Also see the comments about exposing the // GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE conditional define. namespace gte { template <typename UInteger> class BSRational { public: // Construction. The default constructor generates the zero // BSRational. The constructors that take only numerators set the // denominators to one. BSRational() : mNumerator(0), mDenominator(1) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(BSRational const& r) { *this = r; } BSRational(float numerator) : mNumerator(numerator), mDenominator(1.0f) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(double numerator) : mNumerator(numerator), mDenominator(1.0) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(int32_t numerator) : mNumerator(numerator), mDenominator(1) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(uint32_t numerator) : mNumerator(numerator), mDenominator(1) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(int64_t numerator) : mNumerator(numerator), mDenominator(1) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(uint64_t numerator) : mNumerator(numerator), mDenominator(1) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(BSNumber<UInteger> const& numerator) : mNumerator(numerator), mDenominator(1) { #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(float numerator, float denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(double numerator, double denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(int32_t numerator, int32_t denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(uint32_t numerator, uint32_t denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(int64_t numerator, int64_t denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(uint64_t numerator, uint64_t denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(BSNumber<UInteger> const& numerator, BSNumber<UInteger> const& denominator) : mNumerator(numerator), mDenominator(denominator) { LogAssert(mDenominator.mSign != 0, "Division by zero."); if (mDenominator.mSign < 0) { mNumerator.mSign = -mNumerator.mSign; mDenominator.mSign = 1; } // Set the exponent of the denominator to zero, but you can do so // only by modifying the biased exponent. Adjust the numerator // accordingly. This prevents large growth of the exponents in // both numerator and denominator simultaneously. mNumerator.mBiasedExponent -= mDenominator.GetExponent(); mDenominator.mBiasedExponent = -(mDenominator.GetUInteger().GetNumBits() - 1); #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(std::string const& number) { LogAssert(number.size() > 0, "A number must be specified."); // Get the leading '+' or '-' if it exists. std::string fpNumber; int32_t sign; if (number[0] == '+') { fpNumber = number.substr(1); sign = +1; LogAssert(fpNumber.size() > 1, "Invalid number format."); } else if (number[0] == '-') { fpNumber = number.substr(1); sign = -1; LogAssert(fpNumber.size() > 1, "Invalid number format."); } else { fpNumber = number; sign = +1; } size_t decimal = fpNumber.find('.'); if (decimal != std::string::npos) { if (decimal > 0) { if (decimal < fpNumber.size()) { // The number is "x.y". BSNumber<UInteger> intPart = BSNumber<UInteger>::ConvertToInteger(fpNumber.substr(0, decimal)); BSRational frcPart = ConvertToFraction(fpNumber.substr(decimal + 1)); mNumerator = intPart * frcPart.mDenominator + frcPart.mNumerator; mDenominator = frcPart.mDenominator; } else { // The number is "x.". mNumerator = BSNumber<UInteger>::ConvertToInteger(fpNumber.substr(0,fpNumber.size()-1)); mDenominator = 1; } } else { // The number is ".y". BSRational frcPart = ConvertToFraction(fpNumber.substr(1)); mNumerator = frcPart.mNumerator; mDenominator = frcPart.mDenominator; } } else { // The number is "x". mNumerator = BSNumber<UInteger>::ConvertToInteger(fpNumber); mDenominator = 1; } mNumerator.SetSign(sign); #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif } BSRational(const char* number) : BSRational(std::string(number)) { } // Implicit conversions. These always use the default rounding mode, // round-to-nearest-ties-to-even. operator float() const { float output; Convert(*this, FE_TONEAREST, output); return output; } operator double() const { double output; Convert(*this, FE_TONEAREST, output); return output; } // Assignment. BSRational& operator=(BSRational const& r) { mNumerator = r.mNumerator; mDenominator = r.mDenominator; #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif return *this; } // Support for move semantics. BSRational(BSRational&& r) noexcept { *this = std::move(r); } BSRational& operator=(BSRational&& r) noexcept { mNumerator = std::move(r.mNumerator); mDenominator = std::move(r.mDenominator); #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = (double)*this; #endif return *this; } // Member access. inline void SetSign(int32_t sign) { mNumerator.SetSign(sign); mDenominator.SetSign(1); #if defined(GTL_BINARY_SCIENTIFIC_SHOW_DOUBLE) mValue = sign * std::fabs(mValue); #endif } inline int32_t GetSign() const { return mNumerator.GetSign() * mDenominator.GetSign(); } inline BSNumber<UInteger> const& GetNumerator() const { return mNumerator; } inline BSNumber<UInteger>& GetNumerator() { return mNumerator; } inline BSNumber<UInteger> const& GetDenominator() const { return mDenominator; } inline BSNumber<UInteger>& GetDenominator() { return mDenominator; } // Comparisons. bool operator==(BSRational const& r) const { // Do inexpensive sign tests first for optimum performance. if (mNumerator.mSign != r.mNumerator.mSign) { return false; } if (mNumerator.mSign == 0) { // The numbers are both zero. return true; } return mNumerator * r.mDenominator == mDenominator * r.mNumerator; } bool operator!=(BSRational const& r) const { return !operator==(r); } bool operator< (BSRational const& r) const { // Do inexpensive sign tests first for optimum performance. if (mNumerator.mSign > 0) { if (r.mNumerator.mSign <= 0) { return false; } } else if (mNumerator.mSign == 0) { return r.mNumerator.mSign > 0; } else if (mNumerator.mSign < 0) { if (r.mNumerator.mSign >= 0) { return true; } } return mNumerator * r.mDenominator < mDenominator * r.mNumerator; } bool operator<=(BSRational const& r) const { return !r.operator<(*this); } bool operator> (BSRational const& r) const { return r.operator<(*this); } bool operator>=(BSRational const& r) const { return !operator<(r); } // Unary operations. BSRational operator+() const { return *this; } BSRational operator-() const { return BSRational(-mNumerator, mDenominator); } // Arithmetic. BSRational operator+(BSRational const& r) const { BSNumber<UInteger> product0 = mNumerator * r.mDenominator; BSNumber<UInteger> product1 = mDenominator * r.mNumerator; BSNumber<UInteger> numerator = product0 + product1; // Complex expressions can lead to 0/denom, where denom is not 1. if (numerator.mSign != 0) { BSNumber<UInteger> denominator = mDenominator * r.mDenominator; return BSRational(numerator, denominator); } else { return BSRational(0); } } BSRational operator-(BSRational const& r) const { BSNumber<UInteger> product0 = mNumerator * r.mDenominator; BSNumber<UInteger> product1 = mDenominator * r.mNumerator; BSNumber<UInteger> numerator = product0 - product1; // Complex expressions can lead to 0/denom, where denom is not 1. if (numerator.mSign != 0) { BSNumber<UInteger> denominator = mDenominator * r.mDenominator; return BSRational(numerator, denominator); } else { return BSRational(0); } } BSRational operator*(BSRational const& r) const { BSNumber<UInteger> numerator = mNumerator * r.mNumerator; // Complex expressions can lead to 0/denom, where denom is not 1. if (numerator.mSign != 0) { BSNumber<UInteger> denominator = mDenominator * r.mDenominator; return BSRational(numerator, denominator); } else { return BSRational(0); } } BSRational operator/(BSRational const& r) const { LogAssert(r.mNumerator.mSign != 0, "Division by zero in BSRational::operator/."); BSNumber<UInteger> numerator = mNumerator * r.mDenominator; // Complex expressions can lead to 0/denom, where denom is not 1. if (numerator.mSign != 0) { BSNumber<UInteger> denominator = mDenominator * r.mNumerator; if (denominator.mSign < 0) { numerator.mSign = -numerator.mSign; denominator.mSign = 1; } return BSRational(numerator, denominator); } else { return BSRational(0); } } BSRational& operator+=(BSRational const& r) { *this = operator+(r); return *this; } BSRational& operator-=(BSRational const& r) { *this = operator-(r); return *this; } BSRational& operator*=(BSRational const& r) { *this = operator*(r); return *this; } BSRational& operator/=(BSRational const& r) { *this = operator/(r); return *this; } // Disk input/output. The fstream objects should be created using // std::ios::binary. The return value is 'true' iff the operation // was successful. bool Write(std::ostream& output) const { return mNumerator.Write(output) && mDenominator.Write(output); } bool Read(std::istream& input) { return mNumerator.Read(input) && mDenominator.Read(input); } private: // Helper for converting a string to a BSRational, where the string // is the fractional part "y" of the string "x.y". static BSRational ConvertToFraction(std::string const& number) { LogAssert(number.find_first_not_of("0123456789") == std::string::npos, "Invalid number format."); BSRational y(0), ten(10), pow10(10); for (size_t i = 0; i < number.size(); ++i) { int32_t digit = static_cast<int32_t>(number[i]) - static_cast<int32_t>('0'); if (digit > 0) { y += BSRational(digit) / pow10; } pow10 *= ten; } return y; } #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) public: // List this first so that it shows up first in the debugger watch // window. double mValue; private: #endif BSNumber<UInteger> mNumerator, mDenominator; }; // Explicit conversion to a user-specified precision. The rounding // mode is one of the flags provided in <cfenv>. The modes are // FE_TONEAREST: round to nearest ties to even // FE_DOWNWARD: round towards negative infinity // FE_TOWARDZERO: round towards zero // FE_UPWARD: round towards positive infinity template <typename UInteger> void Convert(BSRational<UInteger> const& input, int32_t precision, int32_t roundingMode, BSNumber<UInteger>& output) { if (precision <= 0) { LogError("Precision must be positive."); } size_t const maxNumBlocks = UInteger::GetMaxSize(); size_t const numPrecBlocks = static_cast<size_t>((precision + 31) / 32); if (numPrecBlocks >= maxNumBlocks) { LogError("The maximum precision has been exceeded."); } if (input.GetSign() == 0) { output = BSNumber<UInteger>(0); return; } BSNumber<UInteger> n = input.GetNumerator(); BSNumber<UInteger> d = input.GetDenominator(); // The ratio is abstractly of the form n/d = (1.u*2^p)/(1.v*2^q). // Convert to the form // (1.u/1.v)*2^{p-q}, if 1.u >= 1.v // 2*(1.u/1.v)*2^{p-q-1} if 1.u < 1.v // which are in the interval [1,2). int32_t sign = n.GetSign() * d.GetSign(); n.SetSign(1); d.SetSign(1); int32_t pmq = n.GetExponent() - d.GetExponent(); n.SetExponent(0); d.SetExponent(0); if (n < d) { n.SetExponent(n.GetExponent() + 1); --pmq; } // Let p = precision. At this time, n/d = 1.c in [1,2). Define the // sequence of bits w = 1c = w_{p-1} w_{p-2} ... w_0 r, where // w_{p-1} = 1. The bits r after w_0 are used for rounding based on // the user-specified rounding mode. // Compute p bits for w, the leading bit guaranteed to be 1 and // occurring at index (1 << (precision-1)). BSNumber<UInteger> one(1), two(2); UInteger& w = output.GetUInteger(); w.SetNumBits(precision); w.SetAllBitsToZero(); int32_t const size = w.GetSize(); int32_t const precisionM1 = precision - 1; int32_t const leading = precisionM1 % 32; uint32_t mask = (1 << leading); auto& bits = w.GetBits(); int32_t current = size - 1; int32_t lastBit = -1; for (int32_t i = precisionM1; i >= 0; --i) { if (n < d) { n = two * n; lastBit = 0; } else { n = two * (n - d); bits[current] |= mask; lastBit = 1; if (n.GetSign() == 0) { // The input rational has a finite number of bits in its // representation, so it is exactly a BSNumber. if (i > 0) { // The number n is zero for the remainder of the loop, // so the last bit of the p-bit precision pattern is // a zero. There is no need to continue looping. lastBit = 0; } break; } } if (mask == 0x00000001u) { --current; mask = 0x80000000u; } else { mask >>= 1; } } // At this point as a sequence of bits, r = n/d = r0 r1 ... if (roundingMode == FE_TONEAREST) { n = n - d; if (n.GetSign() > 0 || (n.GetSign() == 0 && lastBit == 1)) { // round up pmq += w.RoundUp(); } // else round down, equivalent to truncating the r bits } else if (roundingMode == FE_UPWARD) { if (n.GetSign() > 0 && sign > 0) { // round up pmq += w.RoundUp(); } // else round down, equivalent to truncating the r bits } else if (roundingMode == FE_DOWNWARD) { if (n.GetSign() > 0 && sign < 0) { // Round down. This is the round-up operation applied to // w, but the final sign is negative which amounts to // rounding down. pmq += w.RoundUp(); } // else round down, equivalent to truncating the r bits } else if (roundingMode != FE_TOWARDZERO) { // Currently, no additional implementation-dependent modes // are supported for rounding. LogError("Implementation-dependent rounding mode not supported."); } // else roundingMode == FE_TOWARDZERO. Truncate the r bits, which // requires no additional work. // Shift the bits if necessary to obtain the invariant that BSNumber // objects have bit patterns that are odd integers. if ((w.GetBits()[0] & 1) == 0) { UInteger temp = w; auto shift = w.ShiftRightToOdd(temp); pmq += shift; } // Do not use SetExponent(pmq) at this step. The number of // requested bits is 'precision' but w.GetNumBits() will be // different when round-up occurs, and SetExponent accesses // w.GetNumBits(). output.SetSign(sign); output.SetBiasedExponent(pmq - precisionM1); #if defined(GTE_BINARY_SCIENTIFIC_SHOW_DOUBLE) output.mValue = (double)output; #endif } // This conversion is used to avoid having to expose BSNumber in the // APConversion class as well as other places where BSRational<UInteger> // is passed via a template parameter named Rational. template <typename UInteger> void Convert(BSRational<UInteger> const& input, int32_t precision, int32_t roundingMode, BSRational<UInteger>& output) { BSNumber<UInteger> numerator; Convert(input, precision, roundingMode, numerator); output = BSRational<UInteger>(numerator); } // Convert to 'float' or 'double' using the specified rounding mode. template <typename UInteger, typename FPType> void Convert(BSRational<UInteger> const& input, int32_t roundingMode, FPType& output) { static_assert(std::is_floating_point<FPType>::value, "Invalid floating-point type."); BSNumber<UInteger> number; Convert(input, std::numeric_limits<FPType>::digits, roundingMode, number); output = static_cast<FPType>(number); } } namespace std { // TODO: Allow for implementations of the math functions in which a // specified precision is used when computing the result. template <typename UInteger> inline gte::BSRational<UInteger> acos(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::acos((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> acosh(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::acosh((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> asin(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::asin((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> asinh(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::asinh((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> atan(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::atan((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> atanh(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::atanh((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> atan2(gte::BSRational<UInteger> const& y, gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::atan2((double)y, (double)x); } template <typename UInteger> inline gte::BSRational<UInteger> ceil(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::ceil((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> cos(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::cos((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> cosh(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::cosh((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> exp(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::exp((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> exp2(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::exp2((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> fabs(gte::BSRational<UInteger> const& x) { return (x.GetSign() >= 0 ? x : -x); } template <typename UInteger> inline gte::BSRational<UInteger> floor(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::floor((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> fmod(gte::BSRational<UInteger> const& x, gte::BSRational<UInteger> const& y) { return (gte::BSRational<UInteger>)std::fmod((double)x, (double)y); } template <typename UInteger> inline gte::BSRational<UInteger> frexp(gte::BSRational<UInteger> const& x, int32_t* exponent) { gte::BSRational<UInteger> result = x; auto& numer = result.GetNumerator(); auto& denom = result.GetDenominator(); int32_t e = numer.GetExponent() - denom.GetExponent(); numer.SetExponent(0); denom.SetExponent(0); int32_t saveSign = numer.GetSign(); numer.SetSign(1); if (numer >= denom) { ++e; numer.SetExponent(-1); } numer.SetSign(saveSign); *exponent = e; return result; } template <typename UInteger> inline gte::BSRational<UInteger> ldexp(gte::BSRational<UInteger> const& x, int32_t exponent) { gte::BSRational<UInteger> result = x; int32_t biasedExponent = result.GetNumerator().GetBiasedExponent(); biasedExponent += exponent; result.GetNumerator().SetBiasedExponent(biasedExponent); return result; } template <typename UInteger> inline gte::BSRational<UInteger> log(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::log((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> log2(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::log2((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> log10(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::log10((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> pow(gte::BSRational<UInteger> const& x, gte::BSRational<UInteger> const& y) { return (gte::BSRational<UInteger>)std::pow((double)x, (double)y); } template <typename UInteger> inline gte::BSRational<UInteger> sin(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::sin((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> sinh(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::sinh((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> sqrt(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::sqrt((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> tan(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::tan((double)x); } template <typename UInteger> inline gte::BSRational<UInteger> tanh(gte::BSRational<UInteger> const& x) { return (gte::BSRational<UInteger>)std::tanh((double)x); } // Type trait that says BSRational is a signed type. template <typename UInteger> struct is_signed<gte::BSRational<UInteger>> : true_type {}; } namespace gte { template <typename UInteger> inline BSRational<UInteger> atandivpi(BSRational<UInteger> const& x) { return (BSRational<UInteger>)atandivpi((double)x); } template <typename UInteger> inline BSRational<UInteger> atan2divpi(BSRational<UInteger> const& y, BSRational<UInteger> const& x) { return (BSRational<UInteger>)atan2divpi((double)y, (double)x); } template <typename UInteger> inline BSRational<UInteger> clamp(BSRational<UInteger> const& x, BSRational<UInteger> const& xmin, BSRational<UInteger> const& xmax) { return (BSRational<UInteger>)clamp((double)x, (double)xmin, (double)xmax); } template <typename UInteger> inline BSRational<UInteger> cospi(BSRational<UInteger> const& x) { return (BSRational<UInteger>)cospi((double)x); } template <typename UInteger> inline BSRational<UInteger> exp10(BSRational<UInteger> const& x) { return (BSRational<UInteger>)exp10((double)x); } template <typename UInteger> inline BSRational<UInteger> invsqrt(BSRational<UInteger> const& x) { return (BSRational<UInteger>)invsqrt((double)x); } template <typename UInteger> inline int32_t isign(BSRational<UInteger> const& x) { return isign((double)x); } template <typename UInteger> inline BSRational<UInteger> saturate(BSRational<UInteger> const& x) { return (BSRational<UInteger>)saturate((double)x); } template <typename UInteger> inline BSRational<UInteger> sign(BSRational<UInteger> const& x) { return (BSRational<UInteger>)sign((double)x); } template <typename UInteger> inline BSRational<UInteger> sinpi(BSRational<UInteger> const& x) { return (BSRational<UInteger>)sinpi((double)x); } template <typename UInteger> inline BSRational<UInteger> sqr(BSRational<UInteger> const& x) { return (BSRational<UInteger>)sqr((double)x); } // See the comments in Math.h about traits is_arbitrary_precision // and has_division_operator. template <typename UInteger> struct is_arbitrary_precision_internal<BSRational<UInteger>> : std::true_type {}; template <typename UInteger> struct has_division_operator_internal<BSRational<UInteger>> : std::true_type {}; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CurveExtractor.h
.h
10,064
284
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <array> #include <cstdint> #include <map> #include <type_traits> #include <vector> namespace gte { // The image type T must be one of the integer types: int8_t, int16_t, // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations // are performed using int64_t. The type Real is for extraction to // floating-point vertices. template <typename T, typename Real> class CurveExtractor { public: // Abstract base class. virtual ~CurveExtractor() = default; // The level curves form a graph of vertices and edges. The vertices // are computed as pairs of nonnegative rational numbers. Vertex // represents the rational pair (xNumer/xDenom, yNumer/yDenom) as // (xNumer, xDenom, yNumer, yDenom), where all components are // nonnegative. The edges connect pairs of vertices, forming a graph // that represents the level set. struct Vertex { Vertex() = default; Vertex(int64_t inXNumer, int64_t inXDenom, int64_t inYNumer, int64_t inYDenom) { // The vertex generation leads to the numerator and // denominator having the same sign. This constructor changes // sign to ensure the numerator and denominator are both // positive. if (inXDenom > 0) { xNumer = inXNumer; xDenom = inXDenom; } else { xNumer = -inXNumer; xDenom = -inXDenom; } if (inYDenom > 0) { yNumer = inYNumer; yDenom = inYDenom; } else { yNumer = -inYNumer; yDenom = -inYDenom; } } // The non-default constructor guarantees that xDenom > 0 and // yDenom > 0. The following comparison operators assume that // the denominators are positive. bool operator==(Vertex const& other) const { return // xn0 / xd0 == xn1 / xd1 xNumer * other.xDenom == other.xNumer * xDenom && // yn0/yd0 == yn1/yd1 yNumer * other.yDenom == other.yNumer * yDenom; } bool operator<(Vertex const& other) const { int64_t xn0txd1 = xNumer * other.xDenom; int64_t xn1txd0 = other.xNumer * xDenom; if (xn0txd1 < xn1txd0) { // xn0/xd0 < xn1/xd1 return true; } if (xn0txd1 > xn1txd0) { // xn0/xd0 > xn1/xd1 return false; } int64_t yn0tyd1 = yNumer * other.yDenom; int64_t yn1tyd0 = other.yNumer * yDenom; // yn0/yd0 < yn1/yd1 return yn0tyd1 < yn1tyd0; } int64_t xNumer, xDenom, yNumer, yDenom; }; struct Edge { Edge() = default; Edge(int32_t v0, int32_t v1) { if (v0 < v1) { v[0] = v0; v[1] = v1; } else { v[0] = v1; v[1] = v0; } } bool operator==(Edge const& other) const { return v[0] == other.v[0] && v[1] == other.v[1]; } bool operator<(Edge const& other) const { for (int32_t i = 0; i < 2; ++i) { if (v[i] < other.v[i]) { return true; } if (v[i] > other.v[i]) { return false; } } return false; } std::array<int32_t, 2> v; }; // Extract level curves and return rational vertices. virtual void Extract(T level, std::vector<Vertex>& vertices, std::vector<Edge>& edges) = 0; void Extract(T level, bool removeDuplicateVertices, std::vector<std::array<Real, 2>>& vertices, std::vector<Edge>& edges) { std::vector<Vertex> rationalVertices; Extract(level, rationalVertices, edges); if (removeDuplicateVertices) { MakeUnique(rationalVertices, edges); } Convert(rationalVertices, vertices); } // The extraction has duplicate vertices on edges shared by pixels. // This function will eliminate the duplicates. void MakeUnique(std::vector<Vertex>& vertices, std::vector<Edge>& edges) { size_t numVertices = vertices.size(); size_t numEdges = edges.size(); if (numVertices == 0 || numEdges == 0) { return; } // Compute the map of unique vertices and assign to them new and // unique indices. std::map<Vertex, int32_t> vmap; int32_t nextVertex = 0; for (size_t v = 0; v < numVertices; ++v) { // Keep only unique vertices. auto result = vmap.insert(std::make_pair(vertices[v], nextVertex)); if (result.second) { ++nextVertex; } } // Compute the map of unique edges and assign to them new and // unique indices. std::map<Edge, int32_t> emap; int32_t nextEdge = 0; for (size_t e = 0; e < numEdges; ++e) { // Replace old vertex indices by new vertex indices. Edge& edge = edges[e]; for (int32_t i = 0; i < 2; ++i) { auto iter = vmap.find(vertices[edge.v[i]]); LogAssert(iter != vmap.end(), "Expecting the vertex to be in the vmap."); edge.v[i] = iter->second; } // Keep only unique edges. auto result = emap.insert(std::make_pair(edge, nextEdge)); if (result.second) { ++nextEdge; } } // Pack the vertices into an array. vertices.resize(vmap.size()); for (auto const& element : vmap) { vertices[element.second] = element.first; } // Pack the edges into an array. edges.resize(emap.size()); for (auto const& element : emap) { edges[element.second] = element.first; } } // Convert from Vertex to std::array<Real, 2> rationals. void Convert(std::vector<Vertex> const& input, std::vector<std::array<Real, 2>>& output) { output.resize(input.size()); for (size_t i = 0; i < input.size(); ++i) { Real rxNumer = static_cast<Real>(input[i].xNumer); Real rxDenom = static_cast<Real>(input[i].xDenom); Real ryNumer = static_cast<Real>(input[i].yNumer); Real ryDenom = static_cast<Real>(input[i].yDenom); output[i][0] = rxNumer / rxDenom; output[i][1] = ryNumer / ryDenom; } } protected: // The input is a 2D image with lexicographically ordered pixels (x,y) // stored in a linear array. Pixel (x,y) is stored in the array at // location index = x + xBound * y. The inputs xBound and yBound must // each be 2 or larger so that there is at least one image square to // process. The inputPixels must be nonnull and point to contiguous // storage that contains at least xBound * yBound elements. CurveExtractor(int32_t xBound, int32_t yBound, T const* inputPixels) : mXBound(xBound), mYBound(yBound), mInputPixels(inputPixels), mPixels{} { static_assert(std::is_integral<T>::value && sizeof(T) <= 4, "Type T must be int32_t{8,16,32}_t or uint{8,16,32}_t."); LogAssert(mXBound > 1 && mYBound > 1 && mInputPixels != nullptr, "Invalid input."); mPixels.resize(static_cast<size_t>(static_cast<size_t>(mXBound) * static_cast<size_t>(mYBound))); } void AddVertex(std::vector<Vertex>& vertices, int64_t xNumer, int64_t xDenom, int64_t yNumer, int64_t yDenom) { vertices.push_back(Vertex(xNumer, xDenom, yNumer, yDenom)); } void AddEdge(std::vector<Vertex>& vertices, std::vector<Edge>& edges, int64_t xNumer0, int64_t xDenom0, int64_t yNumer0, int64_t yDenom0, int64_t xNumer1, int64_t xDenom1, int64_t yNumer1, int64_t yDenom1) { int32_t v0 = static_cast<int32_t>(vertices.size()); int32_t v1 = v0 + 1; edges.push_back(Edge(v0, v1)); vertices.push_back(Vertex(xNumer0, xDenom0, yNumer0, yDenom0)); vertices.push_back(Vertex(xNumer1, xDenom1, yNumer1, yDenom1)); } int32_t mXBound, mYBound; T const* mInputPixels; std::vector<int64_t> mPixels; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DisjointIntervals.h
.h
12,744
404
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstddef> #include <cstdint> #include <vector> namespace gte { // Compute Boolean operations of disjoint sets of half-open intervals of // the form [xmin,xmax) with xmin < xmax. template <typename Scalar> class DisjointIntervals { public: // Construction and destruction. The non-default constructor requires // that xmin < xmax. DisjointIntervals() { } DisjointIntervals(Scalar const& xmin, Scalar const& xmax) { if (xmin < xmax) { mEndpoints = { xmin, xmax }; mEndpoints[0] = xmin; mEndpoints[1] = xmax; } } ~DisjointIntervals() { } // Copy operations. DisjointIntervals(DisjointIntervals const& other) : mEndpoints(other.mEndpoints) { } DisjointIntervals& operator=(DisjointIntervals const& other) { mEndpoints = other.mEndpoints; return *this; } // Move operations. DisjointIntervals(DisjointIntervals&& other) noexcept : mEndpoints(std::move(other.mEndpoints)) { } DisjointIntervals& operator=(DisjointIntervals&& other) noexcept { mEndpoints = std::move(other.mEndpoints); return *this; } // The number of intervals in the set. inline int32_t GetNumIntervals() const { return static_cast<int32_t>(mEndpoints.size() / 2); } // The i-th interval is [xmin,xmax). The values xmin and xmax are // valid only when 0 <= i < GetNumIntervals(). bool GetInterval(int32_t i, Scalar& xmin, Scalar& xmax) const { int32_t index = 2 * i; if (0 <= index && index < static_cast<int32_t>(mEndpoints.size())) { xmin = mEndpoints[index]; xmax = mEndpoints[++index]; return true; } xmin = (Scalar)0; xmax = (Scalar)0; return false; } // Make this set empty. inline void Clear() { mEndpoints.clear(); } // Insert [xmin,xmax) into the set. This is a Boolean 'union' // operation. The operation is successful only when xmin < xmax. bool Insert(Scalar const& xmin, Scalar const& xmax) { if (xmin < xmax) { DisjointIntervals input(xmin, xmax); DisjointIntervals output = *this | input; mEndpoints = std::move(output.mEndpoints); return true; } return false; } // Remove [xmin,xmax) from the set. This is a Boolean 'difference' // operation. The operation is successful only when xmin < xmax. bool Remove(Scalar const& xmin, Scalar const& xmax) { if (xmin < xmax) { DisjointIntervals input(xmin, xmax); DisjointIntervals output = std::move(*this - input); mEndpoints = std::move(output.mEndpoints); return true; } return false; } // Get the union of the interval sets, input0 union input1. friend DisjointIntervals operator|(DisjointIntervals const& input0, DisjointIntervals const& input1) { DisjointIntervals output; size_t const numEndpoints0 = input0.mEndpoints.size(); size_t const numEndpoints1 = input1.mEndpoints.size(); size_t i0 = 0, i1 = 0; int32_t parity0 = 0, parity1 = 0; while (i0 < numEndpoints0 && i1 < numEndpoints1) { Scalar const& value0 = input0.mEndpoints[i0]; Scalar const& value1 = input1.mEndpoints[i1]; if (value0 < value1) { if (parity0 == 0) { parity0 = 1; if (parity1 == 0) { output.mEndpoints.push_back(value0); } } else { if (parity1 == 0) { output.mEndpoints.push_back(value0); } parity0 = 0; } ++i0; } else if (value1 < value0) { if (parity1 == 0) { parity1 = 1; if (parity0 == 0) { output.mEndpoints.push_back(value1); } } else { if (parity0 == 0) { output.mEndpoints.push_back(value1); } parity1 = 0; } ++i1; } else // value0 == value1 { if (parity0 == parity1) { output.mEndpoints.push_back(value0); } parity0 ^= 1; parity1 ^= 1; ++i0; ++i1; } } while (i0 < numEndpoints0) { output.mEndpoints.push_back(input0.mEndpoints[i0]); ++i0; } while (i1 < numEndpoints1) { output.mEndpoints.push_back(input1.mEndpoints[i1]); ++i1; } return output; } // Get the intersection of the interval sets, input0 intersect is1. friend DisjointIntervals operator&(DisjointIntervals const& input0, DisjointIntervals const& input1) { DisjointIntervals output; size_t const numEndpoints0 = input0.mEndpoints.size(); size_t const numEndpoints1 = input1.mEndpoints.size(); size_t i0 = 0, i1 = 0; int32_t parity0 = 0, parity1 = 0; while (i0 < numEndpoints0 && i1 < numEndpoints1) { Scalar const& value0 = input0.mEndpoints[i0]; Scalar const& value1 = input1.mEndpoints[i1]; if (value0 < value1) { if (parity0 == 0) { parity0 = 1; if (parity1 == 1) { output.mEndpoints.push_back(value0); } } else { if (parity1 == 1) { output.mEndpoints.push_back(value0); } parity0 = 0; } ++i0; } else if (value1 < value0) { if (parity1 == 0) { parity1 = 1; if (parity0 == 1) { output.mEndpoints.push_back(value1); } } else { if (parity0 == 1) { output.mEndpoints.push_back(value1); } parity1 = 0; } ++i1; } else // value0 == value1 { if (parity0 == parity1) { output.mEndpoints.push_back(value0); } parity0 ^= 1; parity1 ^= 1; ++i0; ++i1; } } return output; } // Get the differences of the interval sets, input0 minus input1. friend DisjointIntervals operator-(DisjointIntervals const& input0, DisjointIntervals const& input1) { DisjointIntervals output; size_t const numEndpoints0 = input0.mEndpoints.size(); size_t const numEndpoints1 = input1.mEndpoints.size(); size_t i0 = 0, i1 = 0; int32_t parity0 = 0, parity1 = 1; while (i0 < numEndpoints0 && i1 < numEndpoints1) { Scalar const& value0 = input0.mEndpoints[i0]; Scalar const& value1 = input1.mEndpoints[i1]; if (value0 < value1) { if (parity0 == 0) { parity0 = 1; if (parity1 == 1) { output.mEndpoints.push_back(value0); } } else { if (parity1 == 1) { output.mEndpoints.push_back(value0); } parity0 = 0; } ++i0; } else if (value1 < value0) { if (parity1 == 0) { parity1 = 1; if (parity0 == 1) { output.mEndpoints.push_back(value1); } } else { if (parity0 == 1) { output.mEndpoints.push_back(value1); } parity1 = 0; } ++i1; } else // value0 == value1 { if (parity0 == parity1) { output.mEndpoints.push_back(value0); } parity0 ^= 1; parity1 ^= 1; ++i0; ++i1; } } while (i0 < numEndpoints0) { output.mEndpoints.push_back(input0.mEndpoints[i0]); ++i0; } return output; } // Get the exclusive or of the interval sets, input0 xor input1 = // (input0 minus input1) or (input1 minus input0). friend DisjointIntervals operator^(DisjointIntervals const& input0, DisjointIntervals const& input1) { DisjointIntervals output; size_t const numEndpoints0 = input0.mEndpoints.size(); size_t const numEndpoints1 = input1.mEndpoints.size(); size_t i0 = 0, i1 = 0; while (i0 < numEndpoints0 && i1 < numEndpoints1) { Scalar const& value0 = input0.mEndpoints[i0]; Scalar const& value1 = input1.mEndpoints[i1]; if (value0 < value1) { output.mEndpoints.push_back(value0); ++i0; } else if (value1 < value0) { output.mEndpoints.push_back(value1); ++i1; } else // value0 == value1 { ++i0; ++i1; } } while (i0 < numEndpoints0) { output.mEndpoints.push_back(input0.mEndpoints[i0]); ++i0; } while (i1 < numEndpoints1) { output.mEndpoints.push_back(input1.mEndpoints[i1]); ++i1; } return output; } private: // The array of endpoints has an even number of elements. The i-th // interval is [mEndPoints[2*i],mEndPoints[2*i+1]). std::vector<Scalar> mEndpoints; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/LDLTDecomposition.h
.h
28,270
817
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/GMatrix.h> // Factor a positive symmetric matrix A = L * D * L^T, where L is a lower // triangular matrix with diagonal entries all 1 (L is lower unit triangular) // and where D is a diagonal matrix with diagonal entries all positive. namespace gte { template <typename T, int32_t...> class LDLTDecomposition; template <typename T, int32_t...> class BlockLDLTDecomposition; // Implementation for sizes known at compile time. template <typename T, int32_t N> class LDLTDecomposition<T, N> { public: LDLTDecomposition() { static_assert( N > 0, "Invalid size."); } // The matrix A must be positive definite. The implementation uses // only the lower-triangular portion of A. On output, L is lower // unit triangular and D is diagonal. bool Factor(Matrix<N, N, T> const& A, Matrix<N, N, T>& L, Matrix<N, N, T>& D) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); L.MakeZero(); D.MakeZero(); for (int32_t j = 0; j < N; ++j) { T Djj = A(j, j); for (int32_t k = 0; k < j; ++k) { T Ljk = L(j, k); T Dkk = D(k, k); Djj -= Ljk * Ljk * Dkk; } D(j, j) = Djj; if (Djj == zero) { return false; } L(j, j) = one; for (int32_t i = j + 1; i < N; ++i) { T Lij = A(i, j); for (int32_t k = 0; k < j; ++k) { T Lik = L(i, k); T Ljk = L(j, k); T Dkk = D(k, k); Lij -= Lik * Ljk * Dkk; } Lij /= Djj; L(i, j) = Lij; } } return true; } // Solve A*X = B for positive definite A = L * D * L^T with // factoring before the call. void Solve(Matrix<N, N, T> const& L, Matrix<N, N, T> const& D, Vector<N, T> const& B, Vector<N, T>& X) { // Solve L * Z = L * (D * L^T * X) = B for Z. for (int32_t r = 0; r < N; ++r) { X[r] = B[r]; for (int32_t c = 0; c < r; ++c) { X[r] -= L(r, c) * X[c]; } } // Solve D * Y = D * (L^T * X) = Z for Y. for (int32_t r = 0; r < N; ++r) { X[r] /= D(r, r); } // Solve L^T * Y = Z for X. for (int32_t r = N - 1; r >= 0; --r) { for (int32_t c = r + 1; c < N; ++c) { X[r] -= L(c, r) * X[c]; } } } // Solve A*X = B for positive definite A = L * D * L^T with // factoring during the call. void Solve(Matrix<N, N, T> const& A, Vector<N, T> const& B, Vector<N, T>& X) { Matrix<N, N, T> L, D; Factor(A, L, D); Solve(L, D, B, X); } }; // Implementation for sizes known only at run time. template <typename T> class LDLTDecomposition<T> { public: int32_t const N; LDLTDecomposition(int32_t inN) : N(inN) { LogAssert( N > 0, "Invalid size."); } // The matrix A must be positive definite. The implementation uses // only the lower-triangular portion of A. On output, L is lower // unit triangular and D is diagonal. bool Factor(GMatrix<T> const& A, GMatrix<T>& L, GMatrix<T>& D) { LogAssert( A.GetNumRows() == N && A.GetNumCols() == N, "Invalid size."); T const zero = static_cast<T>(0); T const one = static_cast<T>(1); L.SetSize(N, N); L.MakeZero(); D.SetSize(N, N); D.MakeZero(); for (int32_t j = 0; j < N; ++j) { T Djj = A(j, j); for (int32_t k = 0; k < j; ++k) { T Ljk = L(j, k); T Dkk = D(k, k); Djj -= Ljk * Ljk * Dkk; } D(j, j) = Djj; if (Djj == zero) { return false; } L(j, j) = one; for (int32_t i = j + 1; i < N; ++i) { T Lij = A(i, j); for (int32_t k = 0; k < j; ++k) { T Lik = L(i, k); T Ljk = L(j, k); T Dkk = D(k, k); Lij -= Lik * Ljk * Dkk; } Lij /= Djj; L(i, j) = Lij; } } return true; } // Solve A*X = B for positive definite A = L * D * L^T with // factoring before the call. void Solve(GMatrix<T> const& L, GMatrix<T> const& D, GVector<T> const& B, GVector<T>& X) { LogAssert( L.GetNumRows() == N && L.GetNumCols() == N && D.GetNumRows() == N && D.GetNumCols() && B.GetSize() == N, "Invalid size."); X.SetSize(N); // Solve L * Z = L * (D * L^T * X) = B for Z. for (int32_t r = 0; r < N; ++r) { X[r] = B[r]; for (int32_t c = 0; c < r; ++c) { X[r] -= L(r, c) * X[c]; } } // Solve D * Y = D * (L^T * X) = Z for Y. for (int32_t r = 0; r < N; ++r) { X[r] /= D(r, r); } // Solve L^T * Y = Z for X. for (int32_t r = N - 1; r >= 0; --r) { for (int32_t c = r + 1; c < N; ++c) { X[r] -= L(c, r) * X[c]; } } } // Solve A*X = B for positive definite A = L * D * L^T. void Solve(GMatrix<T> const& A, GVector<T> const& B, GVector<T>& X) { LogAssert( A.GetNumRows() == N && A.GetNumCols() == N && B.GetSize() == N, "Invalid size."); GMatrix<T> L, D; Factor(A, L, D); Solve(L, D, B, X); } }; // Implementation for sizes known at compile time. template <typename T, int32_t BlockSize, int32_t NumBlocks> class BlockLDLTDecomposition<T, BlockSize, NumBlocks> { public: // Let B represent the block size and N represent the number of // blocks. The matrix A is (N*B)-by-(N*B) but partitioned into an // N-by-N matrix of blocks, each block of size B-by-B. The value // N*B is NumDimensions. enum { NumDimensions = NumBlocks * BlockSize }; using BlockVector = std::array<Vector<BlockSize, T>, NumBlocks>; using BlockMatrix = std::array<std::array<Matrix<BlockSize, BlockSize, T>, NumBlocks>, NumBlocks>; BlockLDLTDecomposition() { static_assert( BlockSize > 0 && NumBlocks > 0, "Invalid size."); } // Treating the matrix as a 2D table of scalars with NumDimensions // rows and NumDimensions columns, look up the correct block that // stores the requested element and return a reference. void Get(BlockMatrix const& M, int32_t row, int32_t col, T& value) { int32_t b0 = col / BlockSize; int32_t b1 = row / BlockSize; int32_t i0 = col - BlockSize * b0; int32_t i1 = row - BlockSize * b1; auto const& MBlock = M[b1][b0]; value = MBlock(i1, i0); } void Set(BlockMatrix& M, int32_t row, int32_t col, T const& value) { int32_t b0 = col / BlockSize; int32_t b1 = row / BlockSize; int32_t i0 = col - BlockSize * b0; int32_t i1 = row - BlockSize * b1; auto& MBlock = M[b1][b0]; MBlock(i1, i0) = value; } // Convert from a matrix to a block matrix. void Convert(Matrix<NumDimensions, NumDimensions, T> const& M, BlockMatrix& MBlock) const { for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize) { for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize) { auto& current = MBlock[r][c]; for (int32_t j = 0; j < BlockSize; ++j) { for (int32_t i = 0; i < BlockSize; ++i) { current(j, i) = M(rb + j, cb + i); } } } } } // Convert from a vector to a block vector. void Convert(Vector<NumDimensions, T> const& V, BlockVector& VBlock) const { for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize) { auto& current = VBlock[r]; for (int32_t j = 0; j < BlockSize; ++j) { current[j] = V[rb + j]; } } } // Convert from a block matrix to a matrix. void Convert(BlockMatrix const& MBlock, Matrix<NumDimensions, NumDimensions, T>& M) const { for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize) { for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize) { auto const& current = MBlock[r][c]; for (int32_t j = 0; j < BlockSize; ++j) { for (int32_t i = 0; i < BlockSize; ++i) { M(rb + j, cb + i) = current(j, i); } } } } } // Convert from a block vector to a vector. void Convert(BlockVector const& VBlock, Vector<NumDimensions, T>& V) const { for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize) { auto const& current = VBlock[r]; for (int32_t j = 0; j < BlockSize; ++j) { V[rb + j] = current[j]; } } } // The block matrix A must be positive definite. The implementation // uses only the lower-triangular blocks of A. On output, the block // matrix L is lower unit triangular (diagonal blocks are BxB identity // matrices) and the block matrix D is diagonal (diagonal blocks are // BxB diagonal matrices). bool Factor(BlockMatrix const& A, BlockMatrix& L, BlockMatrix& D) { for (int32_t row = 0; row < NumBlocks; ++row) { for (int32_t col = 0; col < NumBlocks; ++col) { L[row][col].MakeZero(); D[row][col].MakeZero(); } } for (int32_t j = 0; j < NumBlocks; ++j) { Matrix<BlockSize, BlockSize, T> Djj = A[j][j]; for (int32_t k = 0; k < j; ++k) { auto const& Ljk = L[j][k]; auto const& Dkk = D[k][k]; Djj -= MultiplyABT(Ljk * Dkk, Ljk); } D[j][j] = Djj; bool invertible = false; Matrix<BlockSize, BlockSize, T> invDjj = Inverse(Djj, &invertible); if (!invertible) { return false; } L[j][j].MakeIdentity(); for (int32_t i = j + 1; i < NumBlocks; ++i) { Matrix<BlockSize, BlockSize, T> Lij = A[i][j]; for (int32_t k = 0; k < j; ++k) { auto const& Lik = L[i][k]; auto const& Ljk = L[j][k]; auto const& Dkk = D[k][k]; Lij -= MultiplyABT(Lik * Dkk, Ljk); } Lij = Lij * invDjj; L[i][j] = Lij; } } return true; } // Solve A*X = B for positive definite A = L * D * L^T with // factoring before the call. void Solve(BlockMatrix const& L, BlockMatrix const& D, BlockVector const& B, BlockVector& X) { // Solve L * Z = L * (D * L^T * X) = B for Z. for (int32_t r = 0; r < NumBlocks; ++r) { X[r] = B[r]; for (int32_t c = 0; c < r; ++c) { X[r] -= L[r][c] * X[c]; } } // Solve D * Y = D * (L^T * X) = Z for Y. for (int32_t r = 0; r < NumBlocks; ++r) { X[r] = Inverse(D[r][r]) * X[r]; } // Solve L^T * Y = Z for X. for (int32_t r = NumBlocks - 1; r >= 0; --r) { for (int32_t c = r + 1; c < NumBlocks; ++c) { X[r] -= X[c] * L[c][r]; } } } // Solve A*X = B for positive definite A = L * D * L^T with // factoring during the call. void Solve(BlockMatrix const& A, BlockVector const& B, BlockVector& X) { BlockMatrix L, D; Factor(A, L, D); Solve(L, D, B, X); } }; // Implementation for sizes known only at run time. template <typename T> class BlockLDLTDecomposition<T> { public: // Let B represent the block size and N represent the number of // blocks. The matrix A is (N*B)-by-(N*B) but partitioned into an // N-by-N matrix of blocks, each block of size B-by-B and stored in // row-major order. The value N*B is NumDimensions. int32_t const BlockSize; int32_t const NumBlocks; int32_t const NumDimensions; // The number of elements in a BlockVector object must be NumBlocks // and each GVector element has BlockSize components. using BlockVector = std::vector<GVector<T>>; // The BlockMatrix is an array of NumBlocks-by-NumBlocks matrices. // Each block matrix is stored in row-major order. The BlockMatrix // elements themselves are stored in row-major order. The block // matrix element M = BlockMatrix[col + NumBlocks * row] is of size // BlockSize-by-BlockSize (in row-major order) and is in the (row,col) // location of the full matrix of blocks. using BlockMatrix = std::vector<GMatrix<T>>; BlockLDLTDecomposition(int32_t blockSize, int32_t numBlocks) : BlockSize(blockSize), NumBlocks(numBlocks), NumDimensions(blockSize* numBlocks) { LogAssert( blockSize > 0 && numBlocks > 0, "Invalid size."); } // Treating the matrix as a 2D table of scalars with NumDimensions // rows and NumDimensions columns, look up the correct block that // stores the requested element and return a reference. NOTE: You // are responsible for ensuring that M has NumBlocks-by-NumBlocks // elements, each M[] having BlockSize-by-BlockSize elements. void Get(BlockMatrix const& M, int32_t row, int32_t col, T& value, bool verifySize = true) { if (verifySize) { LogAssert( M.size() == static_cast<size_t>(NumBlocks) * static_cast<size_t>(NumBlocks), "Invalid size."); } int32_t b0 = col / BlockSize; int32_t b1 = row / BlockSize; int32_t i0 = col - BlockSize * b0; int32_t i1 = row - BlockSize * b1; auto const& MBlock = M[GetIndex(b1, b0)]; if (verifySize) { LogAssert( MBlock.GetNumRows() == BlockSize && MBlock.GetNumCols() == BlockSize, "Invalid size."); } value = MBlock(i1, i0); } void Set(BlockMatrix& M, int32_t row, int32_t col, T const& value, bool verifySize = true) { if (verifySize) { LogAssert( M.size() == static_cast<size_t>(NumBlocks) * static_cast<size_t>(NumBlocks), "Invalid size."); } int32_t b0 = col / BlockSize; int32_t b1 = row / BlockSize; int32_t i0 = col - BlockSize * b0; int32_t i1 = row - BlockSize * b1; auto& MBlock = M[GetIndex(b1, b0)]; if (verifySize) { LogAssert( MBlock.GetNumRows() == BlockSize && MBlock.GetNumCols() == BlockSize, "Invalid size."); } MBlock(i1, i0) = value; } // Convert from a matrix to a block matrix. void Convert(GMatrix<T> const& M, BlockMatrix& MBlock, bool verifySize = true) const { if (verifySize) { LogAssert( M.GetNumRows() == NumDimensions && M.GetNumCols() == NumDimensions, "Invalid size."); } size_t const szNumBlocks = static_cast<size_t>(NumBlocks); MBlock.resize(szNumBlocks * szNumBlocks); for (int32_t r = 0, rb = 0, index = 0; r < NumBlocks; ++r, rb += BlockSize) { for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize, ++index) { auto& current = MBlock[index]; current.SetSize(BlockSize, BlockSize); for (int32_t j = 0; j < BlockSize; ++j) { for (int32_t i = 0; i < BlockSize; ++i) { current(j, i) = M(rb + j, cb + i); } } } } } // Convert from a vector to a block vector. void Convert(GVector<T> const& V, BlockVector& VBlock, bool verifySize = true) const { if (verifySize) { LogAssert( V.GetSize() == NumDimensions, "Invalid size."); } VBlock.resize(static_cast<size_t>(NumBlocks)); for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize) { auto& current = VBlock[r]; current.SetSize(BlockSize); for (int32_t j = 0; j < BlockSize; ++j) { current[j] = V[rb + j]; } } } // Convert from a block matrix to a matrix. void Convert(BlockMatrix const& MBlock, GMatrix<T>& M, bool verifySize = true) const { if (verifySize) { LogAssert( MBlock.size() == static_cast<size_t>(NumBlocks) * static_cast<size_t>(NumBlocks), "Invalid size."); for (auto const& current : MBlock) { LogAssert( current.GetNumRows() == NumBlocks && current.GetNumCols() == NumBlocks, "Invalid size."); } } M.SetSize(NumDimensions, NumDimensions); for (int32_t r = 0, rb = 0, index = 0; r < NumBlocks; ++r, rb += BlockSize) { for (int32_t c = 0, cb = 0; c < NumBlocks; ++c, cb += BlockSize, ++index) { auto const& current = MBlock[index]; for (int32_t j = 0; j < BlockSize; ++j) { for (int32_t i = 0; i < BlockSize; ++i) { M(rb + j, cb + i) = current(j, i); } } } } } // Convert from a block vector to a vector. void Convert(BlockVector const& VBlock, GVector<T>& V, bool verifySize = true) const { if (verifySize) { LogAssert( VBlock.size() == static_cast<size_t>(NumBlocks), "Invalid size."); for (auto const& current : VBlock) { LogAssert( current.GetSize() == NumBlocks, "Invalid size."); } } V.SetSize(NumDimensions); for (int32_t r = 0, rb = 0; r < NumBlocks; ++r, rb += BlockSize) { auto const& current = VBlock[r]; for (int32_t j = 0; j < BlockSize; ++j) { V[rb + j] = current[j]; } } } // The block matrix A must be positive definite. The implementation // uses only the lower-triangular blocks of A. On output, the block // matrix L is lower unit triangular (diagonal blocks are BxB identity // matrices) and the block matrix D is diagonal (diagonal blocks are // BxB diagonal matrices). bool Factor(BlockMatrix const& A, BlockMatrix& L, BlockMatrix& D, bool verifySize = true) { if (verifySize) { size_t szNumBlocks = static_cast<size_t>(NumBlocks); LogAssert( A.size() == szNumBlocks * szNumBlocks, "Invalid size."); for (size_t i = 0; i < A.size(); ++i) { LogAssert( A[i].GetNumRows() == BlockSize && A[i].GetNumCols() == BlockSize, "Invalid size."); } } L.resize(A.size()); D.resize(A.size()); for (size_t i = 0; i < L.size(); ++i) { L[i].SetSize(BlockSize, BlockSize); L[i].MakeZero(); D[i].SetSize(BlockSize, BlockSize); D[i].MakeZero(); } for (int32_t j = 0; j < NumBlocks; ++j) { GMatrix<T> Djj = A[GetIndex(j, j)]; for (int32_t k = 0; k < j; ++k) { auto const& Ljk = L[GetIndex(j, k)]; auto const& Dkk = D[GetIndex(k, k)]; Djj -= MultiplyABT(Ljk * Dkk, Ljk); } D[GetIndex(j, j)] = Djj; bool invertible = false; GMatrix<T> invDjj = Inverse(Djj, &invertible); if (!invertible) { return false; } L[GetIndex(j, j)].MakeIdentity(); for (int32_t i = j + 1; i < NumBlocks; ++i) { GMatrix<T> Lij = A[GetIndex(i, j)]; for (int32_t k = 0; k < j; ++k) { auto const& Lik = L[GetIndex(i, k)]; auto const& Ljk = L[GetIndex(j, k)]; auto const& Dkk = D[GetIndex(k, k)]; Lij -= MultiplyABT(Lik * Dkk, Ljk); } Lij = Lij * invDjj; L[GetIndex(i, j)] = Lij; } } return true; } // Solve A*X = B for positive definite A = L * D * L^T with // factoring before the call. void Solve(BlockMatrix const& L, BlockMatrix const& D, BlockVector const& B, BlockVector& X, bool verifySize = true) { if (verifySize) { size_t const szNumBlocks = static_cast<size_t>(NumBlocks); size_t const LDsize = szNumBlocks * szNumBlocks; LogAssert( L.size() == LDsize && D.size() == LDsize && B.size() == szNumBlocks, "Invalid size."); for (size_t i = 0; i < L.size(); ++i) { LogAssert( L[i].GetNumRows() == BlockSize && L[i].GetNumCols() == BlockSize && D[i].GetNumRows() == BlockSize && D[i].GetNumCols() == BlockSize, "Invalid size."); } for (size_t i = 0; i < B.size(); ++i) { LogAssert( B[i].GetSize() == BlockSize, "Invalid size."); } } // Solve L * Z = L * (D * L^T * X) = B for Z. X.resize(static_cast<size_t>(NumBlocks)); for (int32_t r = 0; r < NumBlocks; ++r) { X[r] = B[r]; for (int32_t c = 0; c < r; ++c) { X[r] -= L[GetIndex(r, c)] * X[c]; } } // Solve D * Y = D * (L^T * X) = Z for Y. for (int32_t r = 0; r < NumBlocks; ++r) { X[r] = Inverse(D[GetIndex(r, r)]) * X[r]; } // Solve L^T * Y = Z for X. for (int32_t r = NumBlocks - 1; r >= 0; --r) { for (int32_t c = r + 1; c < NumBlocks; ++c) { X[r] -= X[c] * L[GetIndex(c, r)]; } } } // Solve A*X = B for positive definite A = L * D * L^T with // factoring during the call. void Solve(BlockMatrix const& A, BlockVector const& B, BlockVector& X, bool verifySize = true) { if (verifySize) { size_t const szNumBlocks = static_cast<size_t>(NumBlocks); LogAssert( A.size() == szNumBlocks * szNumBlocks && B.size() == szNumBlocks, "Invalid size."); for (size_t i = 0; i < A.size(); ++i) { LogAssert( A[i].GetNumRows() == BlockSize && A[i].GetNumCols() == BlockSize, "Invalid size."); } for (size_t i = 0; i < B.size(); ++i) { LogAssert( B[i].GetSize() == BlockSize, "Invalid size."); } } BlockMatrix L, D; Factor(A, L, D, false); Solve(L, D, B, X, false); } private: // Compute the 1-dimensional index of the block matrix in a // 2-dimensional BlockMatrix object. inline size_t GetIndex(int32_t row, int32_t col) const { return static_cast<size_t>(col + row * static_cast<size_t>(NumBlocks)); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment2AlignedBox2.h
.h
6,472
167
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine2AlignedBox2.h> #include <Mathematics/Segment.h> #include <Mathematics/Vector2.h> // The queries consider the box to be a solid. // // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the four // edges of the box. namespace gte { template <typename Real> class TIQuery<Real, Segment2<Real>, AlignedBox2<Real>> : public TIQuery<Real, Line2<Real>, AlignedBox2<Real>> { public: struct Result : public TIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result { Result() : TIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result{} { } // No additional information to compute. }; Result operator()(Segment2<Real> const& segment, AlignedBox2<Real> const& box) { // Get the centered form of the aligned box. The axes are // implicitly Axis[d] = Vector2<Real>::Unit(d). Vector2<Real> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the segment to a centered form in the aligned-box // coordinate system. Vector2<Real> transformedP0 = segment.p[0] - boxCenter; Vector2<Real> transformedP1 = segment.p[1] - boxCenter; Segment2<Real> transformedSegment(transformedP0, transformedP1); Vector2<Real> segOrigin{}, segDirection{}; Real segExtent{}; transformedSegment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, boxExtent, result); return result; } protected: void DoQuery(Vector2<Real> const& segOrigin, Vector2<Real> const& segDirection, Real segExtent, Vector2<Real> const& boxExtent, Result& result) { for (int32_t i = 0; i < 2; ++i) { Real lhs = std::fabs(segOrigin[i]); Real rhs = boxExtent[i] + segExtent * std::fabs(segDirection[i]); if (lhs > rhs) { result.intersect = false; return; } } TIQuery<Real, Line2<Real>, AlignedBox2<Real>>::DoQuery(segOrigin, segDirection, boxExtent, result); } }; template <typename Real> class FIQuery<Real, Segment2<Real>, AlignedBox2<Real>> : public FIQuery<Real, Line2<Real>, AlignedBox2<Real>> { public: struct Result : public FIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result { Result() : FIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result{}, cdeParameter{ (Real)0, (Real)0 } { } // The base class parameter[] values are t-values for the // segment parameterization (1-t)*p[0] + t*p[1], where t in [0,1]. // The values in this class are s-values for the centered form // C + s * D, where s in [-e,e] and e is the extent of the // segment. std::array<Real, 2> cdeParameter; }; Result operator()(Segment2<Real> const& segment, AlignedBox2<Real> const& box) { // Get the centered form of the aligned box. The axes are // implicitly Axis[d] = Vector2<Real>::Unit(d). Vector2<Real> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the segment to a centered form in the aligned-box // coordinate system. Vector2<Real> transformedP0 = segment.p[0] - boxCenter; Vector2<Real> transformedP1 = segment.p[1] - boxCenter; Segment2<Real> transformedSegment(transformedP0, transformedP1); Vector2<Real> segOrigin{}, segDirection{}; Real segExtent{}; transformedSegment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, boxExtent, result); for (int32_t i = 0; i < result.numIntersections; ++i) { // Compute the segment in the aligned-box coordinate system // and then translate it back to the original coordinates // using the box cener. result.point[i] = boxCenter + (segOrigin + result.parameter[i] * segDirection); result.cdeParameter[i] = result.parameter[i]; // Convert the parameters from the centered form to the // endpoint form. result.parameter[i] = (result.parameter[i] / segExtent + (Real)1) * (Real)0.5; } return result; } protected: void DoQuery(Vector2<Real> const& segOrigin, Vector2<Real> const& segDirection, Real segExtent, Vector2<Real> const& boxExtent, Result& result) { FIQuery<Real, Line2<Real>, AlignedBox2<Real>>::DoQuery(segOrigin, segDirection, boxExtent, result); if (result.intersect) { // The line containing the segment intersects the box; the // t-interval is [t0,t1]. The segment intersects the box as // long as [t0,t1] overlaps the segment t-interval // [-segExtent,+segExtent]. std::array<Real, 2> segInterval = { -segExtent, segExtent }; FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>> iiQuery{}; auto iiResult = iiQuery(result.parameter, segInterval); result.intersect = iiResult.intersect; result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContEllipsoid3.h
.h
6,373
165
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprGaussian3.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/Projection.h> #include <Mathematics/Rotation.h> namespace gte { // The input points are fit with a Gaussian distribution. The center C of // the ellipsoid is chosen to be the mean of the distribution. The axes // of the ellipsoid are chosen to be the eigenvectors of the covariance // matrix M. The shape of the ellipsoid is determined by the absolute // values of the eigenvalues. NOTE: The construction is ill-conditioned // if the points are (nearly) collinear or (nearly) planar. In this case // M has a (nearly) zero eigenvalue, so inverting M is problematic. template <typename Real> bool GetContainer(int32_t numPoints, Vector3<Real> const* points, Ellipsoid3<Real>& ellipsoid) { // Fit the points with a Gaussian distribution. The covariance // matrix is M = sum_j D[j]*U[j]*U[j]^T, where D[j] are the // eigenvalues and U[j] are corresponding unit-length eigenvectors. ApprGaussian3<Real> fitter; if (fitter.Fit(numPoints, points)) { OrientedBox3<Real> box = fitter.GetParameters(); // If either eigenvalue is nonpositive, adjust the D[] values so // that we actually build an ellipsoid. for (int32_t j = 0; j < 3; ++j) { if (box.extent[j] < (Real)0) { box.extent[j] = -box.extent[j]; } } // Grow the ellipsoid, while retaining its shape determined by the // covariance matrix, to enclose all the input points. The // quadratic/ form that is used for the ellipsoid construction is // Q(X) = (X-C)^T*M*(X-C) // = (X-C)^T*(sum_j D[j]*U[j]*U[j]^T)*(X-C) // = sum_j D[j]*Dot(U[j],X-C)^2 // If the maximum value of Q(X[i]) for all input points is V^2, // then a bounding ellipsoid is Q(X) = V^2 since Q(X[i]) <= V^2 // for all i. Real maxValue = (Real)0; for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - box.center; Real dot[3] = { Dot(box.axis[0], diff), Dot(box.axis[1], diff), Dot(box.axis[2], diff) }; Real value = box.extent[0] * dot[0] * dot[0] + box.extent[1] * dot[1] * dot[1] + box.extent[2] * dot[2] * dot[2]; if (value > maxValue) { maxValue = value; } } // Arrange for the quadratic to satisfy Q(X) <= 1. ellipsoid.center = box.center; for (int32_t j = 0; j < 3; ++j) { ellipsoid.axis[j] = box.axis[j]; ellipsoid.extent[j] = std::sqrt(maxValue / box.extent[j]); } return true; } return false; } // Test for containment of a point inside an ellipsoid. template <typename Real> bool InContainer(Vector3<Real> const& point, Ellipsoid3<Real> const& ellipsoid) { Vector3<Real> diff = point - ellipsoid.center; Vector3<Real> standardized{ Dot(diff, ellipsoid.axis[0]) / ellipsoid.extent[0], Dot(diff, ellipsoid.axis[1]) / ellipsoid.extent[1], Dot(diff, ellipsoid.axis[2]) / ellipsoid.extent[2] }; return Length(standardized) <= (Real)1; } // Construct a bounding ellipsoid for the two input ellipsoids. The result is // not necessarily the minimum-volume ellipsoid containing the two ellipsoids. template <typename Real> bool MergeContainers(Ellipsoid3<Real> const& ellipsoid0, Ellipsoid3<Real> const& ellipsoid1, Ellipsoid3<Real>& merge) { // Compute the average of the input centers merge.center = (Real)0.5 * (ellipsoid0.center + ellipsoid1.center); // The bounding ellipsoid orientation is the average of the input // orientations. Matrix3x3<Real> rot0, rot1; rot0.SetCol(0, ellipsoid0.axis[0]); rot0.SetCol(1, ellipsoid0.axis[1]); rot0.SetCol(2, ellipsoid0.axis[2]); rot1.SetCol(0, ellipsoid1.axis[0]); rot1.SetCol(1, ellipsoid1.axis[1]); rot1.SetCol(2, ellipsoid1.axis[2]); Quaternion<Real> q0 = Rotation<3, Real>(rot0); Quaternion<Real> q1 = Rotation<3, Real>(rot1); if (Dot(q0, q1) < (Real)0) { q1 = -q1; } Quaternion<Real> q = q0 + q1; Normalize(q); Matrix3x3<Real> rot = Rotation<3, Real>(q); for (int32_t j = 0; j < 3; ++j) { merge.axis[j] = rot.GetCol(j); } // Project the input ellipsoids onto the axes obtained by the average // of the orientations and that go through the center obtained by the // average of the centers. for (int32_t i = 0; i < 3; ++i) { // Projection axis. Line3<Real> line(merge.center, merge.axis[i]); // Project ellipsoids onto the axis. Real min0, max0, min1, max1; Project(ellipsoid0, line, min0, max0); Project(ellipsoid1, line, min1, max1); // Determine the smallest interval containing the projected // intervals. Real maxIntr = (max0 >= max1 ? max0 : max1); Real minIntr = (min0 <= min1 ? min0 : min1); // Update the average center to be the center of the bounding box // defined by the projected intervals. merge.center += line.direction * ((Real)0.5 * (minIntr + maxIntr)); // Compute the extents of the box based on the new center. merge.extent[i] = (Real)0.5 * (maxIntr - minIntr); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment2Circle2.h
.h
3,076
100
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine2Circle2.h> #include <Mathematics/Segment.h> // The queries consider the circle to be a solid (disk). namespace gte { template <typename T> class TIQuery<T, Segment2<T>, Circle2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Segment2<T> const& segment, Circle2<T> const& circle) { Result result{}; FIQuery<T, Segment2<T>, Circle2<T>> scQuery{}; result.intersect = scQuery(segment, circle).intersect; return result; } }; template <typename T> class FIQuery<T, Segment2<T>, Circle2<T>> : public FIQuery<T, Line2<T>, Circle2<T>> { public: struct Result : public FIQuery<T, Line2<T>, Circle2<T>>::Result { Result() : FIQuery<T, Line2<T>, Circle2<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment2<T> const& segment, Circle2<T> const& circle) { Vector2<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, circle, result); for (int32_t i = 0; i < result.numIntersections; ++i) { result.point[i] = segOrigin + result.parameter[i] * segDirection; } return result; } protected: void DoQuery(Vector2<T> const& segOrigin, Vector2<T> const& segDirection, T segExtent, Circle2<T> const& circle, Result& result) { FIQuery<T, Line2<T>, Circle2<T>>::DoQuery(segOrigin, segDirection, circle, result); if (result.intersect) { // The line containing the segment intersects the disk; the // t-interval is [t0,t1]. The segment intersects the disk as // long as [t0,t1] overlaps the segment t-interval // [-segExtent,+segExtent]. std::array<T, 2> segInterval = { -segExtent, segExtent }; FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; auto iiResult = iiQuery(result.parameter, segInterval); result.intersect = iiResult.intersect; result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ConvertCoordinates.h
.h
13,279
357
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/GaussianElimination.h> // Convert points and transformations between two coordinate systems. // The mathematics involves a change of basis. See the document // https://www.geometrictools.com/Documentation/ConvertingBetweenCoordinateSystems.pdf // for the details. Typical usage for 3D conversion is shown next. // // // Linear change of basis. The columns of U are the basis vectors for the // // source coordinate system. A vector X = { x0, x1, x2 } in the source // // coordinate system is represented by // // X = x0*(1,0,0) + x1*(0,1,0) + x2*(0,0,1) // // The Cartesian coordinates for the point are the combination of these // // terms, // // X = (x0, x1, x2) // // The columns of V are the basis vectors for the target coordinate system. // // A vector Y = { y0, y1, y2 } in the target coordinate system is // // represented by // // Y = y0*(1,0,0,0) + y1*(0,0,1) + y2*(0,1,0) // // The Cartesian coordinates for the vector are the combination of these // // terms, // // Y = (y0, y2, y1) // // The call Y = convert.UToV(X) computes y0, y1 and y2 so that the Cartesian // // coordinates for X and for Y are the same. For example, // // X = { 1.0, 2.0, 3.0 } // // = 1.0*(1,0,0) + 2.0*(0,1,0) + 3.0*(0,0,1) // // = (1, 2, 3) // // Y = { 1.0, 3.0, 2.0 } // // = 1.0*(1,0,0) + 3.0*(0,0,1) + 2.0*(0,1,0) // // = (1, 2, 3) // // X and Y represent the same vector (equal Cartesian coordinates) but have // // different representations in the source and target coordinates. // // ConvertCoordinates<3, double> convert; // Vector<3, double> X, Y, P0, P1, diff; // Matrix<3, 3, double> U, V, A, B; // bool isRHU, isRHV; // U.SetCol(0, Vector3<double>{1.0, 0.0, 0.0}); // U.SetCol(1, Vector3<double>{0.0, 1.0, 0.0}); // U.SetCol(2, Vector3<double>{0.0, 0.0, 1.0}); // V.SetCol(0, Vector3<double>{1.0, 0.0, 0.0}); // V.SetCol(1, Vector3<double>{0.0, 0.0, 1.0}); // V.SetCol(2, Vector3<double>{0.0, 1.0, 0.0}); // convert(U, true, V, true); // isRHU = convert.IsRightHandedU(); // true // isRHV = convert.IsRightHandedV(); // false // X = { 1.0, 2.0, 3.0 }; // Y = convert.UToV(X); // { 1.0, 3.0, 2.0 } // P0 = U*X; // P1 = V*Y; // diff = P0 - P1; // { 0, 0, 0 } // Y = { 0.0, 1.0, 2.0 }; // X = convert.VToU(Y); // { 0.0, 2.0, 1.0 } // P0 = U*X; // P1 = V*Y; // diff = P0 - P1; // { 0, 0, 0 } // double cs = 0.6, sn = 0.8; // cs*cs + sn*sn = 1 // A.SetCol(0, Vector3<double>{ c, s, 0.0}); // A.SetCol(1, Vector3<double>{ -s, c, 0.0}); // A.SetCol(2, Vector3<double>{0.0, 0.0, 1.0}); // B = convert.UToV(A); // // B.GetCol(0) = { c, 0, s} // // B.GetCol(1) = { 0, 1, 0} // // B.GetCol(2) = {-s, 0, c} // X = A*X; // U is VOR // Y = B*Y; // V is VOR // P0 = U*X; // P1 = V*Y; // diff = P0 - P1; // { 0, 0, 0 } // // // Affine change of basis. The first three columns of U are the basis // // vectors for the source coordinate system and must have last components // // set to 0. The last column is the origin for that system and must have // // last component set to 1. A point X = { x0, x1, x2, 1 } in the source // // coordinate system is represented by // // X = x0*(-1,0,0,0) + x1*(0,0,1,0) + x2*(0,-1,0,0) + 1*(1,2,3,1) // // The Cartesian coordinates for the point are the combination of these // // terms, // // X = (-x0 + 1, -x2 + 2, x1 + 3, 1) // // The first three columns of V are the basis vectors for the target // // coordinate system and must have last components set to 0. The last // // column is the origin for that system and must have last component set // // to 1. A point Y = { y0, y1, y2, 1 } in the target coordinate system is // // represented by // // Y = y0*(0,1,0,0) + y1*(-1,0,0,0) + y2*(0,0,1,0) + 1*(4,5,6,1) // // The Cartesian coordinates for the point are the combination of these // // terms, // // Y = (-y1 + 4, y0 + 5, y2 + 6, 1) // // The call Y = convert.UToV(X) computes y0, y1 and y2 so that the Cartesian // // coordinates for X and for Y are the same. For example, // // X = { -1.0, 4.0, -3.0, 1.0 } // // = -1.0*(-1,0,0,0) + 4.0*(0,0,1,0) - 3.0*(0,-1,0,0) + 1.0*(1,2,3,1) // // = (2, 5, 7, 1) // // Y = { 0.0, 2.0, 1.0, 1.0 } // // = 0.0*(0,1,0,0) + 2.0*(-1,0,0,0) + 1.0*(0,0,1,0) + 1.0*(4,5,6,1) // // = (2, 5, 7, 1) // // X and Y represent the same point (equal Cartesian coordinates) but have // // different representations in the source and target affine coordinates. // // ConvertCoordinates<4, double> convert; // Vector<4, double> X, Y, P0, P1, diff; // Matrix<4, 4, double> U, V, A, B; // bool isRHU, isRHV; // U.SetCol(0, Vector4<double>{-1.0, 0.0, 0.0, 0.0}); // U.SetCol(1, Vector4<double>{0.0, 0.0, 1.0, 0.0}); // U.SetCol(2, Vector4<double>{0.0, -1.0, 0.0, 0.0}); // U.SetCol(3, Vector4<double>{1.0, 2.0, 3.0, 1.0}); // V.SetCol(0, Vector4<double>{0.0, 1.0, 0.0, 0.0}); // V.SetCol(1, Vector4<double>{-1.0, 0.0, 0.0, 0.0}); // V.SetCol(2, Vector4<double>{0.0, 0.0, 1.0, 0.0}); // V.SetCol(3, Vector4<double>{4.0, 5.0, 6.0, 1.0}); // convert(U, true, V, false); // isRHU = convert.IsRightHandedU(); // false // isRHV = convert.IsRightHandedV(); // true // X = { -1.0, 4.0, -3.0, 1.0 }; // Y = convert.UToV(X); // { 0.0, 2.0, 1.0, 1.0 } // P0 = U*X; // P1 = V*Y; // diff = P0 - P1; // { 0, 0, 0, 0 } // Y = { 1.0, 2.0, 3.0, 1.0 }; // X = convert.VToU(Y); // { -1.0, 6.0, -4.0, 1.0 } // P0 = U*X; // P1 = V*Y; // diff = P0 - P1; // { 0, 0, 0, 0 } // double c = 0.6, s = 0.8; // c*c + s*s = 1 // A.SetCol(0, Vector4<double>{ c, s, 0.0, 0.0}); // A.SetCol(1, Vector4<double>{ -s, c, 0.0, 0.0}); // A.SetCol(2, Vector4<double>{0.0, 0.0, 1.0, 0.0}); // A.SetCol(3, Vector4<double>{0.3, 1.0, -2.0, 1.0}); // B = convert.UToV(A); // // B.GetCol(0) = { 1, 0, 0, 0 } // // B.GetCol(1) = { 0, c, s, 0 } // // B.GetCol(2) = { 0, -s, c, 0 } // // B.GetCol(3) = { 2.0, -0.9, -2.6, 1 } // X = A*X; // U is VOR // Y = Y*B; // V is VOL (not VOR) // P0 = U*X; // P1 = V*Y; // diff = P0 - P1; // { 0, 0, 0, 0 } namespace gte { template <int32_t N, typename Real> class ConvertCoordinates { public: // Construction of the change of basis matrix. The implementation // supports both linear change of basis and affine change of basis. ConvertCoordinates() : mC{}, mInverseC{}, mIsVectorOnRightU(true), mIsVectorOnRightV(true), mIsRightHandedU(true), mIsRightHandedV(true) { mC.MakeIdentity(); mInverseC.MakeIdentity(); } // Compute a change of basis between two coordinate systems. The // return value is 'true' iff U and V are invertible. The // matrix-vector multiplication conventions affect the conversion of // matrix transformations. The Boolean inputs indicate how you want // the matrices to be interpreted when applied as transformations of // a vector. bool operator()( Matrix<N, N, Real> const& U, bool vectorOnRightU, Matrix<N, N, Real> const& V, bool vectorOnRightV) { // Initialize in case of early exit. mC.MakeIdentity(); mInverseC.MakeIdentity(); mIsVectorOnRightU = true; mIsVectorOnRightV = true; mIsRightHandedU = true; mIsRightHandedV = true; Matrix<N, N, Real> inverseU; Real determinantU; bool invertibleU = GaussianElimination<Real>()(N, &U[0], &inverseU[0], determinantU, nullptr, nullptr, nullptr, 0, nullptr); if (!invertibleU) { return false; } Matrix<N, N, Real> inverseV; Real determinantV; bool invertibleV = GaussianElimination<Real>()(N, &V[0], &inverseV[0], determinantV, nullptr, nullptr, nullptr, 0, nullptr); if (!invertibleV) { return false; } mC = inverseU * V; mInverseC = inverseV * U; mIsVectorOnRightU = vectorOnRightU; mIsVectorOnRightV = vectorOnRightV; mIsRightHandedU = (determinantU > (Real)0); mIsRightHandedV = (determinantV > (Real)0); return true; } // Member access. inline Matrix<N, N, Real> const& GetC() const { return mC; } inline Matrix<N, N, Real> const& GetInverseC() const { return mInverseC; } inline bool IsVectorOnRightU() const { return mIsVectorOnRightU; } inline bool IsVectorOnRightV() const { return mIsVectorOnRightV; } inline bool IsRightHandedU() const { return mIsRightHandedU; } inline bool IsRightHandedV() const { return mIsRightHandedV; } // Convert points between coordinate systems. The names of the // systems are U and V to make it clear which inputs of operator() // they are associated with. The X vector stores coordinates for the // U-system and the Y vector stores coordinates for the V-system. // Y = C^{-1}*X inline Vector<N, Real> UToV(Vector<N, Real> const& X) const { return mInverseC * X; } // X = C*Y inline Vector<N, Real> VToU(Vector<N, Real> const& Y) const { return mC * Y; } // Convert transformations between coordinate systems. The outputs // are computed according to the tables shown before the function // declarations. The superscript T denotes the transpose operator. // vectorOnRightU = true: transformation is X' = A*X // vectorOnRightU = false: transformation is (X')^T = X^T*A // vectorOnRightV = true: transformation is Y' = B*Y // vectorOnRightV = false: transformation is (Y')^T = Y^T*B // vectorOnRightU | vectorOnRightV | output // ----------------+-----------------+--------------------- // true | true | C^{-1} * A * C // true | false | (C^{-1} * A * C)^T // false | true | C^{-1} * A^T * C // false | false | (C^{-1} * A^T * C)^T Matrix<N, N, Real> UToV(Matrix<N, N, Real> const& A) const { Matrix<N, N, Real> product; if (mIsVectorOnRightU) { product = mInverseC * A * mC; if (mIsVectorOnRightV) { return product; } else { return Transpose(product); } } else { product = mInverseC * MultiplyATB(A, mC); if (mIsVectorOnRightV) { return product; } else { return Transpose(product); } } } // vectorOnRightU | vectorOnRightV | output // ----------------+-----------------+--------------------- // true | true | C * B * C^{-1} // true | false | C * B^T * C^{-1} // false | true | (C * B * C^{-1})^T // false | false | (C * B^T * C^{-1})^T Matrix<N, N, Real> VToU(Matrix<N, N, Real> const& B) const { // vectorOnRightU | vectorOnRightV | output // ----------------+-----------------+--------------------- // true | true | C * B * C^{-1} // true | false | C * B^T * C^{-1} // false | true | (C * B * C^{-1})^T // false | false | (C * B^T * C^{-1})^T Matrix<N, N, Real> product; if (mIsVectorOnRightV) { product = mC * B * mInverseC; if (mIsVectorOnRightU) { return product; } else { return Transpose(product); } } else { product = mC * MultiplyATB(B, mInverseC); if (mIsVectorOnRightU) { return product; } else { return Transpose(product); } } } private: // C = U^{-1}*V, C^{-1} = V^{-1}*U Matrix<N, N, Real> mC, mInverseC; bool mIsVectorOnRightU, mIsVectorOnRightV; bool mIsRightHandedU, mIsRightHandedV; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrAlignedBox2Circle2.h
.h
13,384
363
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/DistPointAlignedBox.h> #include <Mathematics/Vector2.h> // The find-intersection query is based on the document // https://www.geometrictools.com/Documentation/IntersectionMovingCircleRectangle.pdf namespace gte { template <typename T> class TIQuery<T, AlignedBox2<T>, Circle2<T>> { public: // The intersection query considers the box and circle to be solids; // that is, the circle object includes the region inside the circular // boundary and the box object includes the region inside the // rectangular boundary. If the circle object and box object // overlap, the objects intersect. struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(AlignedBox2<T> const& box, Circle2<T> const& circle) { DCPQuery<T, Vector2<T>, AlignedBox2<T>> pbQuery; auto pbResult = pbQuery(circle.center, box); Result result{}; result.intersect = (pbResult.sqrDistance <= circle.radius * circle.radius); return result; } }; template <typename T> class FIQuery<T, AlignedBox2<T>, Circle2<T>> { public: // Currently, only a dynamic query is supported. A static query will // need to compute the intersection set of (solid) box and circle. struct Result { Result() : intersectionType(0), contactTime(static_cast<T>(0)), contactPoint(Vector2<T>::Zero()) { } // The cases are // 1. Objects initially overlapping. The contactPoint is only one // of infinitely many points in the overlap. // intersectionType = -1 // contactTime = 0 // contactPoint = circle.center // 2. Objects initially separated but do not intersect later. The // contactTime and contactPoint are invalid. // intersectionType = 0 // contactTime = 0 // contactPoint = (0,0) // 3. Objects initially separated but intersect later. // intersectionType = +1 // contactTime = first time T > 0 // contactPoint = corresponding first contact int32_t intersectionType; T contactTime; Vector2<T> contactPoint; // TODO: To support arbitrary precision for the contactTime, // return q0, q1 and q2 where contactTime = (q0 - sqrt(q1)) / q2. // The caller can compute contactTime to desired number of digits // of precision. These are valid when intersectionType is +1 but // are set to zero (invalid) in the other cases. Do the same for // the contactPoint. }; Result operator()(AlignedBox2<T> const& box, Vector2<T> const& boxVelocity, Circle2<T> const& circle, Vector2<T> const& circleVelocity) { Result result{}; // Translate the circle and box so that the box center becomes // the origin. Compute the velocity of the circle relative to // the box. Vector2<T> boxCenter = (box.max + box.min) * (T)0.5; Vector2<T> extent = (box.max - box.min) * (T)0.5; Vector2<T> C = circle.center - boxCenter; Vector2<T> V = circleVelocity - boxVelocity; // Change signs on components, if necessary, to transform C to the // first quadrant. Adjust the velocity accordingly. std::array<T, 2> sign = { (T)0, (T)0 }; for (int32_t i = 0; i < 2; ++i) { if (C[i] >= (T)0) { sign[i] = (T)1; } else { C[i] = -C[i]; V[i] = -V[i]; sign[i] = (T)-1; } } DoQuery(extent, C, circle.radius, V, result); if (result.intersectionType != 0) { // Translate back to the original coordinate system. for (int32_t i = 0; i < 2; ++i) { if (sign[i] < (T)0) { result.contactPoint[i] = -result.contactPoint[i]; } } result.contactPoint += boxCenter; } return result; } protected: void DoQuery(Vector2<T> const& K, Vector2<T> const& C, T radius, Vector2<T> const& V, Result& result) { Vector2<T> delta = C - K; if (delta[1] <= radius) { if (delta[0] <= radius) { if (delta[1] <= (T)0) { if (delta[0] <= (T)0) { InteriorOverlap(C, result); } else { EdgeOverlap(0, 1, K, C, delta, radius, result); } } else { if (delta[0] <= (T)0) { EdgeOverlap(1, 0, K, C, delta, radius, result); } else { if (Dot(delta, delta) <= radius * radius) { VertexOverlap(K, delta, radius, result); } else { VertexSeparated(K, delta, V, radius, result); } } } } else { EdgeUnbounded(0, 1, K, C, radius, delta, V, result); } } else { if (delta[0] <= radius) { EdgeUnbounded(1, 0, K, C, radius, delta, V, result); } else { VertexUnbounded(K, C, radius, delta, V, result); } } } private: void InteriorOverlap(Vector2<T> const& C, Result& result) { result.intersectionType = -1; result.contactTime = (T)0; result.contactPoint = C; } void EdgeOverlap(int32_t i0, int32_t i1, Vector2<T> const& K, Vector2<T> const& C, Vector2<T> const& delta, T radius, Result& result) { result.intersectionType = (delta[i0] < radius ? -1 : 1); result.contactTime = (T)0; result.contactPoint[i0] = K[i0]; result.contactPoint[i1] = C[i1]; } void VertexOverlap(Vector2<T> const& K0, Vector2<T> const& delta, T radius, Result& result) { T sqrDistance = delta[0] * delta[0] + delta[1] * delta[1]; T sqrRadius = radius * radius; result.intersectionType = (sqrDistance < sqrRadius ? -1 : 1); result.contactTime = (T)0; result.contactPoint = K0; } void VertexSeparated(Vector2<T> const& K0, Vector2<T> const& delta0, Vector2<T> const& V, T radius, Result& result) { T q0 = -Dot(V, delta0); if (q0 > (T)0) { T dotVPerpD0 = Dot(V, Perp(delta0)); T q2 = Dot(V, V); T q1 = radius * radius * q2 - dotVPerpD0 * dotVPerpD0; if (q1 >= (T)0) { IntersectsVertex(0, 1, K0, q0, q1, q2, result); } } } void EdgeUnbounded(int32_t i0, int32_t i1, Vector2<T> const& K0, Vector2<T> const& C, T radius, Vector2<T> const& delta0, Vector2<T> const& V, Result& result) { if (V[i0] < (T)0) { T dotVPerpD0 = V[i0] * delta0[i1] - V[i1] * delta0[i0]; if (radius * V[i1] + dotVPerpD0 >= (T)0) { Vector2<T> K1, delta1; K1[i0] = K0[i0]; K1[i1] = -K0[i1]; delta1[i0] = C[i0] - K1[i0]; delta1[i1] = C[i1] - K1[i1]; T dotVPerpD1 = V[i0] * delta1[i1] - V[i1] * delta1[i0]; if (radius * V[i1] + dotVPerpD1 <= (T)0) { IntersectsEdge(i0, i1, K0, C, radius, V, result); } else { T q2 = Dot(V, V); T q1 = radius * radius * q2 - dotVPerpD1 * dotVPerpD1; if (q1 >= (T)0) { T q0 = -(V[i0] * delta1[i0] + V[i1] * delta1[i1]); IntersectsVertex(i0, i1, K1, q0, q1, q2, result); } } } else { T q2 = Dot(V, V); T q1 = radius * radius * q2 - dotVPerpD0 * dotVPerpD0; if (q1 >= (T)0) { T q0 = -(V[i0] * delta0[i0] + V[i1] * delta0[i1]); IntersectsVertex(i0, i1, K0, q0, q1, q2, result); } } } } void VertexUnbounded(Vector2<T> const& K0, Vector2<T> const& C, T radius, Vector2<T> const& delta0, Vector2<T> const& V, Result& result) { if (V[0] < (T)0 && V[1] < (T)0) { T dotVPerpD0 = Dot(V, Perp(delta0)); if (radius * V[0] - dotVPerpD0 <= (T)0) { if (-radius * V[1] - dotVPerpD0 >= (T)0) { T q2 = Dot(V, V); T q1 = radius * radius * q2 - dotVPerpD0 * dotVPerpD0; T q0 = -Dot(V, delta0); IntersectsVertex(0, 1, K0, q0, q1, q2, result); } else { Vector2<T> K1{ K0[0], -K0[1] }; Vector2<T> delta1 = C - K1; T dotVPerpD1 = Dot(V, Perp(delta1)); if (-radius * V[1] - dotVPerpD1 >= (T)0) { IntersectsEdge(0, 1, K0, C, radius, V, result); } else { T q2 = Dot(V, V); T q1 = radius * radius * q2 - dotVPerpD1 * dotVPerpD1; if (q1 >= (T)0) { T q0 = -Dot(V, delta1); IntersectsVertex(0, 1, K1, q0, q1, q2, result); } } } } else { Vector2<T> K2{ -K0[0], K0[1] }; Vector2<T> delta2 = C - K2; T dotVPerpD2 = Dot(V, Perp(delta2)); if (radius * V[0] - dotVPerpD2 <= (T)0) { IntersectsEdge(1, 0, K0, C, radius, V, result); } else { T q2 = Dot(V, V); T q1 = radius * radius * q2 - dotVPerpD2 * dotVPerpD2; if (q1 >= (T)0) { T q0 = -Dot(V, delta2); IntersectsVertex(1, 0, K2, q0, q1, q2, result); } } } } } void IntersectsVertex(int32_t i0, int32_t i1, Vector2<T> const& K, T q0, T q1, T q2, Result& result) { result.intersectionType = +1; result.contactTime = (q0 - std::sqrt(q1)) / q2; result.contactPoint[i0] = K[i0]; result.contactPoint[i1] = K[i1]; } void IntersectsEdge(int32_t i0, int32_t i1, Vector2<T> const& K0, Vector2<T> const& C, T radius, Vector2<T> const& V, Result& result) { result.intersectionType = +1; result.contactTime = (K0[i0] + radius - C[i0]) / V[i0]; result.contactPoint[i0] = K0[i0]; result.contactPoint[i1] = C[i1] + result.contactTime * V[i1]; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SharedPtrCompare.h
.h
2,585
87
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <memory> // Comparison operators for std::shared_ptr objects. The type T must implement // comparison operators. You must be careful when managing containers whose // ordering is based on std::shared_ptr comparisons. The underlying objects // can change, which invalidates the container ordering. If objects do not // change while the container persists, these are safe to use. // // NOTE: std::shared_ptr<T> already has comparison operators, but these // compare pointer values instead of comparing the objects referenced by the // pointers. If a container sorted using std::shared_ptr<T> is created for // two different executions of a program, the object ordering implied by the // pointer ordering can differ. This might be undesirable for reproducibility // of results between executions. namespace gte { // sp0 == sp1 template <typename T> struct SharedPtrEQ { bool operator()(std::shared_ptr<T> const& sp0, std::shared_ptr<T> const& sp1) const { return (sp0 ? (sp1 ? *sp0 == *sp1 : false) : !sp1); } }; // sp0 != sp1 template <typename T> struct SharedPtrNEQ { bool operator()(std::shared_ptr<T> const& sp0, std::shared_ptr<T> const& sp1) const { return !SharedPtrEQ<T>()(sp0, sp1); } }; // sp0 < sp1 template <typename T> struct SharedPtrLT { bool operator()(std::shared_ptr<T> const& sp0, std::shared_ptr<T> const& sp1) const { return (sp1 ? (!sp0 || *sp0 < *sp1) : false); } }; // sp0 <= sp1 template <typename T> struct SharedPtrLTE { bool operator()(std::shared_ptr<T> const& sp0, std::shared_ptr<T> const& sp1) const { return !SharedPtrLT<T>()(sp1, sp0); } }; // sp0 > sp1 template <typename T> struct SharedPtrGT { bool operator()(std::shared_ptr<T> const& sp0, std::shared_ptr<T> const& sp1) const { return SharedPtrLT<T>()(sp1, sp0); } }; // sp0 >= sp1 template <typename T> struct SharedPtrGTE { bool operator()(std::shared_ptr<T> const& sp0, std::shared_ptr<T> const& sp1) const { return !SharedPtrLT<T>()(sp0, sp1); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ParticleSystem.h
.h
7,342
227
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector.h> #include <vector> namespace gte { template <int32_t N, typename Real> class ParticleSystem { public: // Construction and destruction. If a particle is to be immovable, // set its mass to std::numeric_limits<Real>::max(). virtual ~ParticleSystem() = default; ParticleSystem(int32_t numParticles, Real step) : mNumParticles(numParticles), mMass(numParticles), mInvMass(numParticles), mPosition(numParticles), mVelocity(numParticles), mStep(step), mHalfStep(step / (Real)2), mSixthStep(step / (Real)6), mPTmp(numParticles), mVTmp(numParticles), mPAllTmp(numParticles), mVAllTmp(numParticles) { std::fill(mMass.begin(), mMass.end(), (Real)0); std::fill(mInvMass.begin(), mInvMass.end(), (Real)0); std::fill(mPosition.begin(), mPosition.end(), Vector<N, Real>::Zero()); std::fill(mVelocity.begin(), mVelocity.end(), Vector<N, Real>::Zero()); } // Member access. inline int32_t GetNumParticles() const { return mNumParticles; } void SetMass(int32_t i, Real mass) { if ((Real)0 < mass && mass < std::numeric_limits<Real>::max()) { mMass[i] = mass; mInvMass[i] = (Real)1 / mass; } else { mMass[i] = std::numeric_limits<Real>::max(); mInvMass[i] = (Real)0; } } inline void SetPosition(int32_t i, Vector<N, Real> const& position) { mPosition[i] = position; } inline void SetVelocity(int32_t i, Vector<N, Real> const& velocity) { mVelocity[i] = velocity; } void SetStep(Real step) { mStep = step; mHalfStep = mStep / (Real)2; mSixthStep = mStep / (Real)6; } inline Real const& GetMass(int32_t i) const { return mMass[i]; } inline Vector<N, Real> const& GetPosition(int32_t i) const { return mPosition[i]; } inline Vector<N, Real> const& GetVelocity(int32_t i) const { return mVelocity[i]; } inline Real GetStep() const { return mStep; } // Update the particle positions based on current time and particle // state. The Acceleration(...) function is called in this update // for each particle. This function is virtual so that derived // classes can perform pre-update and/or post-update semantics. virtual void Update(Real time) { // Runge-Kutta fourth-order solver. Real halfTime = time + mHalfStep; Real fullTime = time + mStep; // Compute the first step. int32_t i; for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPAllTmp[i].d1 = mVelocity[i]; mVAllTmp[i].d1 = Acceleration(i, time, mPosition, mVelocity); } } for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPTmp[i] = mPosition[i] + mHalfStep * mPAllTmp[i].d1; mVTmp[i] = mVelocity[i] + mHalfStep * mVAllTmp[i].d1; } else { mPTmp[i] = mPosition[i]; mVTmp[i].MakeZero(); } } // Compute the second step. for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPAllTmp[i].d2 = mVTmp[i]; mVAllTmp[i].d2 = Acceleration(i, halfTime, mPTmp, mVTmp); } } for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPTmp[i] = mPosition[i] + mHalfStep * mPAllTmp[i].d2; mVTmp[i] = mVelocity[i] + mHalfStep * mVAllTmp[i].d2; } else { mPTmp[i] = mPosition[i]; mVTmp[i].MakeZero(); } } // Compute the third step. for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPAllTmp[i].d3 = mVTmp[i]; mVAllTmp[i].d3 = Acceleration(i, halfTime, mPTmp, mVTmp); } } for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPTmp[i] = mPosition[i] + mStep * mPAllTmp[i].d3; mVTmp[i] = mVelocity[i] + mStep * mVAllTmp[i].d3; } else { mPTmp[i] = mPosition[i]; mVTmp[i].MakeZero(); } } // Compute the fourth step. for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPAllTmp[i].d4 = mVTmp[i]; mVAllTmp[i].d4 = Acceleration(i, fullTime, mPTmp, mVTmp); } } for (i = 0; i < mNumParticles; ++i) { if (mInvMass[i] > (Real)0) { mPosition[i] += mSixthStep * (mPAllTmp[i].d1 + (Real)2 * (mPAllTmp[i].d2 + mPAllTmp[i].d3) + mPAllTmp[i].d4); mVelocity[i] += mSixthStep * (mVAllTmp[i].d1 + (Real)2 * (mVAllTmp[i].d2 + mVAllTmp[i].d3) + mVAllTmp[i].d4); } } } protected: // Callback for acceleration (ODE solver uses x" = F/m) applied to // particle i. The positions and velocities are not necessarily // mPosition and mVelocity, because the ODE solver evaluates the // impulse function at intermediate positions. virtual Vector<N, Real> Acceleration(int32_t i, Real time, std::vector<Vector<N, Real>> const& position, std::vector<Vector<N, Real>> const& velocity) = 0; int32_t mNumParticles; std::vector<Real> mMass, mInvMass; std::vector<Vector<N, Real>> mPosition, mVelocity; Real mStep, mHalfStep, mSixthStep; // Temporary storage for the Runge-Kutta differential equation solver. struct Temporary { Vector<N, Real> d1, d2, d3, d4; }; std::vector<Vector<N, Real>> mPTmp, mVTmp; std::vector<Temporary> mPAllTmp, mVAllTmp; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Polynomial1.h
.h
18,508
599
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <algorithm> #include <initializer_list> #include <vector> namespace gte { template <typename Real> class Polynomial1 { public: // Construction and destruction. The first constructor creates a // polynomial of the specified degree but sets all coefficients to // zero (to ensure initialization). You are responsible for setting // the coefficients, presumably with the degree-term set to a nonzero // number. In the second constructor, the degree is the number of // initializers plus 1, but then adjusted so that coefficient[degree] // is not zero (unless all initializer values are zero). Polynomial1(uint32_t degree = 0) : mCoefficient(static_cast<size_t>(degree) + 1, (Real)0) { } Polynomial1(std::initializer_list<Real> values) { // C++ 11 will call the default constructor for // Polynomial1<Real> p{}, so it is guaranteed that // values.size() > 0. mCoefficient.resize(values.size()); std::copy(values.begin(), values.end(), mCoefficient.begin()); EliminateLeadingZeros(); } // Support for partial construction, where the default constructor is // used when the degree is not yet known. The coefficients are // uninitialized. void SetDegree(uint32_t degree) { mCoefficient.resize(static_cast<size_t>(degree) + 1); } // Set all coefficients to the specified value. void SetCoefficients(Real value) { std::fill(mCoefficient.begin(), mCoefficient.end(), value); } // Member access. inline uint32_t GetDegree() const { // By design, mCoefficient.size() > 0. return static_cast<uint32_t>(mCoefficient.size() - 1); } inline Real const& operator[](uint32_t i) const { return mCoefficient[i]; } inline Real& operator[](uint32_t i) { return mCoefficient[i]; } // Comparisons. inline bool operator==(Polynomial1<Real> const& p) const { return mCoefficient == p.mCoefficient; } inline bool operator!=(Polynomial1<Real> const& p) const { return mCoefficient != p.mCoefficient; } inline bool operator< (Polynomial1<Real> const& p) const { return mCoefficient < p.mCoefficient; } inline bool operator<=(Polynomial1<Real> const& p) const { return mCoefficient <= p.mCoefficient; } inline bool operator> (Polynomial1<Real> const& p) const { return mCoefficient > p.mCoefficient; } inline bool operator>=(Polynomial1<Real> const& p) const { return mCoefficient >= p.mCoefficient; } // Evaluate the polynomial. If the polynomial is invalid, the // function returns zero. Real operator()(Real t) const { int32_t i = static_cast<int32_t>(mCoefficient.size()); Real result = mCoefficient[--i]; for (--i; i >= 0; --i) { result *= t; result += mCoefficient[i]; } return result; } // Compute the derivative of the polynomial. Polynomial1 GetDerivative() const { uint32_t const degree = GetDegree(); if (degree > 0) { Polynomial1 result(degree - 1); for (uint32_t i0 = 0, i1 = 1; i0 < degree; ++i0, ++i1) { result.mCoefficient[i0] = mCoefficient[i1] * (Real)i1; } return result; } else { Polynomial1 result(0); result[0] = (Real)0; return result; } } // Inversion (invpoly[i] = poly[degree-i] for 0 <= i <= degree). Polynomial1 GetInversion() const { uint32_t const degree = GetDegree(); Polynomial1 result(degree); for (uint32_t i = 0; i <= degree; ++i) { result.mCoefficient[i] = mCoefficient[degree - i]; } return result; } // Tranlation. If 'this' is p(t}, return p(t-t0). Polynomial1 GetTranslation(Real t0) const { Polynomial1<Real> factor{ -t0, (Real)1 }; // f(t) = t - t0 uint32_t const degree = GetDegree(); Polynomial1 result{ mCoefficient[degree] }; for (uint32_t i = 1, j = degree - 1; i <= degree; ++i, --j) { result = mCoefficient[j] + factor * result; } return result; } // Eliminate any leading zeros in the polynomial, except in the case // the degree is 0 and the coefficient is 0. The elimination is // necessary when arithmetic operations cause a decrease in the degree // of the result. For example, (1 + x + x^2) + (1 + 2*x - x^2) = // (2 + 3*x). The inputs both have degree 2, so the result is created // with degree 2. After the addition we find that the degree is in // fact 1 and resize the array of coefficients. This function is // called internally by the arithmetic operators, but it is exposed in // the public interface in case you need it for your own purposes. void EliminateLeadingZeros() { size_t size = mCoefficient.size(); if (size > 1) { Real const zero = (Real)0; int32_t leading; for (leading = static_cast<int32_t>(size) - 1; leading > 0; --leading) { if (mCoefficient[leading] != zero) { break; } } mCoefficient.resize(++leading); } } // If 'this' is P(t) and the divisor is D(t) with // degree(P) >= degree(D), then P(t) = Q(t)*D(t)+R(t) where Q(t) is // the quotient with degree(Q) = degree(P) - degree(D) and R(t) is the // remainder with degree(R) < degree(D). If this routine is called // with degree(P) < degree(D), then Q = 0 and R = P are returned. void Divide(Polynomial1 const& divisor, Polynomial1& quotient, Polynomial1& remainder) const { Real const zero = (Real)0; int32_t divisorDegree = static_cast<int32_t>(divisor.GetDegree()); int32_t quotientDegree = static_cast<int32_t>(GetDegree()) - divisorDegree; if (quotientDegree >= 0) { quotient.SetDegree(quotientDegree); // Temporary storage for the remainder. Polynomial1 tmp = *this; // Do the division using the Euclidean algorithm. Real inv = ((Real)1) / divisor[divisorDegree]; for (int32_t i = quotientDegree; i >= 0; --i) { int32_t j = divisorDegree + i; quotient[i] = inv * tmp[j]; for (j--; j >= i; j--) { tmp[j] -= quotient[i] * divisor[j - i]; } } // Calculate the correct degree for the remainder. if (divisorDegree >= 1) { int32_t remainderDegree = divisorDegree - 1; while (remainderDegree > 0 && tmp[remainderDegree] == zero) { --remainderDegree; } remainder.SetDegree(remainderDegree); for (int32_t i = 0; i <= remainderDegree; ++i) { remainder[i] = tmp[i]; } } else { remainder.SetDegree(0); remainder[0] = zero; } } else { quotient.SetDegree(0); quotient[0] = zero; remainder = *this; } } // Scale the polynomial so the highest-degree term has coefficient 1. void MakeMonic() { EliminateLeadingZeros(); Real const one(1); if (mCoefficient.back() != one) { uint32_t degree = GetDegree(); Real invLeading = one / mCoefficient.back(); mCoefficient.back() = one; for (uint32_t i = 0; i < degree; ++i) { mCoefficient[i] *= invLeading; } } } protected: // The class is designed so that mCoefficient.size() >= 1. std::vector<Real> mCoefficient; }; // Compute the greatest common divisor of two polynomials. The returned // polynomial has leading coefficient 1 (except when zero-valued // polynomials are passed to the function. template <typename Real> Polynomial1<Real> GreatestCommonDivisor(Polynomial1<Real> const& p0, Polynomial1<Real> const& p1) { // The numerator should be the polynomial of larger degree. Polynomial1<Real> a, b; if (p0.GetDegree() >= p1.GetDegree()) { a = p0; b = p1; } else { a = p1; b = p0; } Polynomial1<Real> const zero{ (Real)0 }; if (a == zero || b == zero) { return (a != zero ? a : zero); } // Make the polynomials monic to keep the coefficients reasonable size // when computing with floating-point Real. a.MakeMonic(); b.MakeMonic(); Polynomial1<Real> q, r; for (;;) { a.Divide(b, q, r); if (r != zero) { // a = q * b + r, so gcd(a,b) = gcd(b, r) a = b; b = r; b.MakeMonic(); } else { b.MakeMonic(); break; } } return b; } // Factor f = factor[0]*factor[1]^2*factor[2]^3*...*factor[n-1]^n // according to the square-free factorization algorithm // https://en.wikipedia.org/wiki/Square-free_polynomial template <typename Real> void SquareFreeFactorization(Polynomial1<Real> const& f, std::vector<Polynomial1<Real>>& factors) { // In the call to Divide(...), we know that the divisor exactly // divides the numerator, so r = 0 after all such calls. Polynomial1<Real> fder = f.GetDerivative(); Polynomial1<Real> a, b, c, d, q, r; a = GreatestCommonDivisor(f, fder); f.Divide(a, b, r); // b = f / a fder.Divide(a, c, r); // c = fder / a d = c - b.GetDerivative(); do { a = GreatestCommonDivisor(b, d); factors.emplace_back(a); b.Divide(a, q, r); // q = b / a b = std::move(q); d.Divide(a, c, r); // c = d / a d = c - b.GetDerivative(); } while (b.GetDegree() > 0); } // Unary operations. template <typename Real> Polynomial1<Real> operator+(Polynomial1<Real> const& p) { return p; } template <typename Real> Polynomial1<Real> operator-(Polynomial1<Real> const& p) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); for (uint32_t i = 0; i <= degree; ++i) { result[i] = -p[i]; } return result; } // Linear-algebraic operations. template <typename Real> Polynomial1<Real> operator+(Polynomial1<Real> const& p0, Polynomial1<Real> const& p1) { uint32_t const p0Degree = p0.GetDegree(), p1Degree = p1.GetDegree(); uint32_t i; if (p0Degree >= p1Degree) { Polynomial1<Real> result(p0Degree); for (i = 0; i <= p1Degree; ++i) { result[i] = p0[i] + p1[i]; } for (/**/; i <= p0Degree; ++i) { result[i] = p0[i]; } result.EliminateLeadingZeros(); return result; } else { Polynomial1<Real> result(p1Degree); for (i = 0; i <= p0Degree; ++i) { result[i] = p0[i] + p1[i]; } for (/**/; i <= p1Degree; ++i) { result[i] = p1[i]; } result.EliminateLeadingZeros(); return result; } } template <typename Real> Polynomial1<Real> operator-(Polynomial1<Real> const& p0, Polynomial1<Real> const& p1) { uint32_t const p0Degree = p0.GetDegree(), p1Degree = p1.GetDegree(); uint32_t i; if (p0Degree >= p1Degree) { Polynomial1<Real> result(p0Degree); for (i = 0; i <= p1Degree; ++i) { result[i] = p0[i] - p1[i]; } for (/**/; i <= p0Degree; ++i) { result[i] = p0[i]; } result.EliminateLeadingZeros(); return result; } else { Polynomial1<Real> result(p1Degree); for (i = 0; i <= p0Degree; ++i) { result[i] = p0[i] - p1[i]; } for (/**/; i <= p1Degree; ++i) { result[i] = -p1[i]; } result.EliminateLeadingZeros(); return result; } } template <typename Real> Polynomial1<Real> operator*(Polynomial1<Real> const& p0, Polynomial1<Real> const& p1) { uint32_t const p0Degree = p0.GetDegree(), p1Degree = p1.GetDegree(); Polynomial1<Real> result(p0Degree + p1Degree); result.SetCoefficients((Real)0); for (uint32_t i0 = 0; i0 <= p0Degree; ++i0) { for (uint32_t i1 = 0; i1 <= p1Degree; ++i1) { result[i0 + i1] += p0[i0] * p1[i1]; } } return result; } template <typename Real> Polynomial1<Real> operator+(Polynomial1<Real> const& p, Real scalar) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); result[0] = p[0] + scalar; for (uint32_t i = 1; i <= degree; ++i) { result[i] = p[i]; } return result; } template <typename Real> Polynomial1<Real> operator+(Real scalar, Polynomial1<Real> const& p) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); result[0] = p[0] + scalar; for (uint32_t i = 1; i <= degree; ++i) { result[i] = p[i]; } return result; } template <typename Real> Polynomial1<Real> operator-(Polynomial1<Real> const& p, Real scalar) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); result[0] = p[0] - scalar; for (uint32_t i = 1; i <= degree; ++i) { result[i] = p[i]; } return result; } template <typename Real> Polynomial1<Real> operator-(Real scalar, Polynomial1<Real> const& p) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); result[0] = scalar - p[0]; for (uint32_t i = 1; i <= degree; ++i) { result[i] = -p[i]; } return result; } template <typename Real> Polynomial1<Real> operator*(Polynomial1<Real> const& p, Real scalar) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); for (uint32_t i = 0; i <= degree; ++i) { result[i] = scalar * p[i]; } return result; } template <typename Real> Polynomial1<Real> operator*(Real scalar, Polynomial1<Real> const& p) { uint32_t const degree = p.GetDegree(); Polynomial1<Real> result(degree); for (uint32_t i = 0; i <= degree; ++i) { result[i] = scalar * p[i]; } return result; } template <typename Real> Polynomial1<Real> operator/(Polynomial1<Real> const& p, Real scalar) { LogAssert(scalar != (Real)0, "Division by zero."); uint32_t const degree = p.GetDegree(); Real invScalar = (Real)1 / scalar; Polynomial1<Real> result(degree); for (uint32_t i = 0; i <= degree; ++i) { result[i] = invScalar * p[i]; } return result; } template <typename Real> Polynomial1<Real>& operator+=(Polynomial1<Real>& p0, Polynomial1<Real> const& p1) { p0 = p0 + p1; return p0; } template <typename Real> Polynomial1<Real>& operator-=(Polynomial1<Real>& p0, Polynomial1<Real> const& p1) { p0 = p0 - p1; return p0; } template <typename Real> Polynomial1<Real>& operator*=(Polynomial1<Real>& p0, Polynomial1<Real> const& p1) { p0 = p0 * p1; return p0; } template <typename Real> Polynomial1<Real>& operator+=(Polynomial1<Real>& p, Real scalar) { p[0] += scalar; return p; } template <typename Real> Polynomial1<Real>& operator-=(Polynomial1<Real>& p, Real scalar) { p[0] -= scalar; return p; } template <typename Real> Polynomial1<Real>& operator*=(Polynomial1<Real>& p, Real scalar) { p = p * scalar; return p; } template <typename Real> Polynomial1<Real> & operator/=(Polynomial1<Real>& p, Real scalar) { p = p / scalar; return p; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay2Circle2.h
.h
2,840
95
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine2Circle2.h> #include <Mathematics/Ray.h> // The queries consider the circle to be a solid (disk). namespace gte { template <typename T> class TIQuery<T, Ray2<T>, Circle2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Ray2<T> const& ray, Circle2<T> const& circle) { Result result{}; FIQuery<T, Ray2<T>, Circle2<T>> rcQuery{}; result.intersect = rcQuery(ray, circle).intersect; return result; } }; template <typename T> class FIQuery<T, Ray2<T>, Circle2<T>> : public FIQuery<T, Line2<T>, Circle2<T>> { public: struct Result : public FIQuery<T, Line2<T>, Circle2<T>>::Result { Result() : FIQuery<T, Line2<T>, Circle2<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray2<T> const& ray, Circle2<T> const& circle) { Result result{}; DoQuery(ray.origin, ray.direction, circle, result); for (int32_t i = 0; i < result.numIntersections; ++i) { result.point[i] = ray.origin + result.parameter[i] * ray.direction; } return result; } protected: void DoQuery(Vector2<T> const& rayOrigin, Vector2<T> const& rayDirection, Circle2<T> const& circle, Result& result) { FIQuery<T, Line2<T>, Circle2<T>>::DoQuery(rayOrigin, rayDirection, circle, result); if (result.intersect) { // The line containing the ray intersects the disk; the // t-interval is [t0,t1]. The ray intersects the disk as long // as [t0,t1] overlaps the ray t-interval [0,+infinity). std::array<T, 2> rayInterval = { (T)0, std::numeric_limits<T>::max() }; FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; auto iiResult = iiQuery(result.parameter, rayInterval); result.intersect = iiResult.intersect; result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SWInterval.h
.h
13,585
471
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <array> // The SWInterval [e0,e1] must satisfy e0 <= e1. Expose this define to trap // invalid construction where e0 > e1. #define GTE_THROW_ON_INVALID_SWINTERVAL namespace gte { // The T must be 'float' or 'double'. template <typename T> class SWInterval { public: // Convenient constants. static T constexpr zero = 0; static T constexpr one = 1; static T constexpr max = std::numeric_limits<T>::max(); static T constexpr inf = std::numeric_limits<T>::infinity(); // Construction. This is the only way to create an interval. All such // intervals are immutable once created. The constructor SWInterval(T) // is used to create the degenerate interval [e,e]. SWInterval() : mEndpoints{ static_cast<T>(0), static_cast<T>(0) } { static_assert(std::is_floating_point<T>::value, "Invalid type."); } SWInterval(SWInterval const& other) : mEndpoints(other.mEndpoints) { static_assert(std::is_floating_point<T>::value, "Invalid type."); } SWInterval(T e) : mEndpoints{ e, e } { static_assert(std::is_floating_point<T>::value, "Invalid type."); } SWInterval(T e0, T e1) : mEndpoints{ e0, e1 } { static_assert(std::is_floating_point<T>::value, "Invalid type."); #if defined(GTE_THROW_ON_INVALID_SWINTERVAL) LogAssert(mEndpoints[0] <= mEndpoints[1], "Invalid SWInterval."); #endif } SWInterval(std::array<T, 2> const& endpoint) : mEndpoints(endpoint) { static_assert(std::is_floating_point<T>::value, "Invalid type."); #if defined(GTE_THROW_ON_INVALID_SWINTERVAL) LogAssert(mEndpoints[0] <= mEndpoints[1], "Invalid SWInterval."); #endif } SWInterval& operator=(SWInterval const& other) { static_assert(std::is_floating_point<T>::value, "Invalid type."); mEndpoints = other.mEndpoints; return *this; } // Member access. It is only possible to read the endpoints. You // cannot modify the endpoints outside the arithmetic operations. inline T operator[](size_t i) const { return mEndpoints[i]; } inline std::array<T, 2> GetEndpoints() const { return mEndpoints; } // Arithmetic operations to compute intervals at the leaf nodes of // an expression tree. Such nodes correspond to the raw floating-point // variables of the expression. The non-class operators defined after // the class definition are used to compute intervals at the interior // nodes of the expression tree. inline static SWInterval Add(T u, T v) { SWInterval w; T add = u + v; w.mEndpoints[0] = std::nextafter(add, -max); w.mEndpoints[1] = std::nextafter(add, +max); return w; } inline static SWInterval Sub(T u, T v) { SWInterval w; T sub = u - v; w.mEndpoints[0] = std::nextafter(sub, -max); w.mEndpoints[1] = std::nextafter(sub, +max); return w; } inline static SWInterval Mul(T u, T v) { SWInterval w; T mul = u * v; w.mEndpoints[0] = std::nextafter(mul, -max); w.mEndpoints[1] = std::nextafter(mul, +max); return w; } inline static SWInterval Div(T u, T v) { if (v != zero) { SWInterval w; T div = u / v; w.mEndpoints[0] = std::nextafter(div, -max); w.mEndpoints[1] = std::nextafter(div, +max); return w; } else { // Division by zero does not lead to a determinate SWInterval. // Return the entire set of real numbers. return Reals(); } } private: std::array<T, 2> mEndpoints; public: // FOR INTERNAL USE ONLY. These are used by the non-class operators // defined after the class definition. inline static SWInterval Add(T u0, T u1, T v0, T v1) { SWInterval w; w.mEndpoints[0] = std::nextafter(u0 + v0, -max); w.mEndpoints[1] = std::nextafter(u1 + v1, +max); return w; } inline static SWInterval Sub(T u0, T u1, T v0, T v1) { SWInterval w; w.mEndpoints[0] = std::nextafter(u0 - v1, -max); w.mEndpoints[1] = std::nextafter(u1 - v0, +max); return w; } inline static SWInterval Mul(T u0, T u1, T v0, T v1) { SWInterval w; w.mEndpoints[0] = std::nextafter(u0 * v0, -max); w.mEndpoints[1] = std::nextafter(u1 * v1, +max); return w; } inline static SWInterval Mul2(T u0, T u1, T v0, T v1) { T u0mv1 = std::nextafter(u0 * v1, -max); T u1mv0 = std::nextafter(u1 * v0, -max); T u0mv0 = std::nextafter(u0 * v0, +max); T u1mv1 = std::nextafter(u1 * v1, +max); return SWInterval<T>(std::min(u0mv1, u1mv0), std::max(u0mv0, u1mv1)); } inline static SWInterval Div(T u0, T u1, T v0, T v1) { SWInterval w; w.mEndpoints[0] = std::nextafter(u0 / v1, -max); w.mEndpoints[1] = std::nextafter(u1 / v0, +max); return w; } inline static SWInterval Reciprocal(T v0, T v1) { SWInterval w; w.mEndpoints[0] = std::nextafter(one / v1, -max); w.mEndpoints[1] = std::nextafter(one / v0, +max); return w; } inline static SWInterval ReciprocalDown(T v) { T recpv = std::nextafter(one / v, -max); return SWInterval<T>(recpv, +inf); } inline static SWInterval ReciprocalUp(T v) { T recpv = std::nextafter(one / v, +max); return SWInterval<T>(-inf, recpv); } inline static SWInterval Reals() { return SWInterval(-inf, +inf); } }; // Unary operations. Negation of [e0,e1] produces [-e1,-e0]. This // operation needs to be supported in the sense of negating a // "number" in an arithmetic expression. template <typename T> SWInterval<T> operator+(SWInterval<T> const& u) { return u; } template <typename T> SWInterval<T> operator-(SWInterval<T> const& u) { return SWInterval<T>(-u[1], -u[0]); } // Addition operations. template <typename T> SWInterval<T> operator+(T u, SWInterval<T> const& v) { return SWInterval<T>::Add(u, u, v[0], v[1]); } template <typename T> SWInterval<T> operator+(SWInterval<T> const& u, T v) { return SWInterval<T>::Add(u[0], u[1], v, v); } template <typename T> SWInterval<T> operator+(SWInterval<T> const& u, SWInterval<T> const& v) { return SWInterval<T>::Add(u[0], u[1], v[0], v[1]); } template <typename T> SWInterval<T>& operator+=(SWInterval<T>& u, T v) { u = u + v; return u; } template <typename T> SWInterval<T>& operator+=(SWInterval<T>& u, SWInterval<T> const& v) { u = u + v; return u; } // Subtraction operations. template <typename T> SWInterval<T> operator-(T u, SWInterval<T> const& v) { return SWInterval<T>::Sub(u, u, v[0], v[1]); } template <typename T> SWInterval<T> operator-(SWInterval<T> const& u, T v) { return SWInterval<T>::Sub(u[0], u[1], v, v); } template <typename T> SWInterval<T> operator-(SWInterval<T> const& u, SWInterval<T> const& v) { return SWInterval<T>::Sub(u[0], u[1], v[0], v[1]); } template <typename T> SWInterval<T>& operator-=(SWInterval<T>& u, T v) { u = u - v; return u; } template <typename T> SWInterval<T>& operator-=(SWInterval<T>& u, SWInterval<T> const& v) { u = u - v; return u; } // Multiplication operations. template <typename T> SWInterval<T> operator*(T u, SWInterval<T> const& v) { if (u >= SWInterval<T>::zero) { return SWInterval<T>::Mul(u, u, v[0], v[1]); } else { return SWInterval<T>::Mul(u, u, v[1], v[0]); } } template <typename T> SWInterval<T> operator*(SWInterval<T> const& u, T v) { if (v >= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[0], u[1], v, v); } else { return SWInterval<T>::Mul(u[1], u[0], v, v); } } template <typename T> SWInterval<T> operator*(SWInterval<T> const& u, SWInterval<T> const& v) { if (u[0] >= SWInterval<T>::zero) { if (v[0] >= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[0], u[1], v[0], v[1]); } else if (v[1] <= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[1], u[0], v[0], v[1]); } else // v[0] < 0 < v[1] { return SWInterval<T>::Mul(u[1], u[1], v[0], v[1]); } } else if (u[1] <= SWInterval<T>::zero) { if (v[0] >= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[0], u[1], v[1], v[0]); } else if (v[1] <= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[1], u[0], v[1], v[0]); } else // v[0] < 0 < v[1] { return SWInterval<T>::Mul(u[0], u[0], v[1], v[0]); } } else // u[0] < 0 < u[1] { if (v[0] >= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[0], u[1], v[1], v[1]); } else if (v[1] <= SWInterval<T>::zero) { return SWInterval<T>::Mul(u[1], u[0], v[0], v[0]); } else // v[0] < 0 < v[1] { return SWInterval<T>::Mul2(u[0], u[1], v[0], v[1]); } } } template <typename T> SWInterval<T>& operator*=(SWInterval<T>& u, T v) { u = u * v; return u; } template <typename T> SWInterval<T>& operator*=(SWInterval<T>& u, SWInterval<T> const& v) { u = u * v; return u; } // Division operations. If the divisor SWInterval is [v0,v1] with // v0 < 0 < v1, then the returned SWInterval is (-inf,+inf) instead of // Union((-inf,1/v0),(1/v1,+inf)). An application should try to avoid // this case by branching based on [v0,0] and [0,v1]. template <typename T> SWInterval<T> operator/(T u, SWInterval<T> const& v) { if (v[0] > SWInterval<T>::zero || v[1] < SWInterval<T>::zero) { return u * SWInterval<T>::Reciprocal(v[0], v[1]); } else { if (v[0] == SWInterval<T>::zero) { return u * SWInterval<T>::ReciprocalDown(v[1]); } else if (v[1] == SWInterval<T>::zero) { return u * SWInterval<T>::ReciprocalUp(v[0]); } else // v[0] < 0 < v[1] { return SWInterval<T>::Reals(); } } } template <typename T> SWInterval<T> operator/(SWInterval<T> const& u, T v) { if (v > SWInterval<T>::zero) { return SWInterval<T>::Div(u[0], u[1], v, v); } else if (v < SWInterval<T>::zero) { return SWInterval<T>::Div(u[1], u[0], v, v); } else // v = 0 { return SWInterval<T>::Reals(); } } template <typename T> SWInterval<T> operator/(SWInterval<T> const& u, SWInterval<T> const& v) { if (v[0] > SWInterval<T>::zero || v[1] < SWInterval<T>::zero) { return u * SWInterval<T>::Reciprocal(v[0], v[1]); } else { if (v[0] == SWInterval<T>::zero) { return u * SWInterval<T>::ReciprocalDown(v[1]); } else if (v[1] == SWInterval<T>::zero) { return u * SWInterval<T>::ReciprocalUp(v[0]); } else // v[0] < 0 < v[1] { return SWInterval<T>::Reals(); } } } template <typename T> SWInterval<T>& operator/=(SWInterval<T>& u, T v) { u = u / v; return u; } template <typename T> SWInterval<T>& operator/=(SWInterval<T>& u, SWInterval<T> const& v) { u = u / v; return u; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprEllipseByArcs.h
.h
4,464
120
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ContScribeCircle2.h> #include <vector> // The ellipse is (x/a)^2 + (y/b)^2 = 1, but only the portion in the first // quadrant (x >= 0 and y >= 0) is approximated. Generate numArcs >= 2 arcs // by constructing points corresponding to the weighted averages of the // curvatures at the ellipse points (a,0) and (0,b). The returned input point // array has numArcs+1 elements and the returned input center and radius // arrays each have numArc elements. The arc associated with points[i] and // points[i+1] has center centers[i] and radius radii[i]. The algorithm // is described in // https://www.geometrictools.com/Documentation/ApproximateEllipse.pdf namespace gte { // The function returns 'true' when the approximation succeeded, in which // case the output arrays are nonempty. If the 'numArcs' is smaller than // 2 or a == b or one of the calls to Circumscribe fails, the function // returns 'false'. template <typename Real> bool ApproximateEllipseByArcs(Real a, Real b, int32_t numArcs, std::vector<Vector2<Real>>& points, std::vector<Vector2<Real>>& centers, std::vector<Real>& radii) { if (numArcs < 2 || a == b) { // At least 2 arcs are required. The ellipse cannot already be a // circle. points.clear(); centers.clear(); radii.clear(); return false; } points.resize(static_cast<size_t>(numArcs) + 1); centers.resize(numArcs); radii.resize(numArcs); // Compute intermediate ellipse quantities. Real a2 = a * a, b2 = b * b, ab = a * b; Real invB2mA2 = (Real)1 / (b2 - a2); // Compute the endpoints of the ellipse in the first quadrant. The // points are generated in counterclockwise order. points[0] = { a, (Real)0 }; points[numArcs] = { (Real)0, b }; // Compute the curvature at the endpoints. These are used when // computing the arcs. Real curv0 = a / b2; Real curv1 = b / a2; // Select the ellipse points based on curvature properties. Real invNumArcs = (Real)1 / numArcs; for (int32_t i = 1; i < numArcs; ++i) { // The curvature at a new point is a weighted average of curvature // at the endpoints. Real weight1 = static_cast<Real>(i) * invNumArcs; Real weight0 = (Real)1 - weight1; Real curv = weight0 * curv0 + weight1 * curv1; // Compute point having this curvature. Real tmp = std::pow(ab / curv, (Real)2 / (Real)3); points[i][0] = a * std::sqrt(std::fabs((tmp - a2) * invB2mA2)); points[i][1] = b * std::sqrt(std::fabs((tmp - b2) * invB2mA2)); } // Compute the arc at (a,0). Circle2<Real> circle; Vector2<Real> const& p0 = points[0]; Vector2<Real> const& p1 = points[1]; if (!Circumscribe(Vector2<Real>{ p1[0], -p1[1] }, p0, p1, circle)) { // This should not happen for the arc-fitting algorithm. points.clear(); centers.clear(); radii.clear(); return false; } centers[0] = circle.center; radii[0] = circle.radius; // Compute arc at (0,b). int32_t last = numArcs - 1; Vector2<Real> const& pNm1 = points[last]; Vector2<Real> const& pN = points[numArcs]; if (!Circumscribe(Vector2<Real>{ -pNm1[0], pNm1[1] }, pN, pNm1, circle)) { // This should not happen for the arc-fitting algorithm. points.clear(); centers.clear(); radii.clear(); return false; } centers[last] = circle.center; radii[last] = circle.radius; // Compute arcs at intermediate points between (a,0) and (0,b). for (int32_t iM = 0, i = 1, iP = 2; i < last; ++iM, ++i, ++iP) { Circumscribe(points[iM], points[i], points[iP], circle); centers[i] = circle.center; radii[i] = circle.radius; } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSplineSurface.h
.h
6,764
174
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/BasisFunction.h> #include <Mathematics/ParametricSurface.h> namespace gte { template <int32_t N, typename Real> class BSplineSurface : public ParametricSurface<N, Real> { public: // Construction. If the input controls is non-null, a copy is made of // the controls. To defer setting the control points, pass a null // pointer and later access the control points via GetControls() or // SetControl() member functions. The input 'controls' must be stored // in row-major order, control[i0 + numControls0*i1]. As a 2D array, // this corresponds to control2D[i1][i0]. BSplineSurface(BasisFunctionInput<Real> const input[2], Vector<N, Real> const* controls) : ParametricSurface<N, Real>((Real)0, (Real)1, (Real)0, (Real)1, true) { for (int32_t i = 0; i < 2; ++i) { mNumControls[i] = input[i].numControls; mBasisFunction[i].Create(input[i]); } // The mBasisFunction stores the domain but so does // ParametricCurve. this->mUMin = mBasisFunction[0].GetMinDomain(); this->mUMax = mBasisFunction[0].GetMaxDomain(); this->mVMin = mBasisFunction[1].GetMinDomain(); this->mVMax = mBasisFunction[1].GetMaxDomain(); // The replication of control points for periodic splines is // avoided by wrapping the i-loop index in Evaluate. int32_t numControls = mNumControls[0] * mNumControls[1]; mControls.resize(numControls); if (controls) { std::copy(controls, controls + numControls, mControls.begin()); } else { Vector<N, Real> zero{ (Real)0 }; std::fill(mControls.begin(), mControls.end(), zero); } this->mConstructed = true; } // Member access. The index 'dim' must be in {0,1}. inline BasisFunction<Real> const& GetBasisFunction(int32_t dim) const { return mBasisFunction[dim]; } inline int32_t GetNumControls(int32_t dim) const { return mNumControls[dim]; } inline Vector<N, Real>* GetControls() { return mControls.data(); } inline Vector<N, Real> const* GetControls() const { return mControls.data(); } void SetControl(int32_t i0, int32_t i1, Vector<N, Real> const& control) { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { mControls[i0 + static_cast<size_t>(mNumControls[0]) * i1] = control; } } Vector<N, Real> const& GetControl(int32_t i0, int32_t i1) const { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { return mControls[i0 + static_cast<size_t>(mNumControls[0]) * i1]; } else { return mControls[0]; } } // Evaluation of the surface. The function supports derivative // calculation through order 2; that is, order <= 2 is required. If // you want only the position, pass in order of 0. If you want the // position and first-order derivatives, pass in order of 1, and so // on. The output array 'jet' must have enough storage to support the // maximum order. The values are ordered as: position X; first-order // derivatives dX/du, dX/dv; second-order derivatives d2X/du2, // d2X/dudv, d2X/dv2. virtual void Evaluate(Real u, Real v, uint32_t order, Vector<N, Real>* jet) const override { uint32_t const supOrder = ParametricSurface<N, Real>::SUP_ORDER; if (!this->mConstructed || order >= supOrder) { // Return a zero-valued jet for invalid state. for (uint32_t i = 0; i < supOrder; ++i) { jet[i].MakeZero(); } return; } int32_t iumin, iumax, ivmin, ivmax; mBasisFunction[0].Evaluate(u, order, iumin, iumax); mBasisFunction[1].Evaluate(v, order, ivmin, ivmax); // Compute position. jet[0] = Compute(0, 0, iumin, iumax, ivmin, ivmax); if (order >= 1) { // Compute first-order derivatives. jet[1] = Compute(1, 0, iumin, iumax, ivmin, ivmax); jet[2] = Compute(0, 1, iumin, iumax, ivmin, ivmax); if (order >= 2) { // Compute second-order derivatives. jet[3] = Compute(2, 0, iumin, iumax, ivmin, ivmax); jet[4] = Compute(1, 1, iumin, iumax, ivmin, ivmax); jet[5] = Compute(0, 2, iumin, iumax, ivmin, ivmax); } } } private: // Support for Evaluate(...). Vector<N, Real> Compute(uint32_t uOrder, uint32_t vOrder, int32_t iumin, int32_t iumax, int32_t ivmin, int32_t ivmax) const { // The j*-indices introduce a tiny amount of overhead in order to // handle both aperiodic and periodic splines. For aperiodic // splines, j* = i* always. int32_t const numControls0 = mNumControls[0]; int32_t const numControls1 = mNumControls[1]; Vector<N, Real> result; result.MakeZero(); for (int32_t iv = ivmin; iv <= ivmax; ++iv) { Real tmpv = mBasisFunction[1].GetValue(vOrder, iv); int32_t jv = (iv >= numControls1 ? iv - numControls1 : iv); for (int32_t iu = iumin; iu <= iumax; ++iu) { Real tmpu = mBasisFunction[0].GetValue(uOrder, iu); int32_t ju = (iu >= numControls0 ? iu - numControls0 : iu); result += (tmpu * tmpv) * mControls[ju + static_cast<size_t>(numControls0) * jv]; } } return result; } std::array<BasisFunction<Real>, 2> mBasisFunction; std::array<int32_t, 2> mNumControls; std::vector<Vector<N, Real>> mControls; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox2Cone2.h
.h
4,396
112
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrRay2OrientedBox2.h> #include <Mathematics/Cone.h> // The queries consider the box and cone to be solids. // // Define V = cone.ray.origin, D = cone.ray.direction, and cs = cone.cosAngle. // Define C = box.center, U0 = box.axis[0], U1 = box.axis[1], // e0 = box.extent[0], and e1 = box.extent[1]. A box point is // P = C + x*U0 + y*U1 where |x| <= e0 and |y| <= e1. Define the function // F(P) = Dot(D, (P-V)/Length(P-V)) = F(x,y) // = Dot(D, (x*U0 + y*U1 + (C-V))/|x*U0 + y*U1 + (C-V)| // = (a0*x + a1*y + a2)/(x^2 + y^2 + 2*b0*x + 2*b1*y + b2)^{1/2} // The function has an essential singularity when P = V. The box intersects // the cone (with positive-area overlap) when at least one of the four box // corners is strictly inside the cone. It is necessary that the numerator // of F(P) be positive at such a corner. The (interior of the) solid cone // is defined by the quadratic inequality // (Dot(D,P-V))^2 > |P-V|^2*(cone.cosAngle)^2 // This inequality is inexpensive to compute. In summary, overlap occurs // when there is a box corner P for which // F(P) > 0 and (Dot(D,P-V))^2 > |P-V|^2*(cone.cosAngle)^2 namespace gte { template <typename T> class TIQuery<T, OrientedBox<2, T>, Cone<2, T>> { public: struct Result { Result() : intersect(false) { } // The value of 'intersect' is true when there is a box point that // is strictly inside the cone. If the box just touches the cone // from the outside, an intersection is not reported, which // supports the common operation of culling objects outside a // cone. bool intersect; }; Result operator()(OrientedBox<2, T> const& box, Cone<2, T>& cone) { Result result{}; TIQuery<T, Ray<2, T>, OrientedBox<2, T>> rbQuery; auto rbResult = rbQuery(cone.ray, box); if (rbResult.intersect) { // The cone intersects the box. result.intersect = true; return result; } // Define V = cone.ray.origin, D = cone.ray.direction, and // cs = cone.cosAngle. Define C = box.center, U0 = box.axis[0], // U1 = box.axis[1], e0 = box.extent[0], and e1 = box.extent[1]. // A box point is P = C + x*U0 + y*U1 where |x| <= e0 and // |y| <= e1. Define the function // F(x,y) = Dot(D, (P-V)/Length(P-V)) // = Dot(D, (x*U0 + y*U1 + (C-V))/|x*U0 + y*U1 + (C-V)| // = (a0*x + a1*y + a2)/(x^2 + y^2 + 2*b0*x + 2*b1*y + b2)^{1/2} // The function has an essential singularity when P = V. Vector<2, T> diff = box.center - cone.ray.origin; T a0 = Dot(cone.ray.direction, box.axis[0]); T a1 = Dot(cone.ray.direction, box.axis[1]); T a2 = Dot(cone.ray.direction, diff); T b0 = Dot(box.axis[0], diff); T b1 = Dot(box.axis[1], diff); T b2 = Dot(diff, diff); T csSqr = cone.cosAngle * cone.cosAngle; for (int32_t i1 = 0; i1 < 2; ++i1) { T sign1 = i1 * (T)2 - (T)1; T y = sign1 * box.extent[1]; for (int32_t i0 = 0; i0 < 2; ++i0) { T sign0 = i0 * (T)2 - (T)1; T x = sign0 * box.extent[0]; T fNumerator = a0 * x + a1 * y + a2; if (fNumerator > (T)0) { T dSqr = x * x + y * y + (b0 * x + b1 * y) * (T)2 + b2; T nSqr = fNumerator * fNumerator; if (nSqr > dSqr * csSqr) { result.intersect = true; return result; } } } } result.intersect = false; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContOrientedBox3.h
.h
7,418
199
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprGaussian3.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/Rotation.h> namespace gte { // Compute an oriented bounding box of the points. The box center is the // average of the points. The box axes are the eigenvectors of the // covariance matrix. template <typename Real> bool GetContainer(int32_t numPoints, Vector3<Real> const* points, OrientedBox3<Real>& box) { // Fit the points with a Gaussian distribution. ApprGaussian3<Real> fitter; if (fitter.Fit(numPoints, points)) { box = fitter.GetParameters(); // Let C be the box center and let U0, U1, and U2 be the box axes. // Each input point is of the form X = C + y0*U0 + y1*U1 + y2*U2. // The following code computes min(y0), max(y0), min(y1), max(y1), // min(y2), and max(y2). The box center is then adjusted to be // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 // + 0.5*(min(y2)+max(y2))*U2 Vector3<Real> diff = points[0] - box.center; Vector3<Real> pmin{ Dot(diff, box.axis[0]), Dot(diff, box.axis[1]), Dot(diff, box.axis[2]) }; Vector3<Real> pmax = pmin; for (int32_t i = 1; i < numPoints; ++i) { diff = points[i] - box.center; for (int32_t j = 0; j < 3; ++j) { Real dot = Dot(diff, box.axis[j]); if (dot < pmin[j]) { pmin[j] = dot; } else if (dot > pmax[j]) { pmax[j] = dot; } } } for (int32_t j = 0; j < 3; ++j) { box.center += ((Real)0.5 * (pmin[j] + pmax[j])) * box.axis[j]; box.extent[j] = (Real)0.5 * (pmax[j] - pmin[j]); } return true; } return false; } template <typename Real> bool GetContainer(std::vector<Vector3<Real>> const& points, OrientedBox3<Real>& box) { return GetContainer(static_cast<int32_t>(points.size()), points.data(), box); } // Test for containment. Let X = C + y0*U0 + y1*U1 + y2*U2 where C is the // box center and U0, U1, U2 are the orthonormal axes of the box. X is in // the box if |y_i| <= E_i for all i where E_i are the extents of the box. template <typename Real> bool InContainer(Vector3<Real> const& point, OrientedBox3<Real> const& box) { Vector3<Real> diff = point - box.center; for (int32_t i = 0; i < 3; ++i) { Real coeff = Dot(diff, box.axis[i]); if (std::fabs(coeff) > box.extent[i]) { return false; } } return true; } // Construct an oriented box that contains two other oriented boxes. The // result is not guaranteed to be the minimum volume box containing the // input boxes. template <typename Real> bool MergeContainers(OrientedBox3<Real> const& box0, OrientedBox3<Real> const& box1, OrientedBox3<Real>& merge) { // The first guess at the box center. This value will be updated // later after the input box vertices are projected onto axes // determined by an average of box axes. merge.center = (Real)0.5 * (box0.center + box1.center); // A box's axes, when viewed as the columns of a matrix, form a // rotation matrix. The input box axes are converted to quaternions. // The average quaternion is computed, then normalized to unit length. // The result is the slerp of the two input quaternions with t-value // of 1/2. The result is converted back to a rotation matrix and its // columns are selected as the merged box axes. // // TODO: When the GTL Lie Algebra code is posted, use the geodesic // path between the affine matrices formed by the box centers and // orientations. Choose t = 1/2 along that geodesic. Matrix3x3<Real> rot0, rot1; rot0.SetCol(0, box0.axis[0]); rot0.SetCol(1, box0.axis[1]); rot0.SetCol(2, box0.axis[2]); rot1.SetCol(0, box1.axis[0]); rot1.SetCol(1, box1.axis[1]); rot1.SetCol(2, box1.axis[2]); Quaternion<Real> q0 = Rotation<3, Real>(rot0); Quaternion<Real> q1 = Rotation<3, Real>(rot1); if (Dot(q0, q1) < (Real)0) { q1 = -q1; } Quaternion<Real> q = q0 + q1; Normalize(q); Matrix3x3<Real> rot = Rotation<3, Real>(q); for (int32_t j = 0; j < 3; ++j) { merge.axis[j] = rot.GetCol(j); } // Project the input box vertices onto the merged-box axes. Each axis // D[i] containing the current center C has a minimum projected value // min[i] and a maximum projected value max[i]. The corresponding end // points on the axes are C+min[i]*D[i] and C+max[i]*D[i]. The point // C is not necessarily the midpoint for any of the intervals. The // actual box center will be adjusted from C to a point C' that is the // midpoint of each interval, // C' = C + sum_{i=0}^2 0.5*(min[i]+max[i])*D[i] // The box extents are // e[i] = 0.5*(max[i]-min[i]) std::array<Vector3<Real>, 8> vertex; Vector3<Real> pmin{ (Real)0, (Real)0, (Real)0 }; Vector3<Real> pmax{ (Real)0, (Real)0, (Real)0 }; box0.GetVertices(vertex); for (int32_t i = 0; i < 8; ++i) { Vector3<Real> diff = vertex[i] - merge.center; for (int32_t j = 0; j < 3; ++j) { Real dot = Dot(diff, merge.axis[j]); if (dot > pmax[j]) { pmax[j] = dot; } else if (dot < pmin[j]) { pmin[j] = dot; } } } box1.GetVertices(vertex); for (int32_t i = 0; i < 8; ++i) { Vector3<Real> diff = vertex[i] - merge.center; for (int32_t j = 0; j < 3; ++j) { Real dot = Dot(diff, merge.axis[j]); if (dot > pmax[j]) { pmax[j] = dot; } else if (dot < pmin[j]) { pmin[j] = dot; } } } // [min,max] is the axis-aligned box in the coordinate system of the // merged box axes. Update the current box center to be the center of // the new box. Compute the extents based on the new center. Real const half = (Real)0.5; for (int32_t j = 0; j < 3; ++j) { merge.center += half * (pmax[j] + pmin[j]) * merge.axis[j]; merge.extent[j] = half * (pmax[j] - pmin[j]); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FeatureKey.h
.h
2,980
106
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/HashCombine.h> #include <algorithm> #include <array> namespace gte { template <int32_t N, bool Ordered> class FeatureKey { protected: // Abstract base class with V[] uninitialized. The derived classes // must set the V[] values accordingly. // // An ordered feature key has V[0] = min(V[]) with // (V[0],V[1],...,V[N-1]) a permutation of N inputs with an even // number of transpositions. // // An unordered feature key has V[0] < V[1] < ... < V[N-1]. // // Note that the word 'order' is about the geometry of the feature, not // the comparison order for any sorting. FeatureKey() = default; public: // The std::array comparisons were removed to improve the speed of the // comparisons when using the C++ Standard Library that ships with // Microsoft Visual Studio 2019 16.7.*. bool operator==(FeatureKey const& key) const { for (size_t i = 0; i < N; ++i) { if (V[i] != key.V[i]) { return false; } } return true; } bool operator!=(FeatureKey const& key) const { return !operator==(key); } bool operator<(FeatureKey const& key) const { for (size_t i = 0; i < N; ++i) { if (V[i] < key.V[i]) { return true; } if (V[i] > key.V[i]) { return false; } } return false; } bool operator<=(FeatureKey const& key) const { return !key.operator<(*this); } bool operator>(FeatureKey const& key) const { return key.operator<(*this); } bool operator>=(FeatureKey const& key) const { return !operator<(key); } // Support for hashing in std::unordered*<T> container classes. The // first operator() is the hash function. The second operator() is // the equality comparison used for elements in the same bucket. std::size_t operator()(FeatureKey const& key) const { std::size_t seed = 0; for (auto value : key.V) { HashCombine(seed, value); } return seed; } bool operator()(FeatureKey const& v0, FeatureKey const& v1) const { return v0 == v1; } std::array<int32_t, N> V; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPlane3AlignedBox3.h
.h
2,101
63
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistPlane3CanonicalBox3.h> #include <Mathematics/AlignedBox.h> // Compute the distance between a plane and a solid aligned box in 3D. // // The plane is defined by Dot(N, X - P) = 0, where P is the plane origin and // N is a unit-length normal for the plane. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The closest point on the plane is stored in closest[0]. The closest point // on the box is stored in closest[1]. When there are infinitely many choices // for the pair of closest points, only one of them is returned. // // TODO: Modify to support non-unit-length N. namespace gte { template <typename T> class DCPQuery<T, Plane3<T>, AlignedBox3<T>> { public: using PCQuery = DCPQuery<T, Plane3<T>, CanonicalBox3<T>>; using Result = typename PCQuery::Result; Result operator()(Plane3<T> const& plane, AlignedBox3<T> const& box) { Result result{}; // Translate the plane and box so that the box has center at the // origin. Vector3<T> boxCenter{}; CanonicalBox3<T> cbox{}; box.GetCenteredForm(boxCenter, cbox.extent); Vector3<T> xfrmOrigin = plane.origin - boxCenter; // The query computes 'output' relative to the box with center // at the origin. Plane3<T> xfrmPlane(plane.normal, xfrmOrigin); PCQuery pcQuery{}; result = pcQuery(xfrmPlane, cbox); // Translate the closest points to the original coordinates. for (size_t i = 0; i < 2; ++i) { result.closest[i] += boxCenter; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2Line2.h
.h
6,952
192
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.25 #pragma once #include <Mathematics/Vector2.h> #include <Mathematics/Line.h> #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <limits> // Test-intersection and find-intersection queries for two lines. The line // directions are nonzero but not required to be unit length. namespace gte { template <typename T> class TIQuery<T, Line2<T>, Line2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0) { } // If the lines do not intersect, // intersect = false // numIntersections = 0 // // If the lines intersect in a single point, // intersect = true // numIntersections = 1 // // If the lines are the same, // intersect = true // numIntersections = std::numeric_limits<int32_t>::max() bool intersect; int32_t numIntersections; }; Result operator()(Line2<T> const& line0, Line2<T> const& line1) { Result result{}; // The intersection of two lines is a solution to P0 + s0 * D0 = // P1 + s1 * D1. Rewrite this as s0*D0 - s1*D1 = P1 - P0 = Q. If // DotPerp(D0, D1)) = 0, the lines are parallel. Additionally, if // DotPerp(Q, D1)) = 0, the lines are the same. If // DotPerp(D0, D1)) is not zero, then the lines intersect in a // single point where // s0 = DotPerp(Q, D1))/DotPerp(D0, D1)) // s1 = DotPerp(Q, D0))/DotPerp(D0, D1)) T const zero = static_cast<T>(0); T dotD0PerpD1 = DotPerp(line0.direction, line1.direction); if (dotD0PerpD1 != zero) { // The lines are not parallel. result.intersect = true; result.numIntersections = 1; } else { // The lines are parallel. Vector2<T> Q = line1.origin - line0.origin; T dotQDotPerpD1 = DotPerp(Q, line1.direction); if (dotQDotPerpD1 != zero) { // The lines are parallel but distinct. result.intersect = false; result.numIntersections = 0; } else { // The lines are the same. result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); } } return result; } }; template <typename T> class FIQuery<T, Line2<T>, Line2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), line0Parameter{ static_cast<T>(0), static_cast<T>(0) }, line1Parameter{ static_cast<T>(0), static_cast<T>(0) }, point(Vector2<T>::Zero()) { } // If the lines do not intersect, // intersect = false // numIntersections = 0 // line0Parameter[] = { 0, 0 } // invalid // line1Parameter[] = { 0, 0 } // invalid // point = { 0, 0 } // invalid // // If the lines intersect in a single point, the parameter for // line0 is s0 and the parameter for line1 is s1, // intersect = true // numIntersections = 1 // line0Parameter = { s0, s0 } // line1Parameter = { s1, s1 } // point = line0.origin + s0 * line0.direction // = line1.origin + s1 * line1.direction // // If the lines are the same, // let maxT = std::numeric_limits<T>::max(), // intersect = true // numIntersections = std::numeric_limits<int32_t>::max() // line0Parameter = { -maxT, +maxT } // line1Parameter = { -maxT, +maxT } // point = { 0, 0 } // invalid bool intersect; int32_t numIntersections; std::array<T, 2> line0Parameter, line1Parameter; Vector2<T> point; }; Result operator()(Line2<T> const& line0, Line2<T> const& line1) { Result result{}; // The intersection of two lines is a solution to P0 + s0 * D0 = // P1 + s1 * D1. Rewrite this as s0*D0 - s1*D1 = P1 - P0 = Q. If // DotPerp(D0, D1)) = 0, the lines are parallel. Additionally, if // DotPerp(Q, D1)) = 0, the lines are the same. If // DotPerp(D0, D1)) is not zero, then the lines intersect in a // single point where // s0 = DotPerp(Q, D1))/DotPerp(D0, D1)) // s1 = DotPerp(Q, D0))/DotPerp(D0, D1)) T const zero = static_cast<T>(0); Vector2<T> Q = line1.origin - line0.origin; T dotD0PerpD1 = DotPerp(line0.direction, line1.direction); if (dotD0PerpD1 != zero) { // The lines are not parallel. result.intersect = true; result.numIntersections = 1; T dotQPerpD0 = DotPerp(Q, line0.direction); T dotQPerpD1 = DotPerp(Q, line1.direction); T s0 = dotQPerpD1 / dotD0PerpD1; T s1 = dotQPerpD0 / dotD0PerpD1; result.line0Parameter = { s0, s0 }; result.line1Parameter = { s1, s1 }; result.point = line0.origin + s0 * line0.direction; } else { // The lines are parallel. T dotQPerpD1 = DotPerp(Q, line1.direction); if (std::fabs(dotQPerpD1) != zero) { // The lines are parallel but distinct. result.intersect = false; result.numIntersections = 0; } else { // The lines are the same. result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); T const maxT = std::numeric_limits<T>::max(); result.line0Parameter = { -maxT, maxT }; result.line1Parameter = { -maxT, maxT }; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegment3Rectangle3.h
.h
3,030
82
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3Rectangle3.h> #include <Mathematics/DistPointRectangle.h> #include <Mathematics/Segment.h> // Compute the distance between a segment and a solid rectangle in 3D. // // The segment is P0 + t * (P1 - P0) for 0 <= t <= 1. The direction D = P1-P0 // is generally not unit length. // // The rectangle has center C, unit-length axis directions W[0] and W[1], and // extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i] // where |s[i]| <= e[i] for all i. // // The closest point on the segment is stored in closest[0] with parameter t. // The closest point on the rectangle is closest[1] with W-coordinates // (s[0],s[1]). When there are infinitely many choices for the pair of closest // points, only one of them is returned. // // TODO: Modify to support non-unit-length W[]. namespace gte { template <typename T> class DCPQuery<T, Segment3<T>, Rectangle3<T>> { public: using LRQuery = DCPQuery<T, Line3<T>, Rectangle3<T>>; using Result = typename LRQuery::Result; Result operator()(Segment3<T> const& segment, Rectangle3<T> const& rectangle) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector3<T> segDirection = segment.p[1] - segment.p[0]; Line3<T> line(segment.p[0], segDirection); LRQuery lrQuery{}; auto lrResult = lrQuery(line, rectangle); if (lrResult.parameter >= zero) { if (lrResult.parameter <= one) { result = lrResult; } else { DCPQuery<T, Vector3<T>, Rectangle3<T>> prQuery{}; auto prResult = prQuery(segment.p[1], rectangle); result.distance = prResult.distance; result.sqrDistance = prResult.sqrDistance; result.parameter = one; result.cartesian = prResult.cartesian; result.closest[0] = segment.p[1]; result.closest[1] = prResult.closest[1]; } } else { DCPQuery<T, Vector3<T>, Rectangle3<T>> prQuery{}; auto prResult = prQuery(segment.p[0], rectangle); result.distance = prResult.distance; result.sqrDistance = prResult.sqrDistance; result.parameter = zero; result.cartesian = prResult.cartesian; result.closest[0] = segment.p[0]; result.closest[1] = prResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay3Plane3.h
.h
3,258
112
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrLine3Plane3.h> #include <Mathematics/Ray.h> namespace gte { template <typename Real> class TIQuery<Real, Ray3<Real>, Plane3<Real>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Ray3<Real> const& ray, Plane3<Real> const& plane) { Result result{}; // Compute the (signed) distance from the ray origin to the plane. DCPQuery<Real, Vector3<Real>, Plane3<Real>> vpQuery{}; auto vpResult = vpQuery(ray.origin, plane); Real DdN = Dot(ray.direction, plane.normal); if (DdN > (Real)0) { // The ray is not parallel to the plane and is directed toward // the +normal side of the plane. result.intersect = (vpResult.signedDistance <= (Real)0); } else if (DdN < (Real)0) { // The ray is not parallel to the plane and is directed toward // the -normal side of the plane. result.intersect = (vpResult.signedDistance >= (Real)0); } else { // The ray and plane are parallel. result.intersect = (vpResult.distance == (Real)0); } return result; } }; template <typename Real> class FIQuery<Real, Ray3<Real>, Plane3<Real>> : public FIQuery<Real, Line3<Real>, Plane3<Real>> { public: struct Result : public FIQuery<Real, Line3<Real>, Plane3<Real>>::Result { Result() : FIQuery<Real, Line3<Real>, Plane3<Real>>::Result{} { } // No additional information to compute. }; Result operator()(Ray3<Real> const& ray, Plane3<Real> const& plane) { Result result{}; DoQuery(ray.origin, ray.direction, plane, result); if (result.intersect) { result.point = ray.origin + result.parameter * ray.direction; } return result; } protected: void DoQuery(Vector3<Real> const& rayOrigin, Vector3<Real> const& rayDirection, Plane3<Real> const& plane, Result& result) { FIQuery<Real, Line3<Real>, Plane3<Real>>::DoQuery(rayOrigin, rayDirection, plane, result); if (result.intersect) { // The line intersects the plane in a point that might not be // on the ray. if (result.parameter < (Real)0) { result.intersect = false; result.numIntersections = 0; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Array3.h
.h
4,710
167
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstddef> #include <cstdint> #include <vector> // The Array3 class represents a 3-dimensional array that minimizes the number // of new and delete calls. The T objects are stored in a contiguous array. namespace gte { template <typename T> class Array3 { public: // Construction. The first constructor generates an array of objects // that are owned by Array3. The second constructor is given an array // of objects that are owned by the caller. The array has bound0 // columns, bound1 rows, and bound2 slices. Array3(size_t bound0, size_t bound1, size_t bound2) : mBound0(bound0), mBound1(bound1), mBound2(bound2), mObjects(bound0 * bound1 * bound2), mIndirect1(bound1 * bound2), mIndirect2(bound2) { SetPointers(mObjects.data()); } Array3(size_t bound0, size_t bound1, size_t bound2, T* objects) : mBound0(bound0), mBound1(bound1), mBound2(bound2), mIndirect1(bound1 * bound2), mIndirect2(bound2) { SetPointers(objects); } // Support for dynamic resizing, copying, or moving. If 'other' does // not own the original 'objects', they are not copied by the // assignment operator. Array3() : mBound0(0), mBound1(0), mBound2(0) { } Array3(Array3 const& other) : mBound0(other.mBound0), mBound1(other.mBound1), mBound2(other.mBound2) { *this = other; } Array3& operator=(Array3 const& other) { // The copy is valid whether or not other.mObjects has elements. mObjects = other.mObjects; SetPointers(other); return *this; } Array3(Array3&& other) noexcept : mBound0(other.mBound0), mBound1(other.mBound1), mBound2(other.mBound2) { *this = std::move(other); } Array3& operator=(Array3&& other) noexcept { // The move is valid whether or not other.mObjects has elements. mObjects = std::move(other.mObjects); SetPointers(other); return *this; } // Access to the array. Sample usage is // Array3<T> myArray(4, 3, 2); // T** slice1 = myArray[1]; // T* slice1row2 = myArray[1][2]; // T slice1Row2Col3 = myArray[1][2][3]; inline size_t GetBound0() const { return mBound0; } inline size_t GetBound1() const { return mBound1; } inline size_t GetBound2() const { return mBound2; } inline T* const* operator[](int32_t slice) const { return mIndirect2[slice]; } inline T** operator[](int32_t slice) { return mIndirect2[slice]; } private: void SetPointers(T* objects) { for (size_t i2 = 0; i2 < mBound2; ++i2) { size_t j1 = mBound1 * i2; // = bound1*(i2 + j2) where j2 = 0 mIndirect2[i2] = &mIndirect1[j1]; for (size_t i1 = 0; i1 < mBound1; ++i1) { size_t j0 = mBound0 * (i1 + j1); mIndirect2[i2][i1] = &objects[j0]; } } } void SetPointers(Array3 const& other) { mBound0 = other.mBound0; mBound1 = other.mBound1; mBound2 = other.mBound2; mIndirect1.resize(mBound1 * mBound2); mIndirect2.resize(mBound2); if (mBound0 > 0) { // The objects are owned. SetPointers(mObjects.data()); } else if (mIndirect1.size() > 0) { // The objects are not owned. SetPointers(other.mIndirect2[0][0]); } // else 'other' is an empty Array3. } size_t mBound0, mBound1, mBound2; std::vector<T> mObjects; std::vector<T*> mIndirect1; std::vector<T**> mIndirect2; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MeshCurvature.h
.h
11,685
286
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix2x2.h> #include <Mathematics/Matrix3x3.h> // The MeshCurvature class estimates principal curvatures and principal // directions at the vertices of a manifold triangle mesh. The algorithm // is described in // https://www.geometrictools.com/Documentation/MeshDifferentialGeometry.pdf namespace gte { template <typename Real> class MeshCurvature { public: MeshCurvature() = default; // The input to operator() is a triangle mesh with the specified // vertex buffer and index buffer. The number of elements of // 'indices' must be a multiple of 3, each triple of indices // (3*t, 3*t+1, 3*t+2) representing the triangle with vertices // (vertices[3*t], vertices[3*t+1], vertices[3*t+2]). The // singularity threshold is a small nonnegative number. It is // used to characterize whether the DWTrn matrix is singular. In // theory, set the threshold to zero. In practice you might have // to set this to a small positive number. void operator()( size_t numVertices, Vector3<Real> const* vertices, size_t numTriangles, uint32_t const* indices, Real singularityThreshold) { mNormals.resize(numVertices); mMinCurvatures.resize(numVertices); mMaxCurvatures.resize(numVertices); mMinDirections.resize(numVertices); mMaxDirections.resize(numVertices); // Compute the normal vectors for the vertices as an // area-weighted sum of the triangles sharing a vertex. Vector3<Real> vzero{ (Real)0, (Real)0, (Real)0 }; std::fill(mNormals.begin(), mNormals.end(), vzero); uint32_t const* currentIndex = indices; for (size_t i = 0; i < numTriangles; ++i) { // Get vertex indices. uint32_t v0 = *currentIndex++; uint32_t v1 = *currentIndex++; uint32_t v2 = *currentIndex++; // Compute the normal (length provides a weighted sum). Vector3<Real> edge1 = vertices[v1] - vertices[v0]; Vector3<Real> edge2 = vertices[v2] - vertices[v0]; Vector3<Real> normal = Cross(edge1, edge2); mNormals[v0] += normal; mNormals[v1] += normal; mNormals[v2] += normal; } for (size_t i = 0; i < numVertices; ++i) { Normalize(mNormals[i]); } // Compute the matrix of normal derivatives. Matrix3x3<Real> mzero; std::vector<Matrix3x3<Real>> DNormal(numVertices, mzero); std::vector<Matrix3x3<Real>> WWTrn(numVertices, mzero); std::vector<Matrix3x3<Real>> DWTrn(numVertices, mzero); std::vector<bool> DWTrnZero(numVertices, false); currentIndex = indices; for (size_t i = 0; i < numTriangles; ++i) { // Get vertex indices. uint32_t v[3]; v[0] = *currentIndex++; v[1] = *currentIndex++; v[2] = *currentIndex++; for (size_t j = 0; j < 3; j++) { uint32_t v0 = v[j]; uint32_t v1 = v[(j + 1) % 3]; uint32_t v2 = v[(j + 2) % 3]; // Compute the edge direction from vertex v0 to vertex v1, // project it to the tangent plane of vertex v0 and // compute the difference of adjacent normals. Vector3<Real> E = vertices[v1] - vertices[v0]; Vector3<Real> W = E - Dot(E, mNormals[v0]) * mNormals[v0]; Vector3<Real> D = mNormals[v1] - mNormals[v0]; for (int32_t row = 0; row < 3; ++row) { for (int32_t col = 0; col < 3; ++col) { WWTrn[v0](row, col) += W[row] * W[col]; DWTrn[v0](row, col) += D[row] * W[col]; } } // Compute the edge direction from vertex v0 to vertex v2, // project it to the tangent plane of vertex v0 and // compute the difference of adjacent normals. E = vertices[v2] - vertices[v0]; W = E - Dot(E, mNormals[v0]) * mNormals[v0]; D = mNormals[v2] - mNormals[v0]; for (int32_t row = 0; row < 3; ++row) { for (int32_t col = 0; col < 3; ++col) { WWTrn[v0](row, col) += W[row] * W[col]; DWTrn[v0](row, col) += D[row] * W[col]; } } } } // Add in N*N^T to W*W^T for numerical stability. In theory 0*0^T // is added to D*W^T, but of course no update is needed in the // implementation. Compute the matrix of normal derivatives. for (size_t i = 0; i < numVertices; ++i) { for (int32_t row = 0; row < 3; ++row) { for (int32_t col = 0; col < 3; ++col) { WWTrn[i](row, col) = (Real)0.5 * WWTrn[i](row, col) + mNormals[i][row] * mNormals[i][col]; DWTrn[i](row, col) *= (Real)0.5; } } // Compute the max-abs entry of D*W^T. If this entry is // (nearly) zero, flag the DNormal matrix as singular. Real maxAbs = (Real)0; for (int32_t row = 0; row < 3; ++row) { for (int32_t col = 0; col < 3; ++col) { Real absEntry = std::fabs(DWTrn[i](row, col)); if (absEntry > maxAbs) { maxAbs = absEntry; } } } if (maxAbs < singularityThreshold) { DWTrnZero[i] = true; } DNormal[i] = DWTrn[i] * Inverse(WWTrn[i]); } // If N is a unit-length normal at a vertex, let U and V be // unit-length tangents so that {U, V, N} is an orthonormal set. // Define the matrix J = [U | V], a 3-by-2 matrix whose columns // are U and V. Define J^T to be the transpose of J, a 2-by-3 // matrix. Let dN/dX denote the matrix of first-order derivatives // of the normal vector field. The shape matrix is // S = (J^T * J)^{-1} * J^T * dN/dX * J = J^T * dN/dX * J // where the superscript of -1 denotes the inverse; the formula // allows for J to be created from non-perpendicular vectors. The // matrix S is 2-by-2. The principal curvatures are the // eigenvalues of S. If k is a principal curvature and W is the // 2-by-1 eigenvector corresponding to it, then S*W = k*W (by // definition). The corresponding 3-by-1 tangent vector at the // vertex is a principal direction for k and is J*W. for (size_t i = 0; i < numVertices; ++i) { // Compute U and V given N. Vector3<Real> basis[3]; basis[0] = mNormals[i]; ComputeOrthogonalComplement(1, basis); Vector3<Real> const& U = basis[1]; Vector3<Real> const& V = basis[2]; if (DWTrnZero[i]) { // At a locally planar point. mMinCurvatures[i] = (Real)0; mMaxCurvatures[i] = (Real)0; mMinDirections[i] = U; mMaxDirections[i] = V; continue; } // Compute S = J^T * dN/dX * J. In theory S is symmetric, but // because dN/dX is estimated, we must ensure that the // computed S is symmetric. Real s00 = Dot(U, DNormal[i] * U); Real s01 = Dot(U, DNormal[i] * V); Real s10 = Dot(V, DNormal[i] * U); Real s11 = Dot(V, DNormal[i] * V); Real avr = (Real)0.5 * (s01 + s10); Matrix2x2<Real> S{ s00, avr, avr, s11 }; // Compute the eigenvalues of S (min and max curvatures). Real trace = S(0, 0) + S(1, 1); Real det = S(0, 0) * S(1, 1) - S(0, 1) * S(1, 0); Real discr = trace * trace - (Real)4.0 * det; Real rootDiscr = std::sqrt(std::max(discr, (Real)0)); mMinCurvatures[i] = (Real)0.5* (trace - rootDiscr); mMaxCurvatures[i] = (Real)0.5* (trace + rootDiscr); // Compute the eigenvectors of S. Vector2<Real> W0{ S(0, 1), mMinCurvatures[i] - S(0, 0) }; Vector2<Real> W1{ mMinCurvatures[i] - S(1, 1), S(1, 0) }; if (Dot(W0, W0) >= Dot(W1, W1)) { Normalize(W0); mMinDirections[i] = W0[0] * U + W0[1] * V; } else { Normalize(W1); mMinDirections[i] = W1[0] * U + W1[1] * V; } W0 = Vector2<Real>{ S(0, 1), mMaxCurvatures[i] - S(0, 0) }; W1 = Vector2<Real>{ mMaxCurvatures[i] - S(1, 1), S(1, 0) }; if (Dot(W0, W0) >= Dot(W1, W1)) { Normalize(W0); mMaxDirections[i] = W0[0] * U + W0[1] * V; } else { Normalize(W1); mMaxDirections[i] = W1[0] * U + W1[1] * V; } } } void operator()( std::vector<Vector3<Real>> const& vertices, std::vector<uint32_t> const& indices, Real singularityThreshold) { operator()(vertices.size(), vertices.data(), indices.size() / 3, indices.data(), singularityThreshold); } inline std::vector<Vector3<Real>> const& GetNormals() const { return mNormals; } inline std::vector<Real> const& GetMinCurvatures() const { return mMinCurvatures; } inline std::vector<Real> const& GetMaxCurvatures() const { return mMaxCurvatures; } inline std::vector<Vector3<Real>> const& GetMinDirections() const { return mMinDirections; } inline std::vector<Vector3<Real>> const& GetMaxDirections() const { return mMaxDirections; } private: std::vector<Vector3<Real>> mNormals; std::vector<Real> mMinCurvatures; std::vector<Real> mMaxCurvatures; std::vector<Vector3<Real>> mMinDirections; std::vector<Vector3<Real>> mMaxDirections; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/GradientAnisotropic2.h
.h
4,047
113
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/PdeFilter2.h> #include <Mathematics/Math.h> namespace gte { template <typename Real> class GradientAnisotropic2 : public PdeFilter2<Real> { public: GradientAnisotropic2(int32_t xBound, int32_t yBound, Real xSpacing, Real ySpacing, Real const* data, int32_t const* mask, Real borderValue, typename PdeFilter<Real>::ScaleType scaleType, Real K) : PdeFilter2<Real>(xBound, yBound, xSpacing, ySpacing, data, mask, borderValue, scaleType), mK(K) { ComputeParameter(); } virtual ~GradientAnisotropic2() { } protected: void ComputeParameter() { Real gradMagSqr = (Real)0; for (int32_t y = 1; y <= this->mYBound; ++y) { for (int32_t x = 1; x <= this->mXBound; ++x) { Real ux = this->GetUx(x, y); Real uy = this->GetUy(x, y); gradMagSqr += ux * ux + uy * uy; } } gradMagSqr /= (Real)this->mQuantity; mParameter = (Real)1 / (mK * mK * gradMagSqr); mMHalfParameter = (Real)-0.5 * mParameter; } virtual void OnPreUpdate() override { ComputeParameter(); } virtual void OnUpdateSingle(int32_t x, int32_t y) override { this->LookUp9(x, y); // one-sided U-derivative estimates Real uxFwd = this->mInvDx * (this->mUpz - this->mUzz); Real uxBwd = this->mInvDx * (this->mUzz - this->mUmz); Real uyFwd = this->mInvDy * (this->mUzp - this->mUzz); Real uyBwd = this->mInvDy * (this->mUzz - this->mUzm); // centered U-derivative estimates Real uxCenM = this->mHalfInvDx * (this->mUpm - this->mUmm); Real uxCenZ = this->mHalfInvDx * (this->mUpz - this->mUmz); Real uxCenP = this->mHalfInvDx * (this->mUpp - this->mUmp); Real uyCenM = this->mHalfInvDy * (this->mUmp - this->mUmm); Real uyCenZ = this->mHalfInvDy * (this->mUzp - this->mUzm); Real uyCenP = this->mHalfInvDy * (this->mUpp - this->mUpm); Real uxCenZSqr = uxCenZ * uxCenZ; Real uyCenZSqr = uyCenZ * uyCenZ; Real gradMagSqr; // estimate for C(x+1,y) Real uyEstP = (Real)0.5 * (uyCenZ + uyCenP); gradMagSqr = uxCenZSqr + uyEstP * uyEstP; Real cxp = std::exp(mMHalfParameter * gradMagSqr); // estimate for C(x-1,y) Real uyEstM = (Real)0.5 * (uyCenZ + uyCenM); gradMagSqr = uxCenZSqr + uyEstM * uyEstM; Real cxm = std::exp(mMHalfParameter * gradMagSqr); // estimate for C(x,y+1) Real uxEstP = (Real)0.5 * (uxCenZ + uxCenP); gradMagSqr = uyCenZSqr + uxEstP * uxEstP; Real cyp = std::exp(mMHalfParameter * gradMagSqr); // estimate for C(x,y-1) Real uxEstM = (Real)0.5 * (uxCenZ + uxCenM); gradMagSqr = uyCenZSqr + uxEstM * uxEstM; Real cym = std::exp(mMHalfParameter * gradMagSqr); this->mBuffer[this->mDst][y][x] = this->mUzz + this->mTimeStep * ( cxp * uxFwd - cxm * uxBwd + cyp * uyFwd - cym * uyBwd); } // These are updated on each iteration, since they depend on the // current average of the squared length of the gradients at the // pixels. Real mK; // k Real mParameter; // 1/(k^2*average(gradMagSqr)) Real mMHalfParameter; // -0.5*mParameter }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CurveExtractorTriangles.h
.h
8,539
228
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/CurveExtractor.h> // The level set extraction algorithm implemented here is described // in Section 2 of the document // https://www.geometrictools.com/Documentation/ExtractLevelCurves.pdf namespace gte { // The image type T must be one of the integer types: int8_t, int16_t, // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations // are performed using int64_t. The type Real is for extraction to // floating-point vertices. template <typename T, typename Real> class CurveExtractorTriangles : public CurveExtractor<T, Real> { public: // Convenience type definitions. typedef typename CurveExtractor<T, Real>::Vertex Vertex; typedef typename CurveExtractor<T, Real>::Edge Edge; // The input is a 2D image with lexicographically ordered pixels (x,y) // stored in a linear array. Pixel (x,y) is stored in the array at // location index = x + xBound * y. The inputs xBound and yBound must // each be 2 or larger so that there is at least one image square to // process. The inputPixels must be nonnull and point to contiguous // storage that contains at least xBound * yBound elements. CurveExtractorTriangles(int32_t xBound, int32_t yBound, T const* inputPixels) : CurveExtractor<T, Real>(xBound, yBound, inputPixels) { } // Extract level curves and return rational vertices. Use the // base-class Extract if you want real-valued vertices. virtual void Extract(T level, std::vector<Vertex>& vertices, std::vector<Edge>& edges) override { // Adjust the image so that the level set is F(x,y) = 0. int64_t levelI64 = static_cast<int64_t>(level); for (size_t i = 0; i < this->mPixels.size(); ++i) { int64_t inputI64 = static_cast<int64_t>(this->mInputPixels[i]); this->mPixels[i] = inputI64 - levelI64; } vertices.clear(); edges.clear(); for (int32_t y = 0, yp = 1; yp < this->mYBound; ++y, ++yp) { int32_t yParity = (y & 1); for (int32_t x = 0, xp = 1; xp < this->mXBound; ++x, ++xp) { int32_t xParity = (x & 1); // Get the image values at the corners of the square. int32_t i00 = x + this->mXBound * y; int32_t i10 = i00 + 1; int32_t i01 = i00 + this->mXBound; int32_t i11 = i10 + this->mXBound; int64_t f00 = this->mPixels[i00]; int64_t f10 = this->mPixels[i10]; int64_t f01 = this->mPixels[i01]; int64_t f11 = this->mPixels[i11]; // Construct the vertices and edges of the level curve in // the square. The x, xp, y and yp values are implicitly // converted from int32_t to int64_t (which is guaranteed to // be correct). if (xParity == yParity) { ProcessTriangle(vertices, edges, x, y, f00, x, yp, f01, xp, y, f10); ProcessTriangle(vertices, edges, xp, yp, f11, xp, y, f10, x, yp, f01); } else { ProcessTriangle(vertices, edges, x, yp, f01, xp, yp, f11, x, y, f00); ProcessTriangle(vertices, edges, xp, y, f10, x, y, f00, xp, yp, f11); } } } } protected: void ProcessTriangle(std::vector<Vertex>& vertices, std::vector<Edge>& edges, int64_t x0, int64_t y0, int64_t f0, int64_t x1, int64_t y1, int64_t f1, int64_t x2, int64_t y2, int64_t f2) { int64_t xn0, yn0, xn1, yn1, d0, d1; if (f0 != 0) { // convert to case "+**" if (f0 < 0) { f0 = -f0; f1 = -f1; f2 = -f2; } if (f1 > 0) { if (f2 > 0) { // +++ return; } else if (f2 < 0) { // ++- d0 = f0 - f2; xn0 = f0 * x2 - f2 * x0; yn0 = f0 * y2 - f2 * y0; d1 = f1 - f2; xn1 = f1 * x2 - f2 * x1; yn1 = f1 * y2 - f2 * y1; this->AddEdge(vertices, edges, xn0, d0, yn0, d0, xn1, d1, yn1, d1); } else { // ++0 this->AddVertex(vertices, x2, 1, y2, 1); } } else if (f1 < 0) { d0 = f0 - f1; xn0 = f0 * x1 - f1 * x0; yn0 = f0 * y1 - f1 * y0; if (f2 > 0) { // +-+ d1 = f2 - f1; xn1 = f2 * x1 - f1 * x2; yn1 = f2 * y1 - f1 * y2; this->AddEdge(vertices, edges, xn0, d0, yn0, d0, xn1, d1, yn1, d1); } else if (f2 < 0) { // +-- d1 = f2 - f0; xn1 = f2 * x0 - f0 * x2; yn1 = f2 * y0 - f0 * y2; this->AddEdge(vertices, edges, xn0, d0, yn0, d0, xn1, d1, yn1, d1); } else { // +-0 this->AddEdge(vertices, edges, x2, 1, y2, 1, xn0, d0, yn0, d0); } } else { if (f2 > 0) { // +0+ this->AddVertex(vertices, x1, 1, y1, 1); } else if (f2 < 0) { // +0- d0 = f2 - f0; xn0 = f2 * x0 - f0 * x2; yn0 = f2 * y0 - f0 * y2; this->AddEdge(vertices, edges, x1, 1, y1, 1, xn0, d0, yn0, d0); } else { // +00 this->AddEdge(vertices, edges, x1, 1, y1, 1, x2, 1, y2, 1); } } } else if (f1 != 0) { // convert to case 0+* if (f1 < 0) { f1 = -f1; f2 = -f2; } if (f2 > 0) { // 0++ this->AddVertex(vertices, x0, 1, y0, 1); } else if (f2 < 0) { // 0+- d0 = f1 - f2; xn0 = f1 * x2 - f2 * x1; yn0 = f1 * y2 - f2 * y1; this->AddEdge(vertices, edges, x0, 1, y0, 1, xn0, d0, yn0, d0); } else { // 0+0 this->AddEdge(vertices, edges, x0, 1, y0, 1, x2, 1, y2, 1); } } else if (f2 != 0) { // cases 00+ or 00- this->AddEdge(vertices, edges, x0, 1, y0, 1, x1, 1, y1, 1); } else { // case 000 this->AddEdge(vertices, edges, x0, 1, y0, 1, x1, 1, y1, 1); this->AddEdge(vertices, edges, x1, 1, y1, 1, x2, 1, y2, 1); this->AddEdge(vertices, edges, x2, 1, y2, 1, x0, 1, y0, 1); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprSphere3.h
.h
6,934
172
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector3.h> #include <cstdint> // Least-squares fit of a sphere to a set of points. The algorithms are // described in Section 5 of // https://www.geometrictools.com/Documentation/LeastSquaresFitting.pdf // FitUsingLengths uses the algorithm of Section 5.1. // FitUsingSquaredLengths uses the algorithm of Section 5.2. namespace gte { template <typename Real> class ApprSphere3 { public: // The return value is 'true' when the linear system of the algorithm // is solvable, 'false' otherwise. If 'false' is returned, the sphere // center and radius are set to zero values. bool FitUsingSquaredLengths(int32_t numPoints, Vector3<Real> const* points, Sphere3<Real>& sphere) { // Compute the average of the data points. Real const zero(0); Vector3<Real> A = { zero, zero, zero }; for (int32_t i = 0; i < numPoints; ++i) { A += points[i]; } Real invNumPoints = ((Real)1) / static_cast<Real>(numPoints); A *= invNumPoints; // Compute the covariance matrix M of the Y[i] = X[i]-A and the // right-hand side R of the linear system M*(C-A) = R. Real M00 = zero, M01 = zero, M02 = zero, M11 = zero, M12 = zero, M22 = zero; Vector3<Real> R = { zero, zero, zero }; for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> Y = points[i] - A; Real Y0Y0 = Y[0] * Y[0]; Real Y0Y1 = Y[0] * Y[1]; Real Y0Y2 = Y[0] * Y[2]; Real Y1Y1 = Y[1] * Y[1]; Real Y1Y2 = Y[1] * Y[2]; Real Y2Y2 = Y[2] * Y[2]; M00 += Y0Y0; M01 += Y0Y1; M02 += Y0Y2; M11 += Y1Y1; M12 += Y1Y2; M22 += Y2Y2; R += (Y0Y0 + Y1Y1 + Y2Y2) * Y; } R *= (Real)0.5; // Solve the linear system M*(C-A) = R for the center C. Real cof00 = M11 * M22 - M12 * M12; Real cof01 = M02 * M12 - M01 * M22; Real cof02 = M01 * M12 - M02 * M11; Real det = M00 * cof00 + M01 * cof01 + M02 * cof02; if (det != zero) { Real cof11 = M00 * M22 - M02 * M02; Real cof12 = M01 * M02 - M00 * M12; Real cof22 = M00 * M11 - M01 * M01; sphere.center[0] = A[0] + (cof00 * R[0] + cof01 * R[1] + cof02 * R[2]) / det; sphere.center[1] = A[1] + (cof01 * R[0] + cof11 * R[1] + cof12 * R[2]) / det; sphere.center[2] = A[2] + (cof02 * R[0] + cof12 * R[1] + cof22 * R[2]) / det; Real rsqr = zero; for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> delta = points[i] - sphere.center; rsqr += Dot(delta, delta); } rsqr *= invNumPoints; sphere.radius = std::sqrt(rsqr); return true; } else { sphere.center = { zero, zero, zero }; sphere.radius = zero; return false; } } // Fit the points using lengths to drive the least-squares algorithm. // If initialCenterIsAverage is set to 'false', the initial guess for // the initial sphere center is computed as the average of the data // points. If the data points are clustered along a small solid angle, // the algorithm is slow to converge. If initialCenterIsAverage is set // to 'true', the incoming sphere center is used as-is to start the // iterative algorithm. This approach tends to converge more rapidly // than when using the average of points but can be much slower than // FitUsingSquaredLengths. // // The value epsilon may be chosen as a positive number for the // comparison of consecutive estimated sphere centers, terminating the // iterations when the center difference has length less than or equal // to epsilon. // // The return value is the number of iterations used. If is is the // input maxIterations, you can either accept the result or polish the // result by calling the function again with initialCenterIsAverage // set to 'true'. uint32_t FitUsingLengths(int32_t numPoints, Vector3<Real> const* points, uint32_t maxIterations, bool initialCenterIsAverage, Sphere3<Real>& sphere, Real epsilon = (Real)0) { // Compute the average of the data points. Vector3<Real> average = points[0]; for (int32_t i = 1; i < numPoints; ++i) { average += points[i]; } Real invNumPoints = ((Real)1) / static_cast<Real>(numPoints); average *= invNumPoints; // The initial guess for the center. if (initialCenterIsAverage) { sphere.center = average; } Real epsilonSqr = epsilon * epsilon; uint32_t iteration; for (iteration = 0; iteration < maxIterations; ++iteration) { // Update the iterates. Vector3<Real> current = sphere.center; // Compute average L, dL/da, dL/db, dL/dc. Real lenAverage = (Real)0; Vector3<Real> derLenAverage = Vector3<Real>::Zero(); for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - sphere.center; Real length = Length(diff); if (length > (Real)0) { lenAverage += length; Real invLength = ((Real)1) / length; derLenAverage -= invLength * diff; } } lenAverage *= invNumPoints; derLenAverage *= invNumPoints; sphere.center = average + lenAverage * derLenAverage; sphere.radius = lenAverage; Vector3<Real> diff = sphere.center - current; Real diffSqrLen = Dot(diff, diff); if (diffSqrLen <= epsilonSqr) { break; } } return ++iteration; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox3Sphere3.h
.h
3,572
107
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistPointOrientedBox.h> #include <Mathematics/IntrAlignedBox3Sphere3.h> namespace gte { template <typename Real> class TIQuery<Real, OrientedBox3<Real>, Sphere3<Real>> : public TIQuery<Real, AlignedBox3<Real>, Sphere3<Real>> { public: // The intersection query considers the box and sphere to be solids. // For example, if the sphere is strictly inside the box (does not // touch the box faces), the objects intersect. struct Result : public TIQuery<Real, AlignedBox3<Real>, Sphere3<Real>>::Result { Result() : TIQuery<Real, AlignedBox3<Real>, Sphere3<Real>>::Result{} { } // No additional information to compute. }; Result operator()(OrientedBox3<Real> const& box, Sphere3<Real> const& sphere) { DCPQuery<Real, Vector3<Real>, OrientedBox3<Real>> pbQuery; auto pbResult = pbQuery(sphere.center, box); Result result{}; result.intersect = (pbResult.sqrDistance <= sphere.radius * sphere.radius); return result; } }; template <typename Real> class FIQuery<Real, OrientedBox3<Real>, Sphere3<Real>> : public FIQuery<Real, AlignedBox3<Real>, Sphere3<Real>> { public: // Currently, only a dynamic query is supported. The static query // must compute the intersection set of (solid) box and sphere. struct Result : public FIQuery<Real, AlignedBox3<Real>, Sphere3<Real>>::Result { Result() : FIQuery<Real, AlignedBox3<Real>, Sphere3<Real>>::Result{} { } // No additional information to compute. }; Result operator()(OrientedBox3<Real> const& box, Vector3<Real> const& boxVelocity, Sphere3<Real> const& sphere, Vector3<Real> const& sphereVelocity) { Result result{}; result.intersectionType = 0; result.contactTime = (Real)0; result.contactPoint = { (Real)0, (Real)0, (Real)0 }; // Transform the sphere and box so that the box center becomes // the origin and the box is axis aligned. Compute the velocity // of the sphere relative to the box. Vector3<Real> temp = sphere.center - box.center; Vector3<Real> C { Dot(temp, box.axis[0]), Dot(temp, box.axis[1]), Dot(temp, box.axis[2]) }; temp = sphereVelocity - boxVelocity; Vector3<Real> V { Dot(temp, box.axis[0]), Dot(temp, box.axis[1]), Dot(temp, box.axis[2]) }; this->DoQuery(box.extent, C, sphere.radius, V, result); // Transform back to the original coordinate system. if (result.intersectionType != 0) { auto& P = result.contactPoint; P = box.center + P[0] * box.axis[0] + P[1] * box.axis[1] + P[2] * box.axis[2]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment2OrientedBox2.h
.h
4,282
126
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrSegment2AlignedBox2.h> #include <Mathematics/OrientedBox.h> // The queries consider the box to be a solid. // // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the four // edges of the box. namespace gte { template <typename T> class TIQuery<T, Segment2<T>, OrientedBox2<T>> : public TIQuery<T, Segment2<T>, AlignedBox2<T>> { public: struct Result : public TIQuery<T, Segment2<T>, AlignedBox2<T>>::Result { Result() : TIQuery<T, Segment2<T>, AlignedBox2<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment2<T> const& segment, OrientedBox2<T> const& box) { // Transform the segment to the oriented-box coordinate system. Vector2<T> tmpOrigin{}, tmpDirection{}; T segExtent{}; segment.GetCenteredForm(tmpOrigin, tmpDirection, segExtent); Vector2<T> diff = tmpOrigin - box.center; Vector2<T> segOrigin { Dot(diff, box.axis[0]), Dot(diff, box.axis[1]) }; Vector2<T> segDirection { Dot(tmpDirection, box.axis[0]), Dot(tmpDirection, box.axis[1]) }; Result result{}; this->DoQuery(segOrigin, segDirection, segExtent, box.extent, result); return result; } }; template <typename T> class FIQuery<T, Segment2<T>, OrientedBox2<T>> : public FIQuery<T, Segment2<T>, AlignedBox2<T>> { public: struct Result : public FIQuery<T, Segment2<T>, AlignedBox2<T>>::Result { Result() : FIQuery<T, Segment2<T>, AlignedBox2<T>>::Result{}, cdeParameter{ (T)0, (T)0 } { } // The base class parameter[] values are t-values for the // segment parameterization (1-t)*p[0] + t*p[1], where t in [0,1]. // The values in this class are s-values for the centered form // C + s * D, where s in [-e,e] and e is the extent of the // segment. std::array<T, 2> cdeParameter; }; Result operator()(Segment2<T> const& segment, OrientedBox2<T> const& box) { // Transform the segment to the oriented-box coordinate system. Vector2<T> tmpOrigin{}, tmpDirection{}; T segExtent{}; segment.GetCenteredForm(tmpOrigin, tmpDirection, segExtent); Vector2<T> diff = tmpOrigin - box.center; Vector2<T> segOrigin { Dot(diff, box.axis[0]), Dot(diff, box.axis[1]) }; Vector2<T> segDirection { Dot(tmpDirection, box.axis[0]), Dot(tmpDirection, box.axis[1]) }; Result result{}; this->DoQuery(segOrigin, segDirection, segExtent, box.extent, result); for (int32_t i = 0; i < result.numIntersections; ++i) { // Compute the segment in the aligned-box coordinate system // and then translate it back to the original coordinates // using the box cener. result.point[i] = box.center + (segOrigin + result.parameter[i] * segDirection); result.cdeParameter[i] = result.parameter[i]; // Convert the parameters from the centered form to the // endpoint form. result.parameter[i] = (result.parameter[i] / segExtent + (T)1) * (T)0.5; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TetrahedronKey.h
.h
5,147
161
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FeatureKey.h> // An ordered tetrahedron has V[0] = min(v0, v1, v2, v3). Let {u1, u2, u3} // be the set of inputs excluding the one assigned to V[0] and define // V[1] = min(u1, u2, u3). Choose (V[1], V[2], V[3]) to be a permutation // of (u1, u2, u3) so that the final storage is one of // (v0, v1, v2, v3), (v0, v2, v3, v1), (v0, v3, v1, v2) // (v1, v3, v2, v0), (v1, v2, v0, v3), (v1, v0, v3, v2) // (v2, v3, v0, v1), (v2, v0, v1, v3), (v2, v1, v3, v0) // (v3, v1, v0, v2), (v3, v0, v2, v1), (v3, v2, v1, v0) // The idea is that if v0 corresponds to (1, 0, 0, 0), v1 corresponds to // (0, 1, 0, 0), v2 corresponds to (0, 0, 1, 0), and v3 corresponds to // (0, 0, 0, 1), the ordering (v0, v1, v2, v3) corresponds to the 4x4 identity // matrix I; the rows are the specified 4-tuples. The permutation // (V[0], V[1], V[2], V[3]) induces a permutation of the rows of the identity // matrix to form a permutation matrix P with det(P) = 1 = det(I). // // An unordered tetrahedron stores a permutation of (v0, v1, v2, v3) so // that V[0] < V[1] < V[2] < V[3]. namespace gte { template <bool Ordered> class TetrahedronKey : public FeatureKey<4, Ordered> { public: TetrahedronKey() { this->V = { -1, -1, -1, -1 }; } explicit TetrahedronKey(int32_t v0, int32_t v1, int32_t v2, int32_t v3) { Initialize(v0, v1, v2, v3); } // Indexing for the vertices of the triangle opposite a vertex. The // triangle opposite vertex j is // <oppositeFace[j][0], oppositeFace[j][1], oppositeFace[j][2]> // and is listed in counterclockwise order when viewed from outside // the tetrahedron. static inline std::array<std::array<int32_t, 3>, 4> const& GetOppositeFace() { static std::array<std::array<int32_t, 3>, 4> const sOppositeFace = {{ { 1, 2, 3 }, { 0, 3, 2 }, { 0, 1, 3 }, { 0, 2, 1 } }}; return sOppositeFace; } private: template <bool Dummy = Ordered> typename std::enable_if<Dummy, void>::type Initialize(int32_t v0, int32_t v1, int32_t v2, int32_t v3) { int32_t imin = 0; this->V[0] = v0; if (v1 < this->V[0]) { this->V[0] = v1; imin = 1; } if (v2 < this->V[0]) { this->V[0] = v2; imin = 2; } if (v3 < this->V[0]) { this->V[0] = v3; imin = 3; } if (imin == 0) { Permute(v1, v2, v3); } else if (imin == 1) { Permute(v0, v3, v2); } else if (imin == 2) { Permute(v0, v1, v3); } else // imin == 3 { Permute(v0, v2, v1); } } template <bool Dummy = Ordered> typename std::enable_if<!Dummy, void>::type Initialize(int32_t v0, int32_t v1, int32_t v2, int32_t v3) { this->V[0] = v0; this->V[1] = v1; this->V[2] = v2; this->V[3] = v3; std::sort(this->V.begin(), this->V.end()); } template <bool Dummy = Ordered> typename std::enable_if<Dummy, void>::type Permute(int32_t u0, int32_t u1, int32_t u2) { // Once V[0] is determined, create a permutation // (V[1], V[2], V[3]) so that (V[0], V[1], V[2], V[3]) is a // permutation of (v0, v1, v2, v3) that corresponds to the // identity matrix as mentioned in the comments at the beginning // of this file. if (u0 < u1) { if (u0 < u2) { // u0 is minimum this->V[1] = u0; this->V[2] = u1; this->V[3] = u2; } else { // u2 is minimum this->V[1] = u2; this->V[2] = u0; this->V[3] = u1; } } else { if (u1 < u2) { // u1 is minimum this->V[1] = u1; this->V[2] = u2; this->V[3] = u0; } else { // u2 is minimum this->V[1] = u2; this->V[2] = u0; this->V[3] = u1; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CurvatureFlow2.h
.h
1,875
57
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/PdeFilter2.h> namespace gte { template <typename Real> class CurvatureFlow2 : public PdeFilter2<Real> { public: CurvatureFlow2(int32_t xBound, int32_t yBound, Real xSpacing, Real ySpacing, Real const* data, int32_t const* mask, Real borderValue, typename PdeFilter<Real>::ScaleType scaleType) : PdeFilter2<Real>(xBound, yBound, xSpacing, ySpacing, data, mask, borderValue, scaleType) { } virtual ~CurvatureFlow2() { } protected: virtual void OnUpdateSingle(int32_t x, int32_t y) override { this->LookUp9(x, y); Real ux = this->mHalfInvDx * (this->mUpz - this->mUmz); Real uy = this->mHalfInvDy * (this->mUzp - this->mUzm); Real uxx = this->mInvDxDx * (this->mUpz - (Real)2 * this->mUzz + this->mUmz); Real uxy = this->mFourthInvDxDy * (this->mUmm + this->mUpp - this->mUmp - this->mUpm); Real uyy = this->mInvDyDy * (this->mUzp - (Real)2 * this->mUzz + this->mUzm); Real sqrUx = ux * ux; Real sqrUy = uy * uy; Real denom = sqrUx + sqrUy; if (denom > (Real)0) { Real numer = uxx * sqrUy + uyy * sqrUx - (Real)0.5 * uxy * ux * uy; this->mBuffer[this->mDst][y][x] = this->mUzz + this->mTimeStep * numer / denom; } else { this->mBuffer[this->mDst][y][x] = this->mUzz; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CanonicalBox.h
.h
3,231
106
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector.h> // A canonical box has center at the origin and is aligned with the standard // Euclidean basis vectors. It has E = (e[0],e[1],...,e[N-1]) with e[i] >= 0 // for all i. A zero extent is allowed, meaning the box is degenerate in the // corresponding direction. A box point is X = (x[0],x[1],...,x[N-1]) with // |x[i]| <= e[i] for all i. namespace gte { template <int32_t N, typename T> class CanonicalBox { public: // Construction. The default constructor sets all members to zero. CanonicalBox() : extent{} { } CanonicalBox(Vector<N, T> const& inExtent) : extent(inExtent) { } // Compute the vertices of the box. If index i has the bit pattern // i = b[N-1]...b[0], then the corner at index i is // vertex[i] = center + sum_{d=0}^{N-1} sign[d]*extent[d]*axis[d] // where sign[d] = 2*b[d] - 1. void GetVertices(std::array<Vector<N, T>, (1 << N)>& vertex) const { int32_t const imax = (1 << N); for (int32_t i = 0; i < imax; ++i) { vertex[i].MakeZero(); for (int32_t d = 0, mask = 1; d < N; ++d, mask <<= 1) { if ((i & mask) > 0) { vertex[i][d] += extent[d]; } else { vertex[i][d] -= extent[d]; } } } } // It is required that extent[i] >= 0. Vector<N, T> extent; }; // Comparisons to support sorted containers. template <typename T, size_t N> bool operator==(CanonicalBox<N, T> const& box0, CanonicalBox<N, T> const& box1) { return box0.extent == box1.extent; } template <typename T, size_t N> bool operator!=(CanonicalBox<N, T> const& box0, CanonicalBox<N, T> const& box1) { return !operator==(box0, box1); } template <typename T, size_t N> bool operator<(CanonicalBox<N, T> const& box0, CanonicalBox<N, T> const& box1) { return box0.extent < box1.extent; } template <typename T, size_t N> bool operator<=(CanonicalBox<N, T> const& box0, CanonicalBox<N, T> const& box1) { return !operator<(box1, box0); } template <typename T, size_t N> bool operator>(CanonicalBox<N, T> const& box0, CanonicalBox<N, T> const& box1) { return operator<(box1, box0); } template <typename T, size_t N> bool operator>=(CanonicalBox<N, T> const& box0, CanonicalBox<N, T> const& box1) { return !operator<(box0, box1); } // Template aliases for convenience. template <typename T> using CanonicalBox2 = CanonicalBox<2, T>; template <typename T> using CanonicalBox3 = CanonicalBox<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrHalfspace3Cylinder3.h
.h
1,754
54
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/TIQuery.h> #include <Mathematics/Cylinder3.h> #include <Mathematics/Halfspace.h> // Queries for intersection of objects with halfspaces. These are useful for // containment testing, object culling, and clipping. namespace gte { template <typename T> class TIQuery<T, Halfspace3<T>, Cylinder3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Halfspace3<T> const& halfspace, Cylinder3<T> const& cylinder) { Result result{}; // Compute extremes of signed distance Dot(N,X)-d for points on // the cylinder. These are // min = (Dot(N,C)-d) - r*sqrt(1-Dot(N,W)^2) - (h/2)*|Dot(N,W)| // max = (Dot(N,C)-d) + r*sqrt(1-Dot(N,W)^2) + (h/2)*|Dot(N,W)| T center = Dot(halfspace.normal, cylinder.axis.origin) - halfspace.constant; T absNdW = std::fabs(Dot(halfspace.normal, cylinder.axis.direction)); T root = std::sqrt(std::max((T)1, (T)1 - absNdW * absNdW)); T tmax = center + cylinder.radius * root + (T)0.5 * cylinder.height * absNdW; // The cylinder and halfspace intersect when the projection // interval maximum is nonnegative. result.intersect = (tmax >= (T)0); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OdeSolver.h
.h
1,671
57
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/GVector.h> #include <functional> // The differential equation is dx/dt = F(t,x). The TVector template // parameter allows you to create solvers with Vector<N,Real> when the // dimension N is known at compile time or GVector<Real> when the dimension // N is known at run time. Both classes have 'int32_t GetSize() const' that // allow OdeSolver-derived classes to query for the dimension. namespace gte { template <typename Real, typename TVector> class OdeSolver { public: // Abstract base class. virtual ~OdeSolver() = default; protected: OdeSolver(Real tDelta, std::function<TVector(Real, TVector const&)> const& F) : mTDelta(tDelta), mFunction(F) { } public: // Member access. inline void SetTDelta(Real tDelta) { mTDelta = tDelta; } inline Real GetTDelta() const { return mTDelta; } // Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). The // derived classes implement this so that it is possible for xIn and // xOut to be the same object. virtual void Update(Real tIn, TVector const& xIn, Real& tOut, TVector& xOut) = 0; protected: Real mTDelta; std::function<TVector(Real, TVector const&)> mFunction; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprOrthogonalPlane3.h
.h
4,952
132
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.17 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/SymmetricEigensolver3x3.h> #include <Mathematics/Vector3.h> // Least-squares fit of a plane to (x,y,z) data by using distance measurements // orthogonal to the proposed plane. The return value is 'true' if and only if // the fit is unique (always successful, 'true' when a minimum eigenvalue is // unique). The mParameters value is (P,N) = (origin,normal). The error for // S = (x0,y0,z0) is (S-P)^T*(I - N*N^T)*(S-P). namespace gte { template <typename Real> class ApprOrthogonalPlane3 : public ApprQuery<Real, Vector3<Real>> { public: // Initialize the model parameters to zero. ApprOrthogonalPlane3() { mParameters.first = Vector3<Real>::Zero(); mParameters.second = Vector3<Real>::Zero(); } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numPoints, Vector3<Real> const* points, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numPoints, points, numIndices, indices)) { // Compute the mean of the points. Vector3<Real> mean = Vector3<Real>::Zero(); int32_t const* currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { mean += points[*currentIndex++]; } Real invSize = (Real)1 / (Real)numIndices; mean *= invSize; if (std::isfinite(mean[0]) && std::isfinite(mean[1]) && std::isfinite(mean[2])) { // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (Real)0; currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { Vector3<Real> diff = points[*currentIndex++] - mean; covar00 += diff[0] * diff[0]; covar01 += diff[0] * diff[1]; covar02 += diff[0] * diff[2]; covar11 += diff[1] * diff[1]; covar12 += diff[1] * diff[2]; covar22 += diff[2] * diff[2]; } covar00 *= invSize; covar01 *= invSize; covar02 *= invSize; covar11 *= invSize; covar12 *= invSize; covar22 *= invSize; // Solve the eigensystem. SymmetricEigensolver3x3<Real> es; std::array<Real, 3> eval; std::array<std::array<Real, 3>, 3> evec; es(covar00, covar01, covar02, covar11, covar12, covar22, false, +1, eval, evec); // The plane normal is the eigenvector in the direction of // smallest variance of the points. mParameters.first = mean; mParameters.second = evec[0]; // The fitted plane is unique when the minimum eigenvalue // has multiplicity 1. return eval[0] < eval[1]; } } mParameters.first = Vector3<Real>::Zero(); mParameters.second = Vector3<Real>::Zero(); return false; } // Get the parameters for the best fit. std::pair<Vector3<Real>, Vector3<Real>> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return 3; } virtual Real Error(Vector3<Real> const& point) const override { Vector3<Real> diff = point - mParameters.first; Real sqrlen = Dot(diff, diff); Real dot = Dot(diff, mParameters.second); Real error = std::fabs(sqrlen - dot * dot); return error; } virtual void CopyParameters(ApprQuery<Real, Vector3<Real>> const* input) override { auto source = dynamic_cast<ApprOrthogonalPlane3<Real> const*>(input); if (source) { *this = *source; } } private: std::pair<Vector3<Real>, Vector3<Real>> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/QFNumber.h
.h
12,446
409
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> // Class QFNumber is an implementation for quadratic fields with N >= 1 // square root terms. The theory and details are provided in // https://www.geometrictools.com/Documentation/QuadraticFields.pdf // Enable this macro if you want the logging system to trap when arithmetic // operations are performed on two quadratic elements that do not share the // same value d #define GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D namespace gte { // Arithmetic for quadratic fields with N >= 2 square root terms. The // d-term is rational and the x-coefficients are elements in a quadratic // field with N-1 >= 1 square root terms. template <typename T, size_t N> class QFNumber { public: // The quadratic field numbers is x[0] + x[1] * sqrt(d). std::array<QFNumber<T, N - 1>, 2> x; T d; // Create z = 0 + 0 * sqrt(0), where the 0 coefficients are quadratic // field elements with N-1 d-terms all set to 0 and x-coefficients all // set to 0. QFNumber() : d(0) { static_assert(N >= 2, "Invalid number of root arguments."); } // Create z = 0 + 0 * sqrt(d), where the 0 coefficients are quadratic // field elements with N-1 d-terms all set to 0 and x-coefficients all // set to 0. explicit QFNumber(T const& inD) : d(inD) { static_assert(N >= 2, "Invalid number of root arguments."); } // Create z = x0 + x1 * sqrt(d), where the x-coefficients are // quadratic field elements with N-1 d-terms. QFNumber(QFNumber<T, N - 1> const& x0, QFNumber<T, N - 1> const& x1, T const& inD) : x{ x0, x1 }, d(inD) { static_assert(N >= 2, "Invalid number of root arguments."); } // Create z = inX[0] + inX[1] * sqrt(inD), where the x-coefficients are // quadratic field elements with N-1 d-terms. QFNumber(std::array<QFNumber<T, N - 1>, 2> const& inX, T const& inD) : x(inX), d(inD) { static_assert(N >= 2, "Invalid number of root arguments."); } }; // Arithmetic for quadratic fields with 1 square root term. template <typename T> class QFNumber<T, 1> { public: // The quadratic field number is x[0] + x[1] * sqrt(d). std::array<T, 2> x; T d; // Create z = 0. You can defer the setting of d until later. QFNumber() : x{ static_cast<T>(0), static_cast<T>(0) }, d(static_cast<T>(0)) { } // Create z = 0 + 0 * sqrt(d) = 0. explicit QFNumber(T const& inD) : x{ static_cast<T>(0), static_cast<T>(0) }, d(inD) { } // Create z = x0 + x1 * sqrt(d). QFNumber(T const& x0, T const& x1, T const& inD) : x{ x0, x1 }, d(inD) { } // Create z = inX[0] + inX[1] * sqrt(d). QFNumber(std::array<T, 2> const& inX, T const& inD) : x(inX), d(inD) { } }; // Unary operations. template <typename T, size_t N> QFNumber<T, N> operator+(QFNumber<T, N> const& q) { static_assert(N >= 1, "Invalid number of d-terms."); return q; } template <typename T, size_t N> QFNumber<T, N> operator-(QFNumber<T, N> const& q) { static_assert(N >= 1, "Invalid number of d-terms."); return QFNumber<T, N>(-q.x[0], -q.x[1], q.d); } // Arithmetic operations between elements of a quadratic field must occur // only when the d-values are the same. To trap mismatches, read the // comments at the beginning of this file. template <typename T, size_t N> QFNumber<T, N> operator+(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif return QFNumber<T, N>(q0.x[0] + q1.x[0], q0.x[1] + q1.x[1], q0.d); } template <typename T, size_t N> QFNumber<T, N> operator+(QFNumber<T, N> const& q, T const& s) { return QFNumber<T, N>(q.x[0] + s, q.x[1], q.d); } template <typename T, size_t N> QFNumber<T, N> operator+(T const& s, QFNumber<T, N> const& q) { return QFNumber<T, N>(s + q.x[0], q.x[1], q.d); } template <typename T, size_t N> QFNumber<T, N> operator-(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif return QFNumber<T, N>(q0.x[0] - q1.x[0], q0.x[1] - q1.x[1], q0.d); } template <typename T, size_t N> QFNumber<T, N> operator-(QFNumber<T, N> const& q, T const& s) { return QFNumber<T, N>(q.x[0] - s, q.x[1], q.d); } template <typename T, size_t N> QFNumber<T, N> operator-(T const& s, QFNumber<T, N> const& q) { return QFNumber<T, N>(s - q.x[0], -q.x[1], q.d); } template <typename T, size_t N> QFNumber<T, N> operator*(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif return QFNumber<T, N>( q0.x[0] * q1.x[0] + q0.x[1] * q1.x[1] * q0.d, q0.x[0] * q1.x[1] + q0.x[1] * q1.x[0], q0.d); } template <typename T, size_t N> QFNumber<T, N> operator*(QFNumber<T, N> const& q, T const& s) { return QFNumber<T, N>(q.x[0] * s, q.x[1] * s, q.d); } template <typename T, size_t N> QFNumber<T, N> operator*(T const& s, QFNumber<T, N> const& q) { return QFNumber<T, N>(s * q.x[0], s * q.x[1], q.d); } template <typename T, size_t N> QFNumber<T, N> operator/(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif auto denom = q1.x[0] * q1.x[0] - q1.x[1] * q1.x[1] * q0.d; auto numer0 = q0.x[0] * q1.x[0] - q0.x[1] * q1.x[1] * q0.d; auto numer1 = q0.x[1] * q1.x[0] - q0.x[0] * q1.x[1]; return QFNumber<T, N>(numer0 / denom, numer1 / denom, q0.d); } template <typename T, size_t N> QFNumber<T, N> operator/(QFNumber<T, N> const& q, T const& s) { return QFNumber<T, N>(q.x[0] / s, q.x[1] / s, q.d); } template <typename T, size_t N> QFNumber<T, N> operator/(T const& s, QFNumber<T, N> const& q) { auto denom = q.x[0] * q.x[0] - q.x[1] * q.x[1] * q.d; auto x0 = (s * q.x[0]) / denom; auto x1 = -(s * q.x[1]) / denom; return QFNumber<T, N>(x0, x1, q.d); } // Arithmetic updates between elements of a quadratic field must occur // only when the d-values are the same. To trap mismatches, read the // comments at the beginning of this file. template <typename T, size_t N> QFNumber<T, N>& operator+=(QFNumber<T, N>& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif q0.x[0] += q1.x[0]; q0.x[1] += q1.x[1]; return q0; } template <typename T, size_t N> QFNumber<T, N>& operator+=(QFNumber<T, N>& q, T const& s) { q.x[0] += s; return q; } template <typename T, size_t N> QFNumber<T, N>& operator-=(QFNumber<T, N>& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif q0.x[0] -= q1.x[0]; q0.x[1] -= q1.x[1]; return q0; } template <typename T, size_t N> QFNumber<T, N>& operator-=(QFNumber<T, N>& q, T const& s) { q.x[0] -= s; return q; } template <typename T, size_t N> QFNumber<T, N>& operator*=(QFNumber<T, N>& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif auto x0 = q0.x[0] * q1.x[0] + q0.x[1] * q1.x[1] * q0.d; auto x1 = q0.x[0] * q1.x[1] + q0.x[1] * q1.x[0]; q0.x[0] = x0; q0.x[1] = x1; return q0; } template <typename T, size_t N> QFNumber<T, N>& operator*=(QFNumber<T, N>& q, T const& s) { q.x[0] *= s; q.x[1] *= s; return q; } template <typename T, size_t N> QFNumber<T, N>& operator/=(QFNumber<T, N>& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif auto denom = q1.x[0] * q1.x[0] - q1.x[1] * q1.x[1] * q0.d; auto numer0 = q0.x[0] * q1.x[0] - q0.x[1] * q1.x[1] * q0.d; auto numer1 = q0.x[1] * q1.x[0] - q0.x[0] * q1.x[1]; q0.x[0] = numer0 / denom; q0.x[1] = numer1 / denom; return q0; } template <typename T, size_t N> QFNumber<T, N>& operator/=(QFNumber<T, N>& q, T const& s) { q.x[0] /= s; q.x[1] /= s; return q; } // Comparisons between numbers of a quadratic field must occur only when // the d-values are the same. To trap mismatches, read the comments at // the beginning of this file. template <typename T, size_t N> bool operator==(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif if (q0.d == T(0) || q0.x[1] == q1.x[1]) { return q0.x[0] == q1.x[0]; } else if (q0.x[1] > q1.x[1]) { if (q0.x[0] >= q1.x[0]) { return false; } else // q0.x[0] < q1.x[0] { auto diff = q0 - q1; return diff.x[0] * diff.x[0] == diff.x[1] * diff.x[1] * diff.d; } } else // q0.x[1] < q1.x[1] { if (q0.x[0] <= q1.x[0]) { return false; } else // q0.x[0] > q1.x[0] { auto diff = q0 - q1; return diff.x[0] * diff.x[0] == diff.x[1] * diff.x[1] * diff.d; } } } template <typename T, size_t N> bool operator!=(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { return !operator==(q0, q1); } template <typename T, size_t N> bool operator<(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { #if defined(GTE_ASSERT_ON_QFNUMBER_MISMATCHED_D) LogAssert(q0.d == q1.d, "Mismatched d-value."); #endif if (q0.d == T(0) || q0.x[1] == q1.x[1]) { return q0.x[0] < q1.x[0]; } else if (q0.x[1] > q1.x[1]) { if (q0.x[0] >= q1.x[0]) { return false; } else // q0.x[0] < q1.x[0] { auto diff = q0 - q1; return diff.x[0] * diff.x[0] > diff.x[1] * diff.x[1] * diff.d; } } else // q0.x[1] < q1.x[1] { if (q0.x[0] <= q1.x[0]) { return true; } else // q0.x[0] > q1.x[0] { auto diff = q0 - q1; return diff.x[0] * diff.x[0] < diff.x[1] * diff.x[1] * diff.d; } } } template <typename T, size_t N> bool operator>(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { return operator<(q1, q0); } template <typename T, size_t N> bool operator<=(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { return !operator<(q1, q0); } template <typename T, size_t N> bool operator>=(QFNumber<T, N> const& q0, QFNumber<T, N> const& q1) { return !operator<(q0, q1); } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FrenetFrame.h
.h
3,967
133
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ParametricCurve.h> #include <Mathematics/Vector2.h> #include <Mathematics/Vector3.h> #include <memory> namespace gte { template <typename Real> class FrenetFrame2 { public: // Construction. The curve must persist as long as the FrenetFrame2 // object does. FrenetFrame2(std::shared_ptr<ParametricCurve<2, Real>> const& curve) : mCurve(curve) { } // The normal is perpendicular to the tangent, rotated clockwise by // pi/2 radians. void operator()(Real t, Vector2<Real>& position, Vector2<Real>& tangent, Vector2<Real>& normal) const { std::array<Vector2<Real>, 2> jet; mCurve->Evaluate(t, 1, jet.data()); position = jet[0]; tangent = jet[1]; Normalize(tangent); normal = Perp(tangent); } Real GetCurvature(Real t) const { std::array<Vector2<Real>, 3> jet; mCurve->Evaluate(t, 2, jet.data()); Real speedSqr = Dot(jet[1], jet[1]); if (speedSqr > (Real)0) { Real numer = DotPerp(jet[1], jet[2]); Real denom = std::pow(speedSqr, (Real)1.5); return numer / denom; } else { // Curvature is indeterminate, just return 0. return (Real)0; } } private: std::shared_ptr<ParametricCurve<2, Real>> mCurve; }; template <typename Real> class FrenetFrame3 { public: // Construction. The curve must persist as long as the FrenetFrame3 // object does. FrenetFrame3(std::shared_ptr<ParametricCurve<3, Real>> const& curve) : mCurve(curve) { } // The binormal is Cross(tangent, normal). void operator()(Real t, Vector3<Real>& position, Vector3<Real>& tangent, Vector3<Real>& normal, Vector3<Real>& binormal) const { std::array<Vector3<Real>, 3> jet; mCurve->Evaluate(t, 2, jet.data()); position = jet[0]; Real VDotV = Dot(jet[1], jet[1]); Real VDotA = Dot(jet[1], jet[2]); normal = VDotV * jet[2] - VDotA * jet[1]; Normalize(normal); tangent = jet[1]; Normalize(tangent); binormal = Cross(tangent, normal); } Real GetCurvature(Real t) const { std::array<Vector3<Real>, 3> jet; mCurve->Evaluate(t, 2, jet.data()); Real speedSqr = Dot(jet[1], jet[1]); if (speedSqr > (Real)0) { Real numer = Length(Cross(jet[1], jet[2])); Real denom = std::pow(speedSqr, (Real)1.5); return numer / denom; } else { // Curvature is indeterminate, just return 0. return (Real)0; } } Real GetTorsion(Real t) const { std::array<Vector3<Real>, 4> jet; mCurve->Evaluate(t, 3, jet.data()); Vector3<Real> cross = Cross(jet[1], jet[2]); Real denom = Dot(cross, cross); if (denom > (Real)0) { Real numer = Dot(cross, jet[3]); return numer / denom; } else { // Torsion is indeterminate, just return 0. return (Real)0; } } private: std::shared_ptr<ParametricCurve<3, Real>> mCurve; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContLozenge3.h
.h
6,764
215
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprGaussian3.h> #include <Mathematics/DistPointRectangle.h> #include <Mathematics/Lozenge3.h> namespace gte { // Compute the plane of the lozenge rectangle using least-squares fit. // Parallel planes are chosen close enough together so that all the data // points lie between them. The radius is half the distance between the // two planes. The half-cylinder and quarter-cylinder side pieces are // chosen using a method similar to that used for fitting by capsules. template <typename Real> bool GetContainer(int32_t numPoints, Vector3<Real> const* points, Lozenge3<Real>& lozenge) { ApprGaussian3<Real> fitter; fitter.Fit(numPoints, points); OrientedBox3<Real> box = fitter.GetParameters(); Vector3<Real> diff = points[0] - box.center; Real wMin = Dot(box.axis[0], diff); Real wMax = wMin; Real w; for (int32_t i = 1; i < numPoints; ++i) { diff = points[i] - box.center; w = Dot(box.axis[0], diff); if (w < wMin) { wMin = w; } else if (w > wMax) { wMax = w; } } Real radius = (Real)0.5 * (wMax - wMin); Real rSqr = radius * radius; box.center += ((Real)0.5 * (wMax + wMin)) * box.axis[0]; Real aMin = std::numeric_limits<Real>::max(); Real aMax = -aMin; Real bMin = std::numeric_limits<Real>::max(); Real bMax = -bMin; Real discr, radical, u, v, test; for (int32_t i = 0; i < numPoints; ++i) { diff = points[i] - box.center; u = Dot(box.axis[2], diff); v = Dot(box.axis[1], diff); w = Dot(box.axis[0], diff); discr = rSqr - w * w; radical = std::sqrt(std::max(discr, (Real)0)); test = u + radical; if (test < aMin) { aMin = test; } test = u - radical; if (test > aMax) { aMax = test; } test = v + radical; if (test < bMin) { bMin = test; } test = v - radical; if (test > bMax) { bMax = test; } } // The enclosing region might be a capsule or a sphere. if (aMin >= aMax) { test = (Real)0.5 * (aMin + aMax); aMin = test; aMax = test; } if (bMin >= bMax) { test = (Real)0.5 * (bMin + bMax); bMin = test; bMax = test; } // Make correction for points inside mitered corner but outside quarter // sphere. for (int32_t i = 0; i < numPoints; ++i) { diff = points[i] - box.center; u = Dot(box.axis[2], diff); v = Dot(box.axis[1], diff); Real* aExtreme = nullptr; Real* bExtreme = nullptr; if (u > aMax) { if (v > bMax) { aExtreme = &aMax; bExtreme = &bMax; } else if (v < bMin) { aExtreme = &aMax; bExtreme = &bMin; } } else if (u < aMin) { if (v > bMax) { aExtreme = &aMin; bExtreme = &bMax; } else if (v < bMin) { aExtreme = &aMin; bExtreme = &bMin; } } if (aExtreme) { Real deltaU = u - *aExtreme; Real deltaV = v - *bExtreme; Real deltaSumSqr = deltaU * deltaU + deltaV * deltaV; w = Dot(box.axis[0], diff); Real wSqr = w * w; test = deltaSumSqr + wSqr; if (test > rSqr) { discr = (rSqr - wSqr) / deltaSumSqr; Real t = -std::sqrt(std::max(discr, (Real)0)); *aExtreme = u + t * deltaU; *bExtreme = v + t * deltaV; } } } lozenge.radius = radius; lozenge.rectangle.axis[0] = box.axis[2]; lozenge.rectangle.axis[1] = box.axis[1]; if (aMin < aMax) { if (bMin < bMax) { // Container is a lozenge. lozenge.rectangle.center = box.center + aMin * box.axis[2] + bMin * box.axis[1]; lozenge.rectangle.extent[0] = (Real)0.5 * (aMax - aMin); lozenge.rectangle.extent[1] = (Real)0.5 * (bMax - bMin); } else { // Container is a capsule. lozenge.rectangle.center = box.center + aMin * box.axis[2] + ((Real)0.5 * (bMin + bMax)) * box.axis[1]; lozenge.rectangle.extent[0] = (Real)0.5 * (aMax - aMin); lozenge.rectangle.extent[1] = (Real)0; } } else { if (bMin < bMax) { // Container is a capsule. lozenge.rectangle.center = box.center + bMin * box.axis[1] + ((Real)0.5 * (aMin + aMax)) * box.axis[2]; lozenge.rectangle.extent[0] = (Real)0; lozenge.rectangle.extent[1] = (Real)0.5 * (bMax - bMin); } else { // Container is a sphere. lozenge.rectangle.center = box.center + ((Real)0.5 * (aMin + aMax)) * box.axis[2] + ((Real)0.5 * (bMin + bMax)) * box.axis[1]; lozenge.rectangle.extent[0] = (Real)0; lozenge.rectangle.extent[1] = (Real)0; } } return true; } // Test for containment of a point by a lozenge. template <typename Real> bool InContainer(Vector3<Real> const& point, Lozenge3<Real> const& lozenge) { DCPQuery<Real, Vector3<Real>, Rectangle3<Real>> prQuery; auto result = prQuery(point, lozenge.rectangle); return result.distance <= lozenge.radius; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Hyperellipsoid.h
.h
11,978
349
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/SymmetricEigensolver.h> // A hyperellipsoid has center K; axis directions U[0] through U[N-1], all // unit-length vectors; and extents e[0] through e[N-1], all positive numbers. // A point X = K + sum_{d=0}^{N-1} y[d]*U[d] is on the hyperellipsoid whenever // sum_{d=0}^{N-1} (y[d]/e[d])^2 = 1. An algebraic representation for the // hyperellipsoid is (X-K)^T * M * (X-K) = 1, where M is the NxN symmetric // matrix M = sum_{d=0}^{N-1} U[d]*U[d]^T/e[d]^2, where the superscript T // denotes transpose. Observe that U[i]*U[i]^T is a matrix, not a scalar dot // product. The hyperellipsoid is also represented by a quadratic equation // 0 = C + B^T*X + X^T*A*X, where C is a scalar, B is an Nx1 vector, and A is // an NxN symmetric matrix with positive eigenvalues. The coefficients can be // stored from lowest degree to highest degree, // C = k[0] // B = k[1], ..., k[N] // A = k[N+1], ..., k[(N+1)(N+2)/2 - 1] // where the A-coefficients are the upper-triangular elements of A listed in // row-major order. For N = 2, X = (x[0],x[1]) and // 0 = k[0] + // k[1]*x[0] + k[2]*x[1] + // k[3]*x[0]*x[0] + k[4]*x[0]*x[1] // + k[5]*x[1]*x[1] // For N = 3, X = (x[0],x[1],x[2]) and // 0 = k[0] + // k[1]*x[0] + k[2]*x[1] + k[3]*x[2] + // k[4]*x[0]*x[0] + k[5]*x[0]*x[1] + k[6]*x[0]*x[2] + // + k[7]*x[1]*x[1] + k[8]*x[1]*x[2] + // + k[9]*x[2]*x[2] // This equation can be factored to the form (X-K)^T * M * (X-K) = 1, where // K = -A^{-1}*B/2, M = A/(B^T*A^{-1}*B/4-C). namespace gte { template <int32_t N, typename Real> class Hyperellipsoid { public: // Construction and destruction. The default constructor sets the // center to Vector<N,Real>::Zero(), the axes to // Vector<N,Real>::Unit(d), and all extents to 1. Hyperellipsoid() { center.MakeZero(); for (int32_t d = 0; d < N; ++d) { axis[d].MakeUnit(d); extent[d] = (Real)1; } } Hyperellipsoid(Vector<N, Real> const& inCenter, std::array<Vector<N, Real>, N> const inAxis, Vector<N, Real> const& inExtent) : center(inCenter), axis(inAxis), extent(inExtent) { } // Compute M = sum_{d=0}^{N-1} U[d]*U[d]^T/e[d]^2. void GetM(Matrix<N, N, Real>& M) const { M.MakeZero(); for (int32_t d = 0; d < N; ++d) { Vector<N, Real> ratio = axis[d] / extent[d]; M += OuterProduct<N, N, Real>(ratio, ratio); } } // Compute M^{-1} = sum_{d=0}^{N-1} U[d]*U[d]^T*e[d]^2. void GetMInverse(Matrix<N, N, Real>& MInverse) const { MInverse.MakeZero(); for (int32_t d = 0; d < N; ++d) { Vector<N, Real> product = axis[d] * extent[d]; MInverse += OuterProduct<N, N, Real>(product, product); } } // Construct the coefficients in the quadratic equation that represents // the hyperellipsoid. void ToCoefficients(std::array<Real, (N + 1) * (N + 2) / 2>& coeff) const { int32_t const numCoefficients = (N + 1) * (N + 2) / 2; Matrix<N, N, Real> A{}; Vector<N, Real> B{}; Real C{}; ToCoefficients(A, B, C); Convert(A, B, C, coeff); // Arrange for one of the coefficients of the quadratic terms // to be 1. int32_t quadIndex = numCoefficients - 1; int32_t maxIndex = quadIndex; Real maxValue = std::fabs(coeff[quadIndex]); // NOTE: When N = 2, MSVS 2019 16+ generates: // warning C6294: Ill-defined for-loop: initial condition does // not satisfy test. Loop body not executed. // This is the correct behavior for N = 2. int32_t localN = N; if (localN >= 3) { for (int32_t d = 2; d < localN; ++d) { quadIndex -= d; Real absValue = std::fabs(coeff[quadIndex]); if (absValue > maxValue) { maxIndex = quadIndex; maxValue = absValue; } } } Real invMaxValue = (Real)1 / maxValue; for (int32_t i = 0; i < numCoefficients; ++i) { if (i != maxIndex) { coeff[i] *= invMaxValue; } else { coeff[i] = (Real)1; } } } void ToCoefficients(Matrix<N, N, Real>& A, Vector<N, Real>& B, Real& C) const { GetM(A); Vector<N, Real> product = A * center; B = (Real)-2 * product; C = Dot(center, product) - (Real)1; } // Construct C, U[i], and e[i] from the equation. The return value is // 'true' if and only if the input coefficients represent a // hyperellipsoid. If the function returns 'false', the hyperellipsoid // data members are undefined. bool FromCoefficients(std::array<Real, (N + 1) * (N + 2) / 2> const& coeff) { Matrix<N, N, Real> A{}; Vector<N, Real> B{}; Real C{}; Convert(coeff, A, B, C); return FromCoefficients(A, B, C); } bool FromCoefficients(Matrix<N, N, Real> const& A, Vector<N, Real> const& B, Real C) { // Compute the center K = -A^{-1}*B/2. bool invertible{}; Matrix<N, N, Real> invA = Inverse(A, &invertible); if (!invertible) { return false; } center = ((Real)-0.5) * (invA * B); // Compute B^T*A^{-1}*B/4 - C = K^T*A*K - C = -K^T*B/2 - C. Real rightSide = (Real)-0.5 * Dot(center, B) - C; if (rightSide == (Real)0) { return false; } // Compute M = A/(K^T*A*K - C). Real invRightSide = (Real)1 / rightSide; Matrix<N, N, Real> M = invRightSide * A; // Factor into M = R*D*R^T. M is symmetric, so it does not matter whether // the matrix is stored in row-major or column-major order; they are // equivalent. The output R, however, is in row-major order. SymmetricEigensolver<Real> es(N, 32); Matrix<N, N, Real> rotation; std::array<Real, N> diagonal; es.Solve(&M[0], +1); // diagonal[i] are nondecreasing es.GetEigenvalues(&diagonal[0]); es.GetEigenvectors(&rotation[0]); if (es.GetEigenvectorMatrixType() == 0) { auto negLast = -rotation.GetCol(N - 1); rotation.SetCol(N - 1, negLast); } for (int32_t d = 0; d < N; ++d) { if (diagonal[d] <= (Real)0) { return false; } extent[d] = (Real)1 / std::sqrt(diagonal[d]); axis[d] = rotation.GetCol(d); } return true; } // Public member access. Vector<N, Real> center; std::array<Vector<N, Real>, N> axis; Vector<N, Real> extent; private: static void Convert(std::array<Real, (N + 1) * (N + 2) / 2> const& coeff, Matrix<N, N, Real>& A, Vector<N, Real>& B, Real& C) { size_t i = 0; C = coeff[i++]; for (int32_t j = 0; j < N; ++j, ++i) { B[j] = coeff[i]; } i = N + 1; for (int32_t r = 0; r < N; ++r) { for (int32_t c = 0; c < r; ++c) { A(r, c) = A(c, r); } // NOTE: MSVS 2019 16+ generates for N = 2: // warning C28020: The expression // '0 <= _Param_(1)&&_Param(1)<=6-1' is not true at this // call. // A similar warning occurs for N = 3 (upper bound is 10-1). // The warning is incorrect. // // When r = N-1, i = (N+1)*(N+2)/2 - 1 which corresponds to // the last element of coeff[]. The assignment is valid. After // the assignment, i is incremented and now out of range for // coeff[]. However, the loop after the assignment starts at // c = N and the loop body is not executed, after which the // r-loop terminates. A(r, r) = coeff[i]; ++i; for (int32_t c = r + 1; c < N; ++c, ++i) { A(r, c) = coeff[i] * (Real)0.5; } } } static void Convert(Matrix<N, N, Real> const& A, Vector<N, Real> const& B, Real C, std::array<Real, (N + 1) * (N + 2) / 2> & coeff) { size_t i = 0; coeff[i++] = C; for (int32_t j = 0; j < N; ++j, ++i) { coeff[i] = B[j]; } // The structure of the following code avoids incorrect warnings // C28020 when using MSVS 2019 16.* on the previous implementation // of this function. i = N + 1; for (int32_t r = 0; r < N; ++r) { coeff[i] = A(r, r); ++i; for (int32_t c = r + 1; c < N && i < coeff.size(); ++c, ++i) { coeff[i] = A(r, c) * (Real)2; } } } public: // Comparisons to support sorted containers. bool operator==(Hyperellipsoid const& hyperellipsoid) const { return center == hyperellipsoid.center && axis == hyperellipsoid.axis && extent == hyperellipsoid.extent; } bool operator!=(Hyperellipsoid const& hyperellipsoid) const { return !operator==(hyperellipsoid); } bool operator< (Hyperellipsoid const& hyperellipsoid) const { if (center < hyperellipsoid.center) { return true; } if (center > hyperellipsoid.center) { return false; } if (axis < hyperellipsoid.axis) { return true; } if (axis > hyperellipsoid.axis) { return false; } return extent < hyperellipsoid.extent; } bool operator<=(Hyperellipsoid const& hyperellipsoid) const { return !hyperellipsoid.operator<(*this); } bool operator> (Hyperellipsoid const& hyperellipsoid) const { return hyperellipsoid.operator<(*this); } bool operator>=(Hyperellipsoid const& hyperellipsoid) const { return !operator<(hyperellipsoid); } }; // Template aliases for convenience. template <typename Real> using Ellipse2 = Hyperellipsoid<2, Real>; template <typename Real> using Ellipsoid3 = Hyperellipsoid<3, Real>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContCircle2.h
.h
2,712
89
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector2.h> #include <vector> namespace gte { // Compute the smallest bounding circle whose center is the average of // the input points. template <typename Real> bool GetContainer(int32_t numPoints, Vector2<Real> const* points, Circle2<Real>& circle) { circle.center = points[0]; for (int32_t i = 1; i < numPoints; ++i) { circle.center += points[i]; } circle.center /= (Real)numPoints; circle.radius = (Real)0; for (int32_t i = 0; i < numPoints; ++i) { Vector2<Real> diff = points[i] - circle.center; Real radiusSqr = Dot(diff, diff); if (radiusSqr > circle.radius) { circle.radius = radiusSqr; } } circle.radius = std::sqrt(circle.radius); return true; } template <typename Real> bool GetContainer(std::vector<Vector2<Real>> const& points, Circle2<Real>& circle) { return GetContainer(static_cast<int32_t>(points.size()), points.data(), circle); } // Test for containment of a point inside a circle. template <typename Real> bool InContainer(Vector2<Real> const& point, Circle2<Real> const& circle) { Vector2<Real> diff = point - circle.center; return Length(diff) <= circle.radius; } // Compute the smallest bounding circle that contains the input circles. template <typename Real> bool MergeContainers(Circle2<Real> const& circle0, Circle2<Real> const& circle1, Circle2<Real>& merge) { Vector2<Real> cenDiff = circle1.center - circle0.center; Real lenSqr = Dot(cenDiff, cenDiff); Real rDiff = circle1.radius - circle0.radius; Real rDiffSqr = rDiff * rDiff; if (rDiffSqr >= lenSqr) { merge = (rDiff >= (Real)0 ? circle1 : circle0); } else { Real length = std::sqrt(lenSqr); if (length > (Real)0) { Real coeff = (length + rDiff) / (((Real)2)*length); merge.center = circle0.center + coeff * cenDiff; } else { merge.center = circle0.center; } merge.radius = (Real)0.5 * (length + circle0.radius + circle1.radius); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrAlignedBox3Sphere3.h
.h
24,919
612
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistPointAlignedBox.h> #include <Mathematics/IntrRay3AlignedBox3.h> #include <Mathematics/Hypersphere.h> // The find-intersection query is based on the document // https://www.geometrictools.com/Documentation/IntersectionMovingSphereBox.pdf // and also uses the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf namespace gte { template <typename T> class TIQuery<T, AlignedBox3<T>, Sphere3<T>> { public: // The intersection query considers the box and sphere to be solids; // that is, the sphere object includes the region inside the spherical // boundary and the box object includes the region inside the cuboid // boundary. If the sphere object and box object object overlap, the // objects intersect. struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(AlignedBox3<T> const& box, Sphere3<T> const& sphere) { DCPQuery<T, Vector3<T>, AlignedBox3<T>> pbQuery; auto pbResult = pbQuery(sphere.center, box); Result result{}; result.intersect = (pbResult.sqrDistance <= sphere.radius * sphere.radius); return result; } }; template <typename T> class FIQuery<T, AlignedBox3<T>, Sphere3<T>> { public: // Currently, only a dynamic query is supported. A static query will // need to compute the intersection set of (solid) box and sphere. struct Result { Result() : intersectionType(0), contactTime(static_cast<T>(0)), contactPoint(Vector3<T>::Zero()) { } // The cases are // 1. Objects initially overlapping. The contactPoint is only one // of infinitely many points in the overlap. // intersectionType = -1 // contactTime = 0 // contactPoint = sphere.center // 2. Objects initially separated but do not intersect later. The // contactTime and contactPoint are invalid. // intersectionType = 0 // contactTime = 0 // contactPoint = (0,0,0) // 3. Objects initially separated but intersect later. // intersectionType = +1 // contactTime = first time T > 0 // contactPoint = corresponding first contact int32_t intersectionType; T contactTime; Vector3<T> contactPoint; // TODO: To support arbitrary precision for the contactTime, // return q0, q1 and q2 where contactTime = (q0 - sqrt(q1)) / q2. // The caller can compute contactTime to desired number of digits // of precision. These are valid when intersectionType is +1 but // are set to zero (invalid) in the other cases. Do the same for // the contactPoint. }; Result operator()(AlignedBox3<T> const& box, Vector3<T> const& boxVelocity, Sphere3<T> const& sphere, Vector3<T> const& sphereVelocity) { Result result{}; // Translate the sphere and box so that the box center becomes // the origin. Compute the velocity of the sphere relative to // the box. Vector3<T> boxCenter = (box.max + box.min) * (T)0.5; Vector3<T> extent = (box.max - box.min) * (T)0.5; Vector3<T> C = sphere.center - boxCenter; Vector3<T> V = sphereVelocity - boxVelocity; // Test for no-intersection that leads to an early exit. The test // is fast, using the method of separating axes. AlignedBox3<T> superBox; for (int32_t i = 0; i < 3; ++i) { superBox.max[i] = extent[i] + sphere.radius; superBox.min[i] = -superBox.max[i]; } TIQuery<T, Ray3<T>, AlignedBox3<T>> rbQuery; auto rbResult = rbQuery(Ray3<T>(C, V), superBox); if (rbResult.intersect) { DoQuery(extent, C, sphere.radius, V, result); // Translate the contact point back to the coordinate system // of the original sphere and box. result.contactPoint += boxCenter; } return result; } protected: // The query assumes the box is axis-aligned with center at the // origin. Callers need to convert the results back to the original // coordinate system of the query. void DoQuery(Vector3<T> const& K, Vector3<T> const& inC, T radius, Vector3<T> const& inV, Result& result) { // Change signs on components, if necessary, to transform C to the // first quadrant. Adjust the velocity accordingly. Vector3<T> C = inC, V = inV; std::array<T, 3> sign = { (T)0, (T)0, (T)0 }; for (int32_t i = 0; i < 3; ++i) { if (C[i] >= (T)0) { sign[i] = (T)1; } else { C[i] = -C[i]; V[i] = -V[i]; sign[i] = (T)-1; } } Vector3<T> delta = C - K; if (delta[2] <= radius) { if (delta[1] <= radius) { if (delta[0] <= radius) { if (delta[2] <= (T)0) { if (delta[1] <= (T)0) { if (delta[0] <= (T)0) { InteriorOverlap(C, result); } else { // x-face FaceOverlap(0, 1, 2, K, C, radius, delta, result); } } else { if (delta[0] <= (T)0) { // y-face FaceOverlap(1, 2, 0, K, C, radius, delta, result); } else { // xy-edge if (delta[0] * delta[0] + delta[1] * delta[1] <= radius * radius) { EdgeOverlap(0, 1, 2, K, C, radius, delta, result); } else { EdgeSeparated(0, 1, 2, K, C, radius, delta, V, result); } } } } else { if (delta[1] <= (T)0) { if (delta[0] <= (T)0) { // z-face FaceOverlap(2, 0, 1, K, C, radius, delta, result); } else { // xz-edge if (delta[0] * delta[0] + delta[2] * delta[2] <= radius * radius) { EdgeOverlap(2, 0, 1, K, C, radius, delta, result); } else { EdgeSeparated(2, 0, 1, K, C, radius, delta, V, result); } } } else { if (delta[0] <= (T)0) { // yz-edge if (delta[1] * delta[1] + delta[2] * delta[2] <= radius * radius) { EdgeOverlap(1, 2, 0, K, C, radius, delta, result); } else { EdgeSeparated(1, 2, 0, K, C, radius, delta, V, result); } } else { // xyz-vertex if (Dot(delta, delta) <= radius * radius) { VertexOverlap(K, radius, delta, result); } else { VertexSeparated(K, radius, delta, V, result); } } } } } else { // x-face FaceUnbounded(0, 1, 2, K, C, radius, delta, V, result); } } else { if (delta[0] <= radius) { // y-face FaceUnbounded(1, 2, 0, K, C, radius, delta, V, result); } else { // xy-edge EdgeUnbounded(0, 1, 2, K, C, radius, delta, V, result); } } } else { if (delta[1] <= radius) { if (delta[0] <= radius) { // z-face FaceUnbounded(2, 0, 1, K, C, radius, delta, V, result); } else { // xz-edge EdgeUnbounded(2, 0, 1, K, C, radius, delta, V, result); } } else { if (delta[0] <= radius) { // yz-edge EdgeUnbounded(1, 2, 0, K, C, radius, delta, V, result); } else { // xyz-vertex VertexUnbounded(K, C, radius, delta, V, result); } } } if (result.intersectionType != 0) { // Translate back to the coordinate system of the // tranlated box and sphere. for (int32_t i = 0; i < 3; ++i) { if (sign[i] < (T)0) { result.contactPoint[i] = -result.contactPoint[i]; } } } } private: void InteriorOverlap(Vector3<T> const& C, Result& result) { result.intersectionType = -1; result.contactTime = (T)0; result.contactPoint = C; } void VertexOverlap(Vector3<T> const& K, T radius, Vector3<T> const& delta, Result& result) { result.intersectionType = (Dot(delta, delta) < radius * radius ? -1 : 1); result.contactTime = (T)0; result.contactPoint = K; } void EdgeOverlap(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Result& result) { result.intersectionType = (delta[i0] * delta[i0] + delta[i1] * delta[i1] < radius * radius ? -1 : 1); result.contactTime = (T)0; result.contactPoint[i0] = K[i0]; result.contactPoint[i1] = K[i1]; result.contactPoint[i2] = C[i2]; } void FaceOverlap(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Result& result) { result.intersectionType = (delta[i0] < radius ? -1 : 1); result.contactTime = (T)0; result.contactPoint[i0] = K[i0]; result.contactPoint[i1] = C[i1]; result.contactPoint[i2] = C[i2]; } void VertexSeparated(Vector3<T> const& K, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { if (V[0] < (T)0 || V[1] < (T)0 || V[2] < (T)0) { DoQueryRayRoundedVertex(K, radius, delta, V, result); } } void EdgeSeparated(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { if (V[i0] < (T)0 || V[i1] < (T)0) { DoQueryRayRoundedEdge(i0, i1, i2, K, C, radius, delta, V, result); } } void VertexUnbounded(Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { if (V[0] < (T)0 && V[1] < (T)0 && V[2] < (T)0) { // Determine the face of the rounded box that is intersected // by the ray C+T*V. T tmax = (radius - delta[0]) / V[0]; int32_t j0 = 0; T temp = (radius - delta[1]) / V[1]; if (temp > tmax) { tmax = temp; j0 = 1; } temp = (radius - delta[2]) / V[2]; if (temp > tmax) { tmax = temp; j0 = 2; } // The j0-rounded face is the candidate for intersection. int32_t j1 = (j0 + 1) % 3; int32_t j2 = (j1 + 1) % 3; DoQueryRayRoundedFace(j0, j1, j2, K, C, radius, delta, V, result); } } void EdgeUnbounded(int32_t i0, int32_t i1, int32_t /* i2 */, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { if (V[i0] < (T)0 && V[i1] < (T)0) { // Determine the face of the rounded box that is intersected // by the ray C+T*V. T tmax = (radius - delta[i0]) / V[i0]; int32_t j0 = i0; T temp = (radius - delta[i1]) / V[i1]; if (temp > tmax) { tmax = temp; j0 = i1; } // The j0-rounded face is the candidate for intersection. int32_t j1 = (j0 + 1) % 3; int32_t j2 = (j1 + 1) % 3; DoQueryRayRoundedFace(j0, j1, j2, K, C, radius, delta, V, result); } } void FaceUnbounded(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { if (V[i0] < (T)0) { DoQueryRayRoundedFace(i0, i1, i2, K, C, radius, delta, V, result); } } void DoQueryRayRoundedVertex(Vector3<T> const& K, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { T a1 = Dot(V, delta); if (a1 < (T)0) { // The caller must ensure that a0 > 0 and a2 > 0. T a0 = Dot(delta, delta) - radius * radius; T a2 = Dot(V, V); T adiscr = a1 * a1 - a2 * a0; if (adiscr >= (T)0) { // The ray intersects the rounded vertex, so the sphere-box // contact point is the vertex. result.intersectionType = 1; result.contactTime = -(a1 + std::sqrt(adiscr)) / a2; result.contactPoint = K; } } } void DoQueryRayRoundedEdge(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { T b1 = V[i0] * delta[i0] + V[i1] * delta[i1]; if (b1 < (T)0) { // The caller must ensure that b0 > 0 and b2 > 0. T b0 = delta[i0] * delta[i0] + delta[i1] * delta[i1] - radius * radius; T b2 = V[i0] * V[i0] + V[i1] * V[i1]; T bdiscr = b1 * b1 - b2 * b0; if (bdiscr >= (T)0) { T tmax = -(b1 + std::sqrt(bdiscr)) / b2; T p2 = C[i2] + tmax * V[i2]; if (-K[i2] <= p2) { if (p2 <= K[i2]) { // The ray intersects the finite cylinder of the // rounded edge, so the sphere-box contact point // is on the corresponding box edge. result.intersectionType = 1; result.contactTime = tmax; result.contactPoint[i0] = K[i0]; result.contactPoint[i1] = K[i1]; result.contactPoint[i2] = p2; } else { // The ray intersects the infinite cylinder but // not the finite cylinder of the rounded edge. // It is possible the ray intersects the rounded // vertex for K. DoQueryRayRoundedVertex(K, radius, delta, V, result); } } else { // The ray intersects the infinite cylinder but // not the finite cylinder of the rounded edge. // It is possible the ray intersects the rounded // vertex for otherK. Vector3<T> otherK, otherDelta; otherK[i0] = K[i0]; otherK[i1] = K[i1]; otherK[i2] = -K[i2]; otherDelta[i0] = C[i0] - otherK[i0]; otherDelta[i1] = C[i1] - otherK[i1]; otherDelta[i2] = C[i2] - otherK[i2]; DoQueryRayRoundedVertex(otherK, radius, otherDelta, V, result); } } } } void DoQueryRayRoundedFace(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& K, Vector3<T> const& C, T radius, Vector3<T> const& delta, Vector3<T> const& V, Result& result) { Vector3<T> otherK, otherDelta; T tmax = (radius - delta[i0]) / V[i0]; T p1 = C[i1] + tmax * V[i1]; T p2 = C[i2] + tmax * V[i2]; if (p1 < -K[i1]) { // The ray potentially intersects the rounded (i0,i1)-edge // whose top-most vertex is otherK. otherK[i0] = K[i0]; otherK[i1] = -K[i1]; otherK[i2] = K[i2]; otherDelta[i0] = C[i0] - otherK[i0]; otherDelta[i1] = C[i1] - otherK[i1]; otherDelta[i2] = C[i2] - otherK[i2]; DoQueryRayRoundedEdge(i0, i1, i2, otherK, C, radius, otherDelta, V, result); if (result.intersectionType == 0) { if (p2 < -K[i2]) { // The ray potentially intersects the rounded // (i2,i0)-edge whose right-most vertex is otherK. otherK[i0] = K[i0]; otherK[i1] = K[i1]; otherK[i2] = -K[i2]; otherDelta[i0] = C[i0] - otherK[i0]; otherDelta[i1] = C[i1] - otherK[i1]; otherDelta[i2] = C[i2] - otherK[i2]; DoQueryRayRoundedEdge(i2, i0, i1, otherK, C, radius, otherDelta, V, result); } else if (p2 > K[i2]) { // The ray potentially intersects the rounded // (i2,i0)-edge whose right-most vertex is K. DoQueryRayRoundedEdge(i2, i0, i1, K, C, radius, delta, V, result); } } } else if (p1 <= K[i1]) { if (p2 < -K[i2]) { // The ray potentially intersects the rounded // (i2,i0)-edge whose right-most vertex is otherK. otherK[i0] = K[i0]; otherK[i1] = K[i1]; otherK[i2] = -K[i2]; otherDelta[i0] = C[i0] - otherK[i0]; otherDelta[i1] = C[i1] - otherK[i1]; otherDelta[i2] = C[i2] - otherK[i2]; DoQueryRayRoundedEdge(i2, i0, i1, otherK, C, radius, otherDelta, V, result); } else if (p2 <= K[i2]) { // The ray intersects the i0-face of the rounded box, so // the sphere-box contact point is on the corresponding // box face. result.intersectionType = 1; result.contactTime = tmax; result.contactPoint[i0] = K[i0]; result.contactPoint[i1] = p1; result.contactPoint[i2] = p2; } else // p2 > K[i2] { // The ray potentially intersects the rounded // (i2,i0)-edge whose right-most vertex is K. DoQueryRayRoundedEdge(i2, i0, i1, K, C, radius, delta, V, result); } } else // p1 > K[i1] { // The ray potentially intersects the rounded (i0,i1)-edge // whose top-most vertex is K. DoQueryRayRoundedEdge(i0, i1, i2, K, C, radius, delta, V, result); if (result.intersectionType == 0) { if (p2 < -K[i2]) { // The ray potentially intersects the rounded // (i2,i0)-edge whose right-most vertex is otherK. otherK[i0] = K[i0]; otherK[i1] = K[i1]; otherK[i2] = -K[i2]; otherDelta[i0] = C[i0] - otherK[i0]; otherDelta[i1] = C[i1] - otherK[i1]; otherDelta[i2] = C[i2] - otherK[i2]; DoQueryRayRoundedEdge(i2, i0, i1, otherK, C, radius, otherDelta, V, result); } else if (p2 > K[i2]) { // The ray potentially intersects the rounded // (i2,i0)-edge whose right-most vertex is K. DoQueryRayRoundedEdge(i2, i0, i1, K, C, radius, delta, V, result); } } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPlane3CanonicalBox3.h
.h
9,575
254
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Hyperplane.h> #include <Mathematics/CanonicalBox.h> // Compute the distance between a plane and a solid canonical box in 3D. // // The plane is defined by Dot(N, X - P) = 0, where P is the plane origin and // N is a unit-length normal for the plane. // // The canonical box has center at the origin and is aligned with the // coordinate axes. The extents are E = (e[0],e[1],e[2]). A box point is // Y = (y[0],y[1],y[2]) with |y[i]| <= e[i] for all i. // // The closest point on the plane is stored in closest[0]. The closest point // on the box is stored in closest[1]. When there are infinitely many choices // for the pair of closest points, only one of them is returned. // // TODO: Modify to support non-unit-length N. namespace gte { template <typename T> class DCPQuery<T, Plane3<T>, CanonicalBox3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<Vector3<T>, 2> closest; }; Result operator()(Plane3<T> const& plane, CanonicalBox3<T> const& box) { Result result{}; // Copies are made so that we can transform the plane normal to // the first octant (nonnegative components) using reflections. T const zero = static_cast<T>(0); Vector3<T> origin = plane.constant * plane.normal; Vector3<T> normal = plane.normal; std::array<bool, 3> reflect{ false, false }; for (int32_t i = 0; i < 3; ++i) { if (normal[i] < zero) { origin[i] = -origin[i]; normal[i] = -normal[i]; reflect[i] = true; } } // Compute the plane-box closest points. if (normal[0] > zero) { if (normal[1] > zero) { if (normal[2] > zero) { // The normal signs are (+,+,+). DoQuery3D(origin, normal, box.extent, result); } else { // The normal signs are (+,+,0). DoQuery2D(0, 1, 2, origin, normal, box.extent, result); } } else { if (normal[2] > zero) { // The normal signs are (+,0,+). DoQuery2D(0, 2, 1, origin, normal, box.extent, result); } else { // The normal signs are (+,0,0). The closest box point // is (x0,e1,e2) where x0 = clamp(p0,[-e0,e0]). The // closest plane point is (p0,e1,e2). DoQuery1D(0, 1, 2, origin, box.extent, result); } } } else { if (normal[1] > zero) { if (normal[2] > zero) { // The normal signs are (0,+,+). DoQuery2D(1, 2, 0, origin, normal, box.extent, result); } else { // The normal signs are (0,+,0). The closest box point // is (e0,x1,e2) where x1 = clamp(p1,[-e1,e1]). The // closest plane point is (e0,p1,e2). DoQuery1D(1, 2, 0, origin, box.extent, result); } } else { if (normal[2] > zero) { // The normal signs are (0,0,+) The closest box point // is (e0,e1,x2) where x2 = clamp(p2,[-e2,e2]). The // closest plane point is (e0,e1,p2). DoQuery1D(2, 0, 1, origin, box.extent, result); } else { // The normal signs are (0,0,0). Execute the DCP // query for the plane origin and the canonical box. // This is a low-probability event. DoQuery0D(plane.origin, box.extent, result); } } } // Undo the reflections. The origin and normal are not // consumed, so these do not need to be reflected. However, the // closest points are consumed. for (int32_t i = 0; i < 3; ++i) { if (reflect[i]) { for (size_t j = 0; j < 2; ++j) { result.closest[j][i] = -result.closest[j][i]; } } } Vector3<T> diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } private: static void DoQuery3D(Vector3<T> const& origin, Vector3<T> const& normal, Vector3<T> const& extent, Result& result) { T const zero = static_cast<T>(0); T dmin = -Dot(normal, extent + origin); if (dmin >= zero) { result.closest[0] = -extent - dmin * normal; result.closest[1] = -extent; } else { T dmax = Dot(normal, extent - origin); if (dmax <= zero) { result.closest[0] = extent - dmax * normal; result.closest[1] = extent; } else { // t = dmin / (dmin - dmax) in [0,1], compute s = 2*t-1 T s = static_cast<T>(2) * dmin / (dmin - dmax) - static_cast<T>(1); result.closest[0] = s * extent; result.closest[1] = result.closest[0]; } } } static void DoQuery2D(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& origin, Vector3<T> const& normal, Vector3<T> const& extent, Result& result) { T const zero = static_cast<T>(0); T dmin = -( normal[i0] * (extent[i0] + origin[i0]) + normal[i1] * (extent[i1] + origin[i1])); if (dmin >= zero) { result.closest[0][i0] = -extent[i0] - dmin * normal[i0]; result.closest[0][i1] = -extent[i1] - dmin * normal[i1]; result.closest[0][i2] = extent[i2]; result.closest[1][i0] = -extent[i0]; result.closest[1][i1] = -extent[i1]; result.closest[1][i2] = extent[i2]; } else { T dmax = ( normal[i0] * (extent[i0] - origin[i0]) + normal[i1] * (extent[i1] - origin[i1])); if (dmax <= zero) { result.closest[0][i0] = extent[i0] - dmax * normal[i0]; result.closest[0][i1] = extent[i1] - dmax * normal[i1]; result.closest[0][i2] = extent[i2]; result.closest[1][i0] = extent[i0]; result.closest[1][i1] = extent[i1]; result.closest[1][i2] = extent[i2]; } else { // t = dmin / (dmin - dmax) in [0,1], compute s = 2*t-1 T s = static_cast<T>(2) * dmin / (dmin - dmax) - static_cast<T>(1); result.closest[0][i0] = s * extent[i0]; result.closest[0][i1] = s * extent[i1]; result.closest[0][i2] = extent[i2]; result.closest[1] = result.closest[0]; } } } static void DoQuery1D(int32_t i0, int32_t i1, int32_t i2, Vector3<T> const& origin, Vector3<T> const& extent, Result& result) { result.closest[0][i0] = origin[i0]; result.closest[0][i1] = extent[i1]; result.closest[0][i2] = extent[i2]; result.closest[1][i0] = clamp(origin[i0], -extent[i0], extent[i0]); result.closest[1][i1] = extent[i1]; result.closest[1][i2] = extent[i2]; } static void DoQuery0D(Vector3<T> const& origin, Vector3<T> const& extent, Result& result) { result.closest[0] = origin; result.closest[1][0] = clamp(origin[0], -extent[0], extent[0]); result.closest[1][1] = clamp(origin[1], -extent[1], extent[1]); result.closest[1][2] = clamp(origin[2], -extent[2], extent[2]); } }; }
Unknown